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.
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.
Every command in this guide runs from <checkout>/packages/migrator on the migration box, through the built CLI. Define it once per shell:
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.
- A built migrator on the customer box.
dist/cli.jsexists, and$M lifecycle --helplists--from-config. If it does not, you cannot fix it on an offline site (02 Install & Build needs the network): bring a prebuilt copy, see Bring the migrator to an offline box below. - A terminal the TUI accepts.
tmuxis installed. You connect withssh -t.tput colsprints 80 or more. TheCIenvironment variable is not set. Without all four, the TUI falls back to plain CLI output. - Source access. A read-only MSSQL login, and the exact names of the two source databases (
SOURCE_SURVEY_DBandSOURCE_APP_DB). - Target access. The
TARGET_PG_*values andTARGET_PG_SSLfor the target PostgreSQL. - The customer has signed up in the product. The signup project has a neutral name (not the name of any source department): the first department you provision (the lowest id in your list) takes this project over and renames it.
CLIENT_ENVis the production environment id of that project, the id in the product URL/environments/<id>/surveys. - The base config file (one
.envfor the client, see 03 Configure) exists and ischmod 600. If the customer uses the Hub, it already holdsHIVECFM_HUB_URLandHIVECFM_HUB_API_KEY: provision copies the base file into one.envper department and never overwrites an existing file, so a Hub key added to the base later does not reach the departments. - The base registry entry exists in
.migrate/targets.json(example below). Itstieris the real tier, which isprodat a customer: it decides the tier of every department entry and how every confirm asks. Itsidis lower-case letters, digits and-, starts with a letter or digit, and is at most 31 characters, for examplestcbh. The department entries and files are named from it (stcbh-1-main-department,.env.stcbh-1-main-department), and the production token you type at a confirm is the id in capitals plus four digits (STCBH-4821). An id with capitals or other characters is converted for the department names (STC-BHgives.env.stc-bh-…), so the<base id>in this guide's commands would no longer match them. It has nodepartmentIdand no notes that name a department. ItsconfigFileis an absolute path, and every shell command's--from-config <base.env>must be written exactly as thatconfigFile: the CLI compares the text and does not resolve paths, so another spelling fails withE-LIFECYCLE-SCOPE-01(lifecycle) orE-RESET-SCOPE-01(reset-client). - The department list is decided. Run the per-department count query for your source type in 06 (surveys and customer surveys per department; it says how to connect and which of the two queries applies). Write down the ids to migrate. Leave out a department with 0 surveys and 0 customer surveys. A department with surveys but 0 customer surveys is a blocker: report it to the migration owner.
- Channel types. If some source channels must not become type
web,config/channel-mapping.<environmentId>.json(or the sharedconfig/channel-mapping.json) names them. See channel mapping. - Disk space on the target for about twice the data, plus room for the provenance export on the box. Lifecycle logs are never deleted automatically.
- Cutover owner. You know who stops writes to the source system at cutover, and when. The finalize stage (L7) needs it.
- Shared target database? If another client lives in the same database, retire (L8) is database-wide: it refuses until every client in the database is finalized. Agree the order with the other client's owner.
- Keep two directories for the life of the client:
.migrate/lifecycle/(the state; reset needs it) andprovenance/(the only record of which source row became which target row after retire). - Rollback plan. A migrated environment can be rolled back only before retire (10). After retire, the only way back is L10 reset-client, and only before the customer goes live.
{
"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.
- 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 undernode_modulesare absolute paths, so a copy unpacked anywhere else can load the wrong files, or none. - Pack it (tar keeps the links):
tar -czf hivecfm-migrator-<build>.tgz -C /opt/hivecfm hivecfm-core. Leave out every.envfile and the.migrate/directory of your own machine. - Copy and unpack at the same path:
scp hivecfm-migrator-<build>.tgz <user>@<migration box>:, then on the boxsudo mkdir -p /opt/hivecfm && sudo chown $USER /opt/hivecfm && tar -xzf hivecfm-migrator-<build>.tgz -C /opt/hivecfm. - Check it with the commands below. Every line must give the expected answer before you go on.
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
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. PressN(oresc).Interrupted run detected in _MigrationCheckpointwith a table list. That is a single-environment run left over from the advanced path. For a lifecycle client, pressN: the Lifecycle screen resumes its own stages. PressRonly 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).
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
| Key | What it does |
|---|---|
| ↑ ↓ | Move the highlight. |
| r | Re-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. |
| enter | Select 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. |
| x | Expand or collapse the client row, to see or select one department. You do not need this for the lifecycle. |
| l | Reload .migrate/targets.json now, for example after an edit from a shell. |
| n / e | Add 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. |
| esc | Go 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'senvironmentIdis not in the target. Fix it intargets.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 row | What 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):
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.
The Lifecycle screen and every key
Read this once. Every later section says "press enter" and assumes you know what the screen shows.
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.
▸ 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>, thenconfig <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 stageenterruns 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) orquarantine ?(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
| Key | What it does |
|---|---|
| enter | Runs 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. |
| a | Arms 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). |
| d | Sets 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. |
| o | Opens the options panel (next table). |
| h | Re-runs a skipped hub-backfill (L6). Shown only while hub-backfill is skipped, also after the lifecycle is complete. |
| r | Re-reads the state file and the lock. |
| esc | Goes 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.
| Row | Meaning | Default |
|---|---|---|
| --parity-retries | Extra delta + parity rounds per department before verify fails. 0 to 5. Sent to verify only. | 2 |
| --approve-quarantine | QUARANTINE 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_extras | Accept 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-tail | Let 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 confirm | What you see → what you do |
|---|---|
| prod | Type <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. |
| uat | Type APPLY to authorize: → type APPLY, then enter. |
| dev / local | Proceed? [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>(1h05m00sfrom 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
entertwice 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 pressr.
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 sendkill -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 -INTends 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--resumeby itself.
Where things are written
| Path (under packages/migrator) | What |
|---|---|
| .migrate/lifecycle/<base id>.json | The lifecycle state: each stage, each department, accepted checks, Hub push times. Reset (L10) needs it. |
| .migrate/lifecycle/<base id>.lock | Held 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). |
Stages 1–3: open-program · provision · preflight
Take the lease, create one environment per department, check each department. Set [d] before provision.
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] backStage 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.
- 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 asallprovisions every department the source reports, empty ones too. - 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 theDepartment → Environment map. - 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. - 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 600that 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
enteragain. Provision is incomplete for <cfg>: department(s) … have no registry entry …(after a forced stop): pressenteragain. 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 theSELECTit prints (must return 0 surveys and 0 contacts), delete that project as it says (Delete Workspace in the product, or the guardedDELETEit prints), thenenter. If theSELECTis not 0 and 0, stop and ask the owner.- A wrong department id in
[d]fails the preview; nothing is saved. Fix[d]and pressenter.
CLI The lifecycle passes the base entry's tier and id itself:
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
Stages 4–5: dry-run · run
Rehearse every department, then migrate every department. The run also merges language siblings.
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, pressenter. A department whose run was stopped continues with--resumeby itself. E-RUN-RESUME-01(rows already exist without--resume): pressenteragain; 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 ?:
escto the Menu. In Environments,xon the client row, select that department,esc.- Menu →
consolidate-languages. The firstenteris a dry run: it showsAUTO_MERGE N,QUARANTINE N,UNMERGEABLE N. - Read the QUARANTINE groups in
reports/consolidation-<env>-<time>.md(lessin a second tmux window). Each group has agroup:line, its fingerprint. Decide for each group whether its surveys are the same survey in different languages. - Only if every QUARANTINE group in the report should merge: press
a, thenenter.[a]arms all QUARANTINE groups of the report (this screen has no per-group choice), andenterapplies at once, with no typed confirm. If any group must not merge, do not pressa: run the CLI below with only the fingerprints you approve. - Go back to the client row and Lifecycle.
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.
Stage 6: verify
For each department: catch up with a delta, then compare source and target (parity). Repeats up to 1 + parity-retries rounds.
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), runsrun --resumeonce 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.
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 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
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_backfill | Responses 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 id | Late 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-01 | The 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-01 | The 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 else | real 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.
CLI (one department by hand)
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.
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 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'sEnvironmenttable (E-HUB-ENVNF-01; checkCLIENT_ENVin that department's.env). Fix it and pressenter; 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--untilone command would go on to export, retire and census. This works only while no department ispushed to the Hub: finalize pushes every pushed department again and stops if the Hub is down. Afterwards the screen keeps▸ ✗ hub-backfilland[enter] run next stage (hub-backfill), and it never saysMigration completeuntil the push is done. When the Hub is back, pressenter: hub-backfill pushes, then the lifecycle goes on to export, retire and census as usual (L8).hdoes 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 presshon the Lifecycle screen (works before and after retire). If hub-backfill failed instead,hdoes 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.
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.
- 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.
- Press
enter. The preview runsfinalize-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. - 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. - 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-stagingpreview, thenfinalize-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 lifecyclealso printsdept N: running a final delta before finalize — re-checks the source at cutover; the screen does not.)
.migrate/lifecycle/logs/<base>/finalize-dept<N>-finalize-staging-<time>.log. (Target host and user painted over.)finalize-staging --apply.What you should see ✓ finalize, every department finalized yes, ▸ on export.
If not
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 see | What to do |
|---|---|
| Not finalized: the source is still taking writes | Best: 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 verify | The 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 failed | Nothing 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-01 | The source lost rows this environment migrated. Do not finalize; escalate (L5, L9 escalation kit). |
$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).
Do not press enter on export / retire now. Next:
- 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. - Switch the application / DNS to the new platform and run the smoke test (08 Go Live).
- 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).
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.
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.
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:
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. > _
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.
enteron 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 existingmanifest.json), run$M export-provenance --config <base.env> --out ./provenance/<base id>, then pressenteron retire. Keep the moved-aside copy too. - The message says
provenance changed during retirement: arunordeltawrote 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 pressenteron retire. - A refusal naming a tenant that is not finalized: another client in the same database must be finalized first (L0).
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.
[h] (or run the printed command) once HIVECFM_HUB_URL / HIVECFM_HUB_API_KEY are set in each department .env.Lifecycle troubleshooting
Find the text you see in the left column. Every row came from a real run.
| You see | What 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 Menu | Read 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 client | Check 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 created | Cannot 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 finishes | Your 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-01 | First 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-01 | Only 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 --resume | The 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-01 | Real 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 --resume | In 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 data | Run verify first. |
| Not finalized: the source is still taking writes | Stop 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 nothing | Press y. |
| E-PROV-02 Provenance would be dropped without an export | Two 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 zero | Collect the escalation kit (below) with the census output. Do not drop anything by hand. |
| quarantine ? on a department | The count was not recorded. Dry-run Consolidate languages for that department to see (L4). |
A shell lifecycle sat waiting after a stage | It 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 dropped | ssh -t …, then tmux attach -t <client>. Never start a second TUI to see the screen. |
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-*.htmlandreports/consolidation-*.mdof 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.
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
lifecyclerow 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], uatAPPLY, 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.
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.
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.
- Run it from the directory where the lifecycle ran (
packages/migrator). It reads.migrate/lifecycle/<base id>.jsonfor 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'sconfigFilein.migrate/targets.json. - Dry run:
$M reset-client --from-config <base.env>. ReadOrganization,Environments,Cutoff,Upper bound, the steps,Protected (other organizations, …)and theHubline. It endsDRY RUN — nothing was changed. - Hub: if the
Hubline 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. - Apply:
$M reset-client --from-config <base.env> --apply --confirm-org "<exact organization name from the dry run>", plus--acknowledge-hub-pushwhen 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. - Result:
✓ Registry: removed N department entries, moved M file(s) to .migrate/archive/reset-<time>. Base entry "<id>" kept.andNext: 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]).
| Refusal | Meaning → what to do |
|---|---|
| E-RESET-STATE-01 | The client is not retired (migration tables or columns exist). Run $M census --config <base.env>, then see Start over before retire. |
| E-RESET-SCOPE-01 | First 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-01 | Something 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.
- Take the organization id from the reset dry run:
Organization <name> (<organization id>). - Get the Hub API address and the Hub server's own API key (its
API_KEYsetting) from whoever deployed the Hub. Call the Hub API itself, not the public gateway: the gateway does not route/v1/tenants/…. - Count, purge, then count again until it reads 0:
202: accepted. The Hub's worker deletes in the background; repeat the count every minute or so.404on theDELETE: this Hub build has no purge. Do not push the re-migration: leaveHIVECFM_HUB_URL/HIVECFM_HUB_API_KEYout 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").
The same migration from a shell
lifecycle is the CLI behind the Lifecycle screen. Same state file, same stages, same order.
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.
| Flag | Required | Description | Default |
|---|---|---|---|
| --from-config <path> | REQ | The client's base config. Its registry entry is the base entry. | — |
| --departments <ids> | opt | Departments to provision, e.g. 1,3,4,5. Used by provision only. | every department |
| --from-stage <stage> | opt | Start 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> | opt | Stop after this stage. | census |
| --yes | opt | Asks 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> | opt | survey_channel_coverage and/or contact_target_extras only. | none |
| --parity-retries <n> | opt | Extra delta + parity rounds per department. | 2 |
| --export-dir <dir> | opt | Where export writes. CLI only. | ./provenance/<base id> |
| --skip-dry-run | opt | Skip the dry-run stage. Not recommended. CLI only. | false |
| --max-workers <n> | opt | Forwarded to every department's run (parallel Phase 3). CLI only. | serial |
| --approve-quarantine <fps> | opt | QUARANTINE fingerprints for every department's run. | none |
| --accept-live-tail | opt | Let finalize go ahead over rows the source took after its final delta. Recorded. | false |
| --status | opt | Print the state and the next stage; run nothing. CLI only. | false |
| --preview | opt | With --from-stage S --until S for provision, finalize or retire: run only the preview. | false |
What each stage runs (the manual-path map)
| Stage | Command(s) the lifecycle runs |
|---|---|
| open-program | open-program --config <base.env> |
| provision | provision-departments --client <anchor env> --config <base.env> --write-config --tier <base tier> --id-prefix <base id> [--departments …] (preview adds --dry-run) |
| preflight | preflight --client <dept env> --config <dept .env> --department N per department |
| dry-run | run --client <dept env> --config <dept .env> --department N --dry-run --consolidate-languages apply --skip-hub-backfill |
| run | the same without --dry-run (--resume added for a stopped department) |
| verify | per 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-backfill | hub-backfill --client <dept env> --config <dept .env> |
| finalize | in 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 |
| export | export-provenance --config <base.env> --out ./provenance/<base id> |
| retire | retire-migration-program --config <base.env> --confirm --provenance-manifest ./provenance/<base id>/manifest.json [--apply] |
| census | census --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.
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.
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.
| When | What happens | Window |
|---|---|---|
| T−7d | Bulk 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−0 | Cutover. 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…+4h | Rollback 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+30d | Archive 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) |
Glossary
The vocabulary the rest of this guide assumes.
| variant | A known shape of the legacy schema. Three are recognized: StableRJB (newer, has Touchpoint family), ISTServiceEdge (older, no Touchpoint), Custom (unknown, the migrator aborts). |
| legacyId / legacyGuid | Optional nullable columns on target tables that hold the original MSSQL primary key. Fresh clients have NULL; migrated rows carry the source ID for traceability. |
| additivity | Every 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. |
| idempotency | Re-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. |
| cutover | The maintenance window where the client switches from legacy MSSQL to PostgreSQL. Target 1 hour; FR-019 hard maximum 2 hours. |
| delta | Incremental migration of rows changed since the T-7d bulk snapshot. Timestamp-based for StableRJB (uses LastModifiedDate); ID-based for ISTServiceEdge (uses max(ID)). |
| parity | Five validation checks: row count, sample field, FK integrity, KPI aggregate, schema diff. Produces an HTML report with per-table pass/fail. |
| chunked copy | Phase 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 lock | PostgreSQL session-level lock the migrator acquires per (client, run). Prevents two concurrent migrations of the same client. |
| checkpoint | Row in _MigrationCheckpoint tracking the last successfully-written legacy_id per table. Resume reads this to skip already-done rows. |
| materialized view | mv_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). |
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
Does your source DB have a CFMTouchpoint table?
Does CFMSurveyInvitation have a LastModifiedDate column?
Does CFMResponseKPICache exist?
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.
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.
Pipeline deep-dive — 10 phases
What runs in each phase, what mode it uses, expected duration, and how it recovers if interrupted.
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.
| Phase | Mode | Small (<10k) | Medium (10k–500k) | Large (500k+) | Recover |
|---|---|---|---|---|---|
| 1 · Lookups | per-row upsert | <30s | <1m | <2m | --phase=1 --resume |
| 2 · Entities | per-row upsert | 1–3m | 5–15m | 20–40m | --phase=2 --resume |
| 3 · Transactional | chunked COPY + ON CONFLICT | 3–10m | 30m–2h | 2–6h | --phase=3 --resume |
| 4 · KPI | compute + MV refresh | 1–2m | 5–10m | 15–30m | --phase=4 --resume |
| 5 · Validate | read-only checks | <1m | 2–5m | 5–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.
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.
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.
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;| Failure | What actually happens |
|---|---|
| Kill mid-chunk | Transaction 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 writes | Re-encountered rows hit the UNIQUE constraint, ON CONFLICT DO NOTHING. Silent skip, no error. |
| Re-run after success | Checkpoint marks the table complete. Phase 3 reads 0 source rows and writes 0 target rows. |
| Network drop mid-COPY | The TEMP table is session-scoped: dropped automatically. Checkpoint unchanged. Resume re-streams the same chunk. |
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.
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 models | Temp / scratch table | |
|---|---|---|
| Example | Contact, Channel, Response (+ new columns) | tmp_Response |
| Created by | the 5 Prisma migrations — once, up front | the migrator — per chunk, at runtime |
| Lifetime | forever (part of the live app) | one transaction (ON COMMIT DROP) |
| Purpose | give legacy data a permanent home | load fast + dedupe safely |
| Holds data? | yes — the final resting place | yes — 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.
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.
| Table | Why it was added (2026-05) | Status now (2026-08-31, live-verified) |
|---|---|---|
Touchpoint | Region→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. |
TouchpointType | Classifies touchpoints. From CFMTouchpointType. | Dropped 2026-08-24, same migration & evidence as Touchpoint. |
SurveyTouchpoint | M2M 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. |
SurveyTouchpointType | M2M bridge, surveys↔touchpoint types. | Dropped 2026-08-20, same migration & evidence. |
Department | Organisational 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. |
CustomerOrg | Customer organisations. From CFMCustomerOrg. | Dropped 2026-08-24 (20260824000000). 0 rows — the ISTServiceEdgeOld source variant has no CFMCustomerOrg table at all. |
Invitation | Survey 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. |
ResponseAnswer | Individual 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. |
SurveyChannel | Delivery 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). |
LegacySurveyKind | Preserved 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. |
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:
| Table | Columns added by the migrator, originally | Still present 2026-08-31 |
|---|---|---|
Response | touchpoint_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. |
User | touchpoint_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). |
Survey | legacy 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
-- 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
-- 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:
- Read. The migrator streams
CFMSurveyResponserows fromHiveCFMSurveyDB-*in--chunk-sizebatches (default 500). - Transform. Each source row is mapped to target columns. The source PK is copied into
legacy_id; the source GUID intolegacy_guid; unmapped source columns are stashed inlegacy_extras(nothing is silently dropped) — this is what makeslegacy_guid/legacy_extrasthe sole surviving invitation identity now thatInvitationitself is gone. - Stage. The batch is
COPY-ed (TSV) into the throwawaytmp_Responsetable — the loading dock from subsection (a). - Land + dedupe.
INSERT … SELECT … FROM tmp_Response ON CONFLICT ("legacy_id") DO NOTHINGmoves rows into the permanentResponse. Any row already present (from a prior interrupted run) is silently skipped. - Checkpoint.
_MigrationCheckpointadvances in the same transaction, so data + progress commit together.tmp_Responseis dropped atCOMMIT. (_MigrationCheckpointitself is one of the 8STAGING_TABLES— see the callout below.) - Answer projection (Phase 4).
ensureResponseAnswerTable()creates theResponseAnswerstaging table on demand if it doesn't exist, thenbackfill-survey-structure.tsprojects each answer'slegacy_extrasonto the correspondingResponse.datakey.Response.datais the permanent, product-facing copy;ResponseAnsweris scratch that outlives one transaction (unliketmp_Response) only until this tenant is finalized. - Score (Phase 4).
kpiScoresis 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.
ResponseAnswer can vanish and reappear, and eventually vanish for goodResponseAnswer 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.
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:
- 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. - The pool — how many partitions run at once.
--max-workers, default 1 (serial). It also bounds source connections, target connections and memory simultaneously. - 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).
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 table | LastModifiedDate column | CFMResponseKPICache table | Variant | Delta strategy |
|---|---|---|---|---|
| present | present | present | StableRJB | timestamp |
| absent | (any) | absent | ISTServiceEdge | id |
| any other combination | Custom | abort (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.
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.
- Node.js 20 LTS. Run
node -v, must showv20.x - pnpm 9+. Run
pnpm -v - Network access to MSSQL. The source host is reachable from the migration box. Test with
nc -zv <source host> 1433 - PostgreSQL credentials. Connection string for the target
hivecfm_<client>database - Environment ID. The
idof the existingEnvironmentrow in Postgres for this client - Product schema applied, migration objects absent. The target database already has the product's schema (the product's own install or upgrade applies it; on a developer box, 02 step 7). Check it is the schema this migrator build expects:
psql "host=<host> port=<port> dbname=<database> user=<user> sslmode=require" -c "SELECT migration_name FROM _prisma_migrations WHERE migration_name LIKE '20260925120000%' AND finished_at IS NOT NULL;"must return 1 row (usesslmode=disablewhenTARGET_PG_SSLis false). 0 rows: the product on the target is older than this migrator build; stop and ask the owner for matching builds. The migration-owned objects are expected to be absent on a fresh database: the lease table_migrator_program_lease,_MigrationCheckpointand the other staging tables, and thelegacy_id/legacy_guid/legacy_extrascolumns. open-program creates the lease (L3), the first run creates the rest under it (L4), and retire drops them all (L8). Never rundb:pushagainst a customer database: it runs--accept-data-lossand can drop migration-owned objects. - pg_cron extension enabled. Phase 4 requires it. Ask the DB admin or check:
SELECT * FROM pg_extension WHERE extname = 'pg_cron';
The migrator never writes to the source MSSQL databases. It only reads. Even so, use a read-only SQL login; never SA credentials.
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).
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 iteration5d2fa1059— fix(db): add@default(cuid())to 8 migrator lookup models4fa0fd258— fix(migrator): VariantDetector recognizes ISTServiceEdgeOld7595aa93a— fix(license): re-sync dev keypair between activation script and embedded public key5b3a52fb0— fix(auth): make signup resilient to license-signing failureda681292c— fix(db): add 10 migrator model definitions to schema.prisma9b983fcd6— fix(migrator): preserve real email + password on user upsert re-run (never overwrite with synthetic)af4b48920— fix(migrator): auto-activate dev licenses + auto-discoverCLIENT_ENVaftermigrate 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):
- Non-blocking email:
sendVerificationEmailis now wrapped in try/catch (commit5c41baf). SMTP failure logs a warning and signup continues — the user always gets a fully linked account. - Automatic org repair:
no-workspace/page.tsx(commit1fc406f) checks org membership after verifying the session. If the authenticated user has zero orgs, it auto-creates one, creates the owner membership, and redirects to the dashboard. No manual DB edits required. - Double-submit guard: the signup submit button is disabled while the request is in-flight (
disabled={!isValid || isSubmitting}, commit9a08ba1), preventing concurrent duplicate requests that could race to create duplicate orgs.
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:
- Start the Hive web app —
pnpm dev, or on EC2:sudo systemctl start hivecfm-web. - Sign up once — open
http://<host>:3000/auth/signupand create a new account. The app auto-creates an Organization and its default Project + Production/Development Environments. No need to runactivate-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 commit5c41baf) — log in directly. Multi-department source: give the project a neutral name (not anyCFMDepartment.Name), see 06. If this stack has a Hub and you need Hub-side tenant features, restart thehivecfm-corecontainer after signup: an organization created by UI signup is only registered as a Hub tenant at container start. Phase 6 /hub-backfilldoes not need that registration (see 07a). - Get the Environment id — optional since commit
af4b48920:migrate runauto-discovers the production environment ifCLIENT_ENVdoesn'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 intopackages/migrator/.envasCLIENT_ENV=<id>. - Run preflight —
node dist/cli.js preflightfrompackages/migrator/. All checks should be green. - 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.
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
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.
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.
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.
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.
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.
Run the full migration (includes audiences)
Standard full migration. Phase 2.6 runs between Phase 2 (Entities) and Phase 3 (Transactional).
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.
Dry-run audiences (no writes)
Validates source data and prints a plan. Safe to run at any time.
Apply audiences (write)
Runs Phase 2.6 in isolation — idempotent, safe to re-run.
3. Per-contact response history report
Generate contact-history report
Produces a CSV + HTML report showing each contact's response history. Useful for QA and for client hand-off evidence.
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.
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.
Finalize audiences (drop tracking columns)
One-shot cleanup at the very end of the migration project.
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 caveatRollback 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.
Roll back audience data only
Removes segments + membership attributes. Leaves contacts, responses, and channels intact.
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.
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.
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.
Open WSL Ubuntu (Windows only)
Skip this step on macOS or Linux. From PowerShell, drop into your WSL shell.
Enter the repository
Adjust the path to wherever you cloned. The example assumes F:\ISt\HiveFormbricks\hivecfm-core on Windows.
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.
Install workspace dependencies
Run from the repo root. pnpm picks up every workspace under packages/ and apps/.
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.
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.
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.
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).
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.
Configure .envrequired
One config file per client. Five short steps. Each card below has its own copy button.
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).
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.
Copy the .env template
One file per client. Name it after the client so you can keep multiple side-by-side.
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.
.env variable groups · paste into the file above
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:
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.
=true only for self-signed-cert dev boxes (never in production).docker compose port postgres 5432TARGET_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.
cmpa6qyqp0008p301k7mdo311. NOT a slug like ist-serviceedgeThe 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 pasteclseedenvprod000000000,clseedenvdev000000000, or anyclseed*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 envclseedenvprod000000000is 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.
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).
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.
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.
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.
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).
Now any Prisma command runs against any environment by pointing at the matching file:
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.
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.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Target 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-run | opt | Report what would be created without writing | false |
| --departments | opt | Comma-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 |
| --config | opt | Base .env (source + target credentials, CLIENT_ENV). Generated department files copy it. | $ENV_FILE, else ./.env |
| --write-config | opt | Write 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 |
| --tier | opt | Tier 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-prefix | opt | Namespace 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 |
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).
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:
- Check — read-only preflight. Writes nothing.
- Rehearse — a dry-run that simulates the entire migration. Writes nothing.
- Run — the one step that writes real data, and only after you type a confirmation word.
- 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.
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.
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.
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.
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.
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.
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.
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.
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
- Pick your client. You start on the Dashboard — on a first launch every field reads
unknownbecause nothing is selected yet:
Pressno 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 [?]helpe→ the Environments list opens.- If your client is already listed (it reads from
.migrate/targets.json— see the schema above): highlight it with↑/↓and pressEnter. A secondEnteris needed only on a row marked⚠ unverified(⚠ not yet verified — press [r] to re-check it, or enter again to select <label> anyway.); preferr, whose result is saved in.migrate/registry-status.jsonand restored for 24 h. A multi-department client shows one row,Client — <client> (N depts);Enteron it selects the client forlifecycle, and this single-environment flow needs one department:[x], thenEnteron the department. PressEscto return to the Dashboard. - On a fresh checkout the list is empty — this is the normal starting state, not an error:
Presstier label env-id status No environments registered. Press n to add one. [enter] select [n] new [e] edit [r] re-check [d] detailsnand fill inid,label,tier,configFile(the absolute path to your.envfrom 03 Configure) andenvironmentId(the targetEnvironment.idCUID). The editor writes no.envfile: create it first.trunsSELECT 1 FROM "Environment" WHERE id=$1through that file, so it needs a cuid-shapedenvironmentIdand aconfigFilewith a fullTARGET_PG_*block.ssaves oncetpassed. Hand-editing.migrate/targets.jsonworks too; press[l]in Environments to reload it (no restart needed).
- If your client is already listed (it reads from
- 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 warnings0 blockerswith checks still markeddeferredis the expected, normal result — presspto proceed. Nothing is written at this stage. - 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:
PressImpact (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-phaseEnterto run it — it simulates the whole migration and writes nothing. While it runs, the screen showsRunning 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. - Stage 3 · Run (the only write). After a clean dry-run, press
p. The Confirm screen depends on the tier: prod showsType <TOKEN> exactly as shown, then press enter.(case-sensitive; a wrong attempt makes a new token); uat asks you to typeAPPLY; dev/local showsProceed? [y/N]: pressy(enterdoes 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. - Stage 4 · Verify. The Completion screen's keys do nothing except
esc. Pressescto the Dashboard, thenv→ Parity compares source and target and flags any mismatch.
The only keys you need
| Key | What it does |
|---|---|
e | Open Environments — pick your client |
r | Start the flow: Check → Rehearse → Run |
↑ ↓ | Move the highlight |
Enter | Choose / run the highlighted item |
p | Proceed 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. |
Esc | Go back one screen · on the Run monitor, detach (the run keeps going). On the Lifecycle screen esc is refused while a stage runs; use ←. |
v | Verify (Parity) |
s | Resume / status — only if a run stopped |
g or : | Command palette |
? | A fixed "Global keys" overlay (some keys listed there do nothing) |
q | Quit. 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.
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.
- Preflight:
[enter] proceedstays(blocked)because the TUI runs only 3 of the 12 checks; usep(proceed anyway). The full gate is the CLIpreflight. - Plan & dry-run: the single-phase selection (
[P]) cannot be cleared; leave and re-enter the screen. - Confirm: on dev/local,
enterdoes nothing; pressy. - Pause overlay: every key only closes it (see the key table).
- Completion:
[P],[H],[o]and[enter]do nothing; onlyesc. 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 resetstenancyto single and drops its department binding. - Rollback screen: the dry-run impact list is always empty; run
rollback … --dry-runin 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.
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-workersruns 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 withhub-backfillper 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
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; onlyescworks. Pressesc, thenvon 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.
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.
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).
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.
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:
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".
What preflight checks:
- MSSQL connectivity (AppDB and SurveyDB)
- PostgreSQL connectivity and migration version
- Required tables present in source (
CFMUser,CFMSurveyResponse, etc.) - Schema variant detection:
StableRJBorISTServiceEdge - Row count estimates per table
- Advisory lock availability (confirms no other migration is running)
- Target environment ID exists
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.
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.
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:
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.
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 state | What to pass | What happens otherwise |
|---|---|---|
| never-opened — no lease, no migration-owned tables | Nothing. The ordinary path takes no flag on purpose: making the common case ceremonial is how flags stop being read. | — |
| open — lease already present | Nothing. | 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.
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.
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).
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.
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.
- Sign up in the UI and give the project a neutral name (see below). Copy the production environment id from
/environments/<id>/surveys. - Put it in the base config (
.env.<client>-base) asCLIENT_ENV. open-program, thenpreflight(04).- 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.
provision-departments --dry-run --write-config, read the map, thenprovision-departments --write-config(step 1).- Check that the generated
.env.*files read-rw-------(ls -l .env.*; provision writes them 0600). run-all-departments --open-program --dry-run, thenrun-all-departments --open-program(steps 2a and 2b, launched withNODE_OPTIONS=--import=tsx; this applies torun-all-departmentsonly: the lifecycle adds--import tsxto its own children).parity --client <env> --config .env.<dept> --department Nfor each department (07).
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.
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).
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.
--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.
--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.
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.
--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:
Running N department(s) in sequence— the detected list, each with its environment.- The gate:
open-program, thenpreflight --department Nfor 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). - 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. All N department(s) completed.A department failure stops the sequence (add--continue-on-failureto carry on) and names the department; recover that one alone withrun --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-quarantinefor 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).
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.
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.
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.
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.
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.
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."
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.
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.
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.
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"
-tis not optional for these. It forces a TTY, which is whattail -f,watchand any password prompt need; without itwatchexits immediately.- Check the host octet-by-octet. A truncated address (
…26.13instead 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.errand~/AG/run.ndjsonare this rehearsal's; substitute your own.run.ndjsonis the machine-readable event stream —grep phase_doneit for per-phase durations and row counts. /tmp/track2.shis a helper script, not something the migrator ships. Write your own, or read_MigrationCheckpointdirectly with the query above.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment identifier (the cuid in CLIENT_ENV in .env) | CLIENT_ENV |
| --config | opt | Path to the .env file for this client (for a department: its own .env) | reads env vars |
| --dry-run | opt | Run without committing any writes | false |
| --resume | opt | Skip guard check for non-empty target, resume from checkpoint | false |
| --phase | opt | Run only a specific phase (1–5) | all |
| --chunk-size | opt | Rows per COPY batch. Lower for slow connections. | 500 |
| --migrate-users | opt | Write legacy User/Membership rows. Off by default since b9b107b77 — see the callout below. | false |
| --consolidate-languages <mode> | opt | apply 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 |
| --department | opt | Migrate only this legacy department (required on a multi-department source). | whole tenant |
| --max-workers | opt | Phase 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 |
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 nowIt 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.
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.
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.
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.
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.
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.
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).
| Check | What to do |
|---|---|
row-count:… in the window | A 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 line | Pending, 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_extras | Check 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_backfill | Another delta relinks them, or $M backfill-response-contact-attributes --client <env> --config <.env>, then parity again. |
survey_channel_coverage | Source 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. |
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) andcontact_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
0for text/IDs,±0.001for 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.
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.
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).
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
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.
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.
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:
- Questions appear one at a time as each is answered — the old system showed the first group of questions at once.
- A one-page survey has no Back button — the old system also disabled Previous on classic web surveys.
- The response is written once at the end instead of once per page.
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.
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.
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.
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
\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 |
|---|---|---|---|
| Contacts | CFMCustomer | Contact | 252,372 |
| Surveys | CFMSurvey | Survey (legacy_id ≠ null) | 692 |
| Questions | CFMSurveyQuestion | Survey.blocks[].elements[] | 3,531 |
| Responses | CFMCustomerSurvey | Response | 1,087 |
| Answers | CFMSurveyQuestionResponse | ResponseAnswer | 3,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.
SELECT ID, Name, Phone, CustomerIdentifier, UserCIC, BirthDate, Gender, IsAnonymous, Email FROM [HiveCFMSurveyDBStableRJB].[dbo].[CFMCustomer] WHERE Phone = '502987999' ORDER BY ID;
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_id | ID |
name / firstName / lastName | Name (split on first space) |
phoneNumber | Phone |
userId | CustomerIdentifier |
userCIC | UserCIC |
birthDate · gender · isAnonymous | BirthDate · Gender · IsAnonymous |
email | Email (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.
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;
\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 |
|---|---|---|
nps | 8 (nps) | 629 |
rating | 6 (slide), 7 (star), 16 (emoji), 19 (csat), 21 (ces), 22 (numcsat), 23 (numces) | 1,470 |
multipleChoiceSingle | 3 (twochoices), 4 (list), 15 (singleCh), 18 (imgSingle), 20 (fcr) | 678 |
multipleChoiceMulti | 2 (mcq), 17 (imgMcq) | 283 |
openText | 5 (date), 9 (txtinput), 10 (numinput), 11 (emailinput), 12 (teleinput), 13 (postinput), 14 (urlinput), 24 (thumbsfcr), 25 (thumbscsat), 26 (thumbsces) | 471 |
| Total | 3,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.
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.
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 QUARANTINEThe 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 youSince 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:
| Context | Behaviour |
|---|---|
default (--consolidate-languages apply) | commits AUTO_MERGE without asking, in any context |
--consolidate-languages ask | y/N on an interactive terminal; report only in a pipe, CI or the TUI |
--consolidate-languages report | writes the report, merges nothing |
--consolidate-languages skip | no report at all (--skip-consolidate-languages is an alias) |
--dry-run | report 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)
$M consolidate-languages --client <dept env id> --config <dept .env>Step 2 — Apply (commit AUTO_MERGE + approved QUARANTINE groups)
$M consolidate-languages --client <dept env id> --config <dept .env> --apply \
--approve-quarantine "<group-key-1>,<group-key-2>"Real example — Zain Social EN/AR:
$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)
# Get the survivorId from the dry-run report, then:
$M unmerge-languages --config <dept .env> --survivor-id <survivorId>Step 4 — Finalize (permanently delete merge remnants — IRREVERSIBLE)
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.
$M finalize-consolidation --client <dept env id> --config <dept .env>$M finalize-consolidation --client <dept env id> --config <dept .env> --applyQuiz 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.
backfill-quiz-scoring is not a registered command on this branchThe 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.
The scoring columns are added by a Prisma migration. Apply it once on a fresh target before running the backfill:
cd packages/migrator
pnpm prisma migrate deployDry run (gap report)
$M backfill-quiz-scoring --client <env> --config <.env> --dry-runApply
$M backfill-quiz-scoring --client <env> --config <.env>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.
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.
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).
The cutover owner sets the legacy application read-only (outside this tool).
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.
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.
Load the client's survey list, open a recent response, verify KPI widgets show data.
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.
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.
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.
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.
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.
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.
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.
--sinceis 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.--departmentand--configare required for a department, and must be the same values its run used. Without--departmenta delta on a multi-department source is refused (E-DELTA-SCOPE-01) and writes nothing; pass the same--departmentthe 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 --resumewith the same--max-workersas 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--departmentand--configfirst. 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 > @sinceand freezes no line, so its parity keeps the strict boundary.
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.
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.
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.
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 againstSurvey) written between T-0 and the rollback moment. (Older guide versions also listedResponseAnswerandInvitationhere — checked againstpackages/migrator/src/reverse/replay-cutover-window.tsdirectly: it only ever touchesResponse/Survey.Invitationno 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, Postgreslegacy_idupdated. - 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
- Run with
--dry-run, confirm the row counts look right. - Run without
--dry-run(sample stdout:Replayed 1,204 rows; 3 conflicts logged; window 47 min of 240 min remaining). - Flip DNS /
DATABASE_URLback to MSSQL. - Redeploy the app pointing at MSSQL.
- Smoke-test the rollback (open a recent response, file a fresh ticket in your tracker noting the rollback timestamp).
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.
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
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.
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.
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 column | Confirmed 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 by | migrate open-program — and nothing else. Not run, not preflight, not a Prisma migration (04b) | migrate finalize-staging --client <env> --apply |
| Scope | The whole database (one row only, CHECK (id = true)) | One environment_id (PK column, one row per tenant) |
| What it gates | Everything 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 drops | No, never |
| Dropped by | migrate retire-migration-program --apply --confirm, in the same transaction as the 13 staging tables and the 10 migration-owned columns | Same command, same transaction |
| Reversible? | Yes, deliberately: migrate open-program --reopen-after-retirement --confirm | Not 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.
| Code | When retirement refuses | What to do |
|---|---|---|
E-PROV-01 | A 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-02 | Provenance 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-03 | preflight, 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-04 | Status, 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-05 | The 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
- Verify: parity passes for every environment, including
legacy_extras_hidden_field_coverage. If the source is live, run onemigrate deltafirst so the row counts close. - 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. - Export:
migrate --config <cfg> export-provenance --out <new empty dir>. It is read-only and takes no lease. It writes gzipped NDJSON per table plusmanifest.jsonwith row counts and sha256. It refuses a directory that already holds an export. Do not start anotherdeltabetween the export and step 5, or the counts will no longer match. - 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 thanbb98b273e, which under-counted. - Retire: the same command with
--apply. One transaction runsSET LOCAL lock_timeout, then the advisory lock, thenLOCK 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. - 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.
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-runagainst 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-zeroreturned 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.
- 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: runmigrate 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." Since9a5c77aa4,migrate runasks Gate 0 before Phase 1 writes (cli/run.ts), so a fresh database answers never-opened and getsE-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 withlegacy_id, which matches retired and printedE-LEASE-02on a database that was never migrated. If that is what you are seeing, yourdist/predates the fix: 04b. - Gate 1, pre-run, per tenant. Before
migrate runormigrate deltawrites for a client: does_migrator_tenant_finalizedalready hold a row for thisenvironment_id? If yes, refuses withE-TENANT-FINAL-01(assertTenantNotFinalized,target/staging-guard.ts). Idempotency does not cover this:ON CONFLICT DO NOTHINGprotects rows that already exist, whereas a delta exists precisely to add rows that do not. A--dry-runis 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". - Gate 2, pre-finalize, per tenant. Before
finalize-staging --applycommits: four refusals, each scoped to THISenvironment_idonly. (1) An incomplete_MigrationCheckpointrow (a phase stopped mid-way). (2) Unresolved_MigrationDeferredrows. (3) NoSurveyin this environment carries alegacy_id(almost certainly the wrong environment). (4) ASurveyhas alegacy_idbut Phase 4 never finished (purgingResponseAnswernow would make those surveys unrepairable). None can be overridden with a flag. - Gate 3, pre-retirement, program-wide. Before
retire-migration-program --apply --confirmdrops anything: everyenvironment_idthat ever appeared in_MigrationCheckpointmust also appear in_migrator_tenant_finalized, or it refuses and names which tenants are missing. Also refuses if_MigrationCheckpointitself 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.--confirmexists 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.
retire-migration-program alone, or with only --apply, is a REFUSAL, not a dry-runThe 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
- 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. - 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. - After retirement: all 13
STAGING_TABLESand 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. (Runningfinalize-audiences --drop-trackingbeforehand 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.
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.
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:
| Code | Means | What to do |
|---|---|---|
0 | Success, 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. |
1 | A 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. |
2 | Connectivity 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). |
3 | Source schema variant is Custom — neither StableRJB nor ISTServiceEdge. | Stop. See F4 Variant Decider; the transform layer has no mapping for a third shape. |
130 | SIGINT/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. |
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.
| Flag | Description | Default | |
|---|---|---|---|
| --from-config <path> | REQ | The client's base config; its registry entry is the base entry | — |
| --departments <ids> | opt | Departments to provision (provision only) | every department |
| --from-stage / --until <stage> | opt | Start at / stop after this stage. --from-stage hub-backfill is the only way to re-run a skipped hub-backfill | next pending / census |
| --yes | opt | Do 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> | opt | survey_channel_coverage, contact_target_extras only (the latter up to 50 per department) | none |
| --parity-retries <n> | opt | Extra delta + parity rounds per department in verify | 2 |
| --export-dir <dir> | opt | Where export-provenance writes | ./provenance/<base id> |
| --skip-dry-run | opt | Skip the dry-run stage (not recommended) | false |
| --max-workers <n> | opt | Forwarded to every department's run | serial |
| --approve-quarantine <fps> | opt | Forwarded to every department's run | none |
| --accept-live-tail | opt | Let finalize go ahead over rows the source took after its final delta (recorded in the state) | false |
| --status | opt | Print the state and the next stage; run nothing | false |
| --preview | opt | With --from-stage S --until S (provision, finalize, retire): run only the preview | false |
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.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --from-config <path> | REQ | The client's base config | — |
| --apply | opt | Commit the reset | false (dry run) |
| --confirm-org <name> | opt | Required with --apply: the exact organization name the dry run prints | — |
| --acknowledge-hub-push | opt | Required with --apply when the Hub may hold this client's responses; purge them first | false |
| --cutoff <iso> | opt | When the migration started, if no lifecycle state records it (from the first run's log) | lifecycle open-program stamp |
| --upper-cutoff <iso> | opt | When the migration ended (retire --apply), if no lifecycle state records it | lifecycle retire stamp |
| --anchor-name <name> | opt | Name to restore on the anchor project | recorded name |
| --project <id> | opt | Add a department project whose entry is gone (repeatable) | — |
| --keep-registry | opt | Do not archive the department entries and .env files | false |
Refusals: E-RESET-STATE-01, E-RESET-SCOPE-01, E-RESET-CONFIRM-01, E-RESET-DRIFT-01 (L10).
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.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Environment id (global flag) | CLIENT_ENV |
| --config | opt | The environment's .env | env vars |
Read-only. Compares current values against the baseline preflight captured before a scale-up and names every dimension still raised. CLI only.
| Flag | Description | Default | |
|---|---|---|---|
| --report <path> | REQ | Run report holding the preflight baseline | — |
| --observed <dimension=value…> | REQ | Current value per dimension, e.g. "target vCPU=8 vCPU"; every baseline dimension must be supplied | — |
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --config | opt | Path to .env config file | env vars |
| --verbose | opt | Show full column-level scan results | false |
| --allow-resume | opt | Skip "target non-empty" blocker | false |
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).
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.
| Flag | Description | Default | |
|---|---|---|---|
| --config | opt | Path to .env config file (target read from TARGET_PG_*) | env vars |
| --adopt-active-program | opt | Adopt 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-retirement | opt | Deliberately re-open a RETIRED database. Refused on an active one — reaching for it there means the state was misdiagnosed. Requires --confirm. | false |
| --confirm | opt | Required 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)
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --config | opt | Path to .env config file | env vars |
| --dry-run | opt | Simulate without writing | false |
| --resume | opt | Resume from checkpoint | false |
| --phase | opt | Run 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-size | opt | Rows per COPY batch | 500 |
| --department | opt | Migrate ONLY this legacy department id's surveys, plus reached contacts/responses/answers. Get the id from provision-departments (see 03b). | whole tenant |
| --allow-env-discovery | opt | If CLIENT_ENV is absent from the target, adopt its only production environment | false |
| --migrate-users | opt | Write 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-backfill | opt | Don't auto-run targeting backfill after Phase 5 | false |
| --skip-repair | opt | Don't auto-run Phase 2.5 (repair survey status/timestamps) | false |
| --skip-structure-backfill | opt | Don't auto-run structure + response-data backfill at end of Phase 4 | false |
| --skip-hub-backfill | opt | Don't auto-run Phase 6 (Hub push) at end of pipeline | false |
| --skip-audiences | opt | Skip Phase 2.6 (customer lists / CRM codes → Segments) | false |
| --drop-tracking | opt | After a successful run, drop the transient Segment tracking columns | false |
| --consolidate-languages <mode> | opt | apply|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> | opt | Phase 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-env | opt | Deliberately put every department of a multi-department source into one environment (otherwise refused, E-RUN-SCOPE-01). | false |
| --approve-quarantine | opt | Comma-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-question | opt | Repeatable; 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.)
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --config | opt | Path to .env config file | env vars |
| --department | opt | The 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
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --since | opt | Normally 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 |
| --config | opt | Path to .env config file | env vars |
| --strategy | opt | timestamp or id | auto-detected |
| --department | opt | Drain 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-size | opt | Rows per read chunk | 500 |
| --max-duplicate-deletions | opt | Ceiling for the automatic duplicate-placeholder repair; a count above it skips the repair | 100 |
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --cutover-start | opt | ISO 8601 timestamp when cutover began. Omit to run cleanup only, without replay. | , |
| --dry-run | opt | Preview replay scope without writing | false |
| --audiences | opt | Roll back ONLY the v0.8 audience artifacts (segments + list_/crmSegment attributes), leaving contacts intact | false |
| --config | opt | Path to .env config file | env vars |
Exit codes: 0 success, 1 refused (window expired) or error
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.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Target 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-run | opt | Report what would be created without writing | false |
| --departments | opt | Comma-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 |
| --config | opt | Base .env (source + target credentials, CLIENT_ENV). Generated department files copy it. | $ENV_FILE, else ./.env |
| --write-config | opt | Write 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 |
| --tier | opt | Tier recorded on generated registry entries (local|dev|uat|prod). The lifecycle passes the base entry's tier. | dev |
| --id-prefix <prefix> | opt | Namespace generated registry ids and .env files (stcbh → stcbh-1-main-department). The lifecycle passes the base entry id. | none |
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.
| Flag | Description | Default | |
|---|---|---|---|
| --from-config | opt | Run 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-program | opt | Run open-program (idempotent) through each department's config before the preflights | false |
| --dry-run | opt | Pass --dry-run to every child run | false |
| --continue-on-failure | opt | Keep going after a department fails | false (stop) |
| --skip-preflight | opt | Do not run preflight --department N for every department before the first run | false |
| --migrate-users | opt | Forwarded to every child run. Write legacy User/Membership rows (restores the pre-b9b107b77 behaviour). See 06 Run Full Migration. | false |
| --consolidate-languages | opt | Forwarded to every child run (e.g. apply) | child's own |
| --approve-quarantine | opt | Forwarded 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-question | opt | Forwarded to every child run. Repeatable; valid only with --approve-quarantine for the same fingerprint. Added 914d42d15. See 07c for the syntax. | , |
| --skip-hub-backfill | opt | Forwarded to every child run. Keep it on and push per department afterwards. | false |
| --max-workers | opt | Forwarded 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).
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --apply | opt | Write rows | false (dry-run) |
| --report | opt | Path to write report JSON | backfill-targeting-report.json |
| --trigger-name | opt | Name for the auto-created ActionClass | , |
| --trigger-key | opt | Key for the auto-created ActionClass | , |
Runs automatically after Phase 5 during migrate run unless --skip-targeting-backfill. See 07a Post-migration backfill.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --apply | opt | Write segments and attributes idempotently | false (dry-run) |
Full detail: Audiences & segments.
| Flag | Description | Default | |
|---|---|---|---|
| --drop-tracking | opt | Drop 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) |
No flags beyond the global --client/--config. Writes on invoke, no apply gate.
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.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --dry-run | opt | Report what would change without writing | false |
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.
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;
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --apply | opt | Commit the merge: AUTO_MERGE groups commit unattended, QUARANTINE only with --approve-quarantine, UNMERGEABLE never | false (dry-run report) |
| --approve-quarantine | opt | Comma-separated quarantine fingerprints to also commit | , |
| --fold-sibling-question | opt | Repeatable. 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-size | opt | Responses per re-point transaction batch | capped, see CLI help |
Full detail, including Step 4 finalize: 07c Language consolidation.
| Flag | Description | Default | |
|---|---|---|---|
| --survivor-id | REQ | The 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.
IRREVERSIBLE. Ends unmerge-languages for those merges. Refuses to delete any remnant that still holds responses, or a question the survivor never received.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --apply | opt | Commit the deletion | false (dry-run) |
| --accept-question-loss | opt | Delete remnants holding questions absent from the survivor, destroying those questions (TUI key [u]) | false |
| --accept-missing-archive | opt | Go ahead when the merge archive for a remnant is missing (TUI key [m]) | false |
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID | , |
| --batch-size | opt | Rows per PG batch | 100 |
| --concurrency | opt | Parallel Hub POSTs per batch | 8 |
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.
No flags beyond the global --client/--config. Requires Phase 3 complete (Response.contactId populated). Writes ./reports/contact-history-<client>-<ts>.csv and .html.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Client environment ID (via global flag, resolved by resolveClientIdentity) | , |
| --apply | opt | Commit the purge and set this tenant's marker | false (dry-run) |
Full detail, gates, and deployment status: 11b Program retirement & staging-table lifecycle.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --apply | opt | Commit the drop (also requires --confirm) | false (report only) |
| --confirm | opt | Required even for a dry-run report: explicit human sign-off that no future tenant will use this database | false |
| --provenance-manifest <file> | opt | manifest.json from export-provenance. Its per-table counts and database name must match the live populated provenance (E-PROV-02). | , |
| --discard-provenance | opt | Drop 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.
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).
| Flag | Description | Default | |
|---|---|---|---|
| --out <dir> | REQ | Output 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.
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.
| Flag | Description | Default | |
|---|---|---|---|
| --expect-zero | opt | Exit 1 unless every count is zero. Use it as the last step of retirement. | false |
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.
| Flag | Description | Default | |
|---|---|---|---|
| --client | REQ | Environment to project (global flag) | , |
| --dry-run | opt | Report coverage (source / present / missing / conflicting per key) without writing | false |
Four subcommands are wired in the CLI surface but currently print Command not yet implemented. They ship in v0.2:
| Subcommand | Planned behavior |
|---|---|
| superset inventory | Export all Superset dashboards, datasets, charts, RLS rules to a JSON snapshot |
| superset rewrite | Auto-convert MSSQL SQL → PostgreSQL across all chart queries (14 known patterns) |
| superset parity | Run every chart against both DBs and diff results before cutover |
| superset cutover | Atomic 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.json | The environment registry: the base entry and every department entry. |
| .migrate/registry-status.json | Saved Environments re-check results (0600; restored for 24 h). |
| .migrate/live/<pid>.json | One record per running engine child; used to refuse a second writer. |
| .migrate/lifecycle/<base id>.json | Lifecycle state (stages, departments, accepted checks, Hub push times). |
| .migrate/lifecycle/<base id>.lock | Held 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>].json | Channel type mapping (dist/config/ in a built install). |
_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.
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.
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):
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.
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:
GRANT SELECT ON information_schema.columns TO <pg-user>;
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 pressenteron verify, which runs delta + parity again (L5). - Rows filtered by a transform error. Check
_MigrationAuditLogfor error entries
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.
Increase the V8 heap and reduce chunk size:
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.
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.
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.
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:
SELECT phase, table_name, started_at, completed_at, error FROM "_MigrationAuditLog" WHERE environment_id = '<client>' ORDER BY started_at DESC LIMIT 10;
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:
Refresh MVs manually when needed:
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:
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;'
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:
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.
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:
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:
The db:migrate:deploy script invokes a compiled Node entry point. If dist/ is missing, build the database package:
Or bypass the workspace script entirely and call Prisma directly, no build required:
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:
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.
Two causes, both common after a laptop reboot or a new shell:
- Docker Postgres isn't running. Containers don't auto-restart unless configured. Bring it up:
export DATABASE_URLdied with the previous shell. Environment variables don't persist across terminal sessions. Replace exports with a.envfile Prisma auto-loads, see 03 Configure · Step 5 "Make every command env-portable" for the recommended pattern.
Quick recovery without the file setup:
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.
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:
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.
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.
| Migration | What it adds | Reversible? |
|---|---|---|
| 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.
| Migration | What it drops | Reversible? |
|---|---|---|
| 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-016 | Unknown-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-019 | Cutover window cap. Target maintenance window 1 hour, hard maximum 2 hours. Referenced in: Lifecycle, Cutover Checklist. |
| FR-022 | Rollback completes in < 30 min. Worst-case replay bound that drives the FR-023 window length. Referenced in: Emergency Rollback. |
| FR-023 | 4-hour rollback window. Hard cap after cutover start; the rollback command refuses replays beyond this point. Referenced in: Lifecycle, Emergency Rollback. |
| FR-024 | Schema 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-026 | Soft-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-038 | 30-day MSSQL retention. Source DBs stay online read-only for 30 days after cutover. Referenced in: Lifecycle, 30-day archive. |
| FR-039 | Superset 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.