Metadata-Version: 2.4
Name: power-migrate
Version: 0.2.2
Summary: Excel and Power Platform logic to readable, tested code, with a reconciliation report of every checkable cell.
License: Proprietary
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: openpyxl>=3.1
Requires-Dist: oletools>=0.60
Requires-Dist: pyyaml>=6
Requires-Dist: cryptography>=42
Provides-Extra: ai
Requires-Dist: anthropic>=1.12; extra == "ai"
Provides-Extra: pandas
Requires-Dist: pandas>=2.2; extra == "pandas"
Provides-Extra: powerbi
Requires-Dist: pbixray>=0.15; extra == "powerbi"
Provides-Extra: sql
Requires-Dist: duckdb>=1.1; extra == "sql"
Provides-Extra: web
Requires-Dist: fastapi>=0.115; extra == "web"
Requires-Dist: uvicorn[standard]>=0.30; extra == "web"
Requires-Dist: python-multipart>=0.0.9; extra == "web"
Requires-Dist: markdown>=3.6; extra == "web"
Requires-Dist: nh3>=0.2; extra == "web"
Provides-Extra: excel
Requires-Dist: pywin32>=306; sys_platform == "win32" and extra == "excel"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: httpx2>=2.0; extra == "dev"

# Power Migrate

Your spreadsheet, as code you can trust, with the receipts.

Power Migrate converts business-critical Excel workbooks into readable,
tested Python code, then reconciles the new code against the original
workbook and reports every difference. It runs entirely inside your own
environment: no uploads, and an AI model of your choice (or none).

Status: v0.2.2, available since October 2026, positioned as enabling agentic
analytics: logic from workbooks and the Power Platform as tested code that pipelines
and AI agents can run, with the reconciliation report as the proof. The hosted
converter at power-migrate.com/app is free and needs no account; the
command-line tool runs inside your own environment under a licence file
(a free 30-day trial from power-migrate.com/trial, then a team licence);
conversions done for you are on the pricing page. See [ROADMAP.md](ROADMAP.md)
for what is done, what is next and in which order. Every stage that decides
correctness is deterministic; the AI stages are optional, advisory and run
under your own account with the provider (Anthropic today).

## What it does today

```
power-migrate analyse  <workbook.xlsx>   # workbook map + feature report, no code
power-migrate convert  <workbook.xlsx>   # map, generated package, reconciliation
power-migrate estimate <workbook.xlsx>   # convert, then print what the AI stages would cost

options: --out DIR  --vba-from older.xlsm  --redaction labels|strict  --pricing prices.json
         --ai-provider none|anthropic  --ai-model <id>   (naming stage; credentials from the environment)
         --rel-tol 1e-9 --abs-tol 1e-9 (convert)
         --variations N --seed S --excel-macros           (convert; Windows with Excel installed)
         --target python|pandas|sql                           (convert; default python)
         --locale en-GB|en-US|en-PK|...|dmy|mdy[:symbol]       (how the Excel that saved the file reads d/m/y dates and currency text)

power-migrate licence                    # the licence in use, who it is for and how long it has left
power-migrate licence install <file>     # verify a licence file and copy it to your user folder
power-migrate licence usage [--out FILE] # totals from the usage record kept on this machine
```

Every command except `licence` runs under a licence file (`power_migrate/licence.py`):
a small signed JSON document verified on the machine, with no licence server and
no call home. A trial licence is free for 30 days (power-migrate.com/trial);
`scripts/licence.py issue` signs one. Reports and run logs of a command-line run
name the licensee. The tool also keeps one line per run in the user folder
(command, sizes, outcome; never a name, a formula or a value), which
`licence usage` adds up; it is sent nowhere and `PM_USAGE_LOG=off` stops it.

With `--target pandas` each sheet becomes a DataFrame indexed by row number
with Excel column letters as columns, and every copied formula the vectoriser
can express becomes one assignment: a copied-down column is a column
operation, a formula copied across a row is a row operation over a Series
indexed by column letter, and a filled table is a DataFrame operation. Inside
a block, same-position cells are the block's own shape, fixed offsets are
shifts, absolute cells are scalars, fixed ranges and defined names are lookup
tables. Blocks it cannot express (single cells, running totals, ranges that
move with the formula, unsupported functions) are emitted exactly as in the
scalar target and run cell by cell over the same frames, so the reconciliation
covers both kinds and the run log records how much was vectorised. On the
GHSCalc workbook that is 177 of 527 blocks and 2,651 of 3,091 cells, still
reconciling 3,069 of 3,069. The generated package then needs pandas.

With `--target sql` the workbook becomes SQL: one table per worksheet keyed by
row number with a typed column per Excel column, and one `CREATE TABLE ... AS
SELECT` step per logic block in dependency order, so a step may read another
sheet's latest state through joins (the row above, the same row of another
sheet) and a small parameter subquery for fixed cells and defined names. A
column that reads its own previous row becomes a recursive query; copied
formulas become one expression per column; lookups, criteria functions
(SUMIFS over whole columns included), SUMPRODUCT over boolean arrays, NPV and
the financial, date and text functions have direct SQL forms, with Excel's
semantics in a small macro library (`functions.sql`). The package is run in
DuckDB for the reconciliation, and the SQL is the deliverable: on the two
public samples 638 of 641 and 2,476 of 2,477 cells reconcile, every remaining
cell either named as not converted (`IRR` and `RATE` need a solver) or
explained by a declared policy. Those policies are the one thing SQL cannot
hide: it has typed columns and no error values, so an Excel error is `NaN` in
a numeric column (it spreads through arithmetic as in Excel, but its code is
not carried) and `NULL` in a text column, the empty string is `NULL`, a blank
input counts as 0 in arithmetic, and the report counts every cell that
matched only under them on a row of its own, and every cell where Excel shows
an error and the SQL computed a value instead. The generated package
needs duckdb; the SQL itself needs only a DuckDB (other dialects follow once
they can be verified against a live engine).

With `--variations N` the tool opens the workbook read-only in a hidden Excel,
perturbs its numeric parameters N times (seeded, so repeatable), lets Excel
recalculate each case, runs the generated code on the same inputs and compares
every formula cell. It also checks that Excel's own recalculation reproduces
the stored values, which catches workbooks saved with stale results. Macros
stay disabled unless `--excel-macros` is given.

With `--ai-provider anthropic` the AI stages run for real, chosen with
`--ai-stages name,describe,review` (default `name`): `name` proposes
`snake_case` names and purposes for the generated functions, `describe` writes
a plain-English summary per sheet into the workbook map (marked as AI-written,
to verify), and `review` saves an idiomatic-rewrite proposal per module under
`ai_review/` without applying it. The model sees redacted structure, never
values; every request and response is written to `ai_log/` with its hash,
token usage and cost in `run_log.json`, alongside the estimate for the same
stage so the cost model keeps calibrating itself. The arithmetic stays
rule-based either way.

`convert` writes to `out/<workbook>/`:

| Output | What it is |
| --- | --- |
| `workbook_map.md` / `.json` | Sheet-by-sheet summary, inputs and outputs, how sheets connect (Mermaid), functions used, defined names, every risky feature found |
| `graph.html` | Interactive dependency graph: sheets laid out by calculation depth, arrows with formula counts, click a sheet for its blocks and functions. Self-contained, works offline |
| `<package>/` | A Python package: one module per sheet, one function per logic block, `compute(book)` entry point, `inputs.json`, Excel-semantics runtime `xl.py`, `udf.py` for translated macros, and a regression test |
| `reconciliation.md` / `.json` | Every formula cell compared with the value Excel stored: match, mismatch, not converted (with the reason), or no reference |
| `variations.md` / `.json` | With `--variations`: Excel versus the code on generated input sets, cells that agreed on every set, cells that disagreed with examples, and whether Excel reproduces its own stored values |
| `vba_inventory.md` + `vba/` | Every VBA module and procedure, which user-defined functions formulas call, and whether each was translated or stubbed; module sources extracted alongside |
| `ai_estimate.md` / `.json` | Dry run of the optional AI stages: what each would send (redacted), token counts and cost per model. No model is called |
| `lineage.json` | Output cell to generating function to source cells |
| `feature_gap.json` | Feature names and counts only, safe to send back to us |
| `run_log.json` | Inputs, hashes, versions, options, AI calls (none) and the estimate |

On our first test workbook, a 49-sheet building-energy model (3,091 formulas,
986 VLOOKUPs, dead external links, broken names, a user-defined function), the
generated code reproduces 3,069 of 3,069 checkable cells; the rest are
reported as not converted with their root cause. An older macro-enabled
version supplies the user-defined function with `--vba-from`; its three-step
Newton solver is translated from VBA by rules and reproduces Excel's own
`#VALUE!` where the macro failed. Test workbooks of doubtful licence stay in
the gitignored `private/` folder; `samples/` is for public or synthetic files.

The public sample library ([samples/README.md](samples/README.md)) is both the
demo set and the regression suite: each synthetic workbook is built by a
seeded script to contain the habits that make migration hard, converted on
every target, and checked against Excel on generated inputs. Two so far, an
FP&A month-end model and an asset-finance pricing calculator, both reconcile
fully; each new one is built to expose functions and Excel semantics the
runtime does not yet have.

## Power Apps: inventory and map

The first adjacent source. `power-migrate map-app <app.msapp or folder>` reads
a canvas app's own source (`Src/*.pa.yaml` inside the `.msapp`, or a folder
from Git integration), parses every Power Fx formula, and writes an app map
(screens, controls, every formula classified as layout, behaviour, state or
data), the dependency graph (what each formula reads and writes: controls,
variables, context variables, collections, data sources, navigation), and a
feature-gap report that sorts the functions used into translatable, behaviour,
external, connector and not-yet-classified, and names every formula the
parser could not read.

`power-migrate convert-app <app>` goes on to translate every pure formula
(data, state and layout properties, named formulas) into a Python package over
a dependency-free Power Fx runtime, infers the shape of the app's inputs from
how the formulas use them, generates seeded input variations in that shape,
evaluates every formula in Microsoft's open-source Power Fx interpreter on the
same inputs (gallery row by gallery row) and compares. `reconciliation.md`
names every property as reconciled, differing, unchecked (the interpreter
could not evaluate it) or not translated (behaviour formulas such as
`OnSelect`, unsupported functions, unreadable formulas), with the reason.
Supply `--inputs inputs.json` with a real extract to replace the generated
values. The interpreter needs a .NET SDK; without one the package is still
written and the report says nothing was checked. Every `.msapp` layout Power
Apps has saved is read: the current YAML source files, the earlier YAML layout,
and the pre-YAML JSON control trees. On Microsoft's own Track Sales Leads demo
app all 549 pure formulas reconcile; on the community Chess app (4,586
formulas, 11 screens) 4,719 of the 4,753 translated formulas and behaviour
values reconcile with no differences; the 34 unchecked are formulas the
interpreter cannot bind (`Ungroup` and `GroupBy`, which it lacks, spellings
and connector names it does not know) and two `GUID()` values, which change
on every evaluation; their dependents are checked on the values the
generated code produced, and the report names each. The 30-screen AccountPlanReviewerMaster
app (73,137 formulas, Dataverse-backed) runs in about two and a half minutes
over four input sets: 58,335 reconciled, none differing; its Dataverse
column types, lookups and choice sets are read from the metadata the
package carries rather than inferred.

Behaviour formulas (`OnSelect`, `OnStart`, `OnVisible`, ...) are not values,
so they become a state specification instead: `behaviour.md` lists, for every
event, the steps it takes (state written, screens navigated to, actions that
leave the app such as `Notify` or a connector call), and `python/behaviour.py`
holds one handler per event that applies those steps to the same `Context`
the pure formulas read, logging the external actions rather than performing
them. The value expressions inside the steps are reconciled like properties.
On the synthetic `samples/orders_app.msapp`, all 25 pure formulas and the 6
values inside its behaviour steps reconcile across 20 input sets; the 6
behaviour formulas become 10 steps, none unsupported.

## Power Automate: inventory and map

`power-migrate map-flow <export>` reads cloud flows from a solution export, a
legacy package export, a definition JSON or a folder, parses every expression
(the Workflow Definition Language: `@variables('Total')`, `@{...}` text), and
writes a flow map (trigger, every action with its type, kind, what it reads
and writes, what it reaches outside the flow and what it runs after,
indented by nesting with the branch it sits in), the variables and parameters
with their writers and readers, the connectors with each operation marked
read or write, the property paths read from the trigger, from action outputs
and from loop items (the data model a migration has to carry), the functions
used, and a feature-gap report of counts only. Map stage only: no
translation yet, so nothing is guessed. Try it on the synthetic
`samples/invoice_flow.zip`.

## Power BI: inventory and map

`power-migrate map-pbi <report>` reads a `.pbix`, a `.pbit`, or a Power BI
project (a `.pbip` file or its folder, or a `.Report` or `.SemanticModel`
folder on its own) and writes a model map: where the data comes from (every
access function with the path, server or feed it names, and the parameters
it reads), one row per Power Query with its steps, the queries it reads and
the functions it calls, every table with its kind, storage mode, row count,
columns and measures, the relationships with cardinality, filter direction
and whether they are active, every measure with what it reads, the functions
it calls, how deep its chain of measures goes and how many visuals use it,
calculated columns and tables, calculation groups, row-level security filters
and hierarchies; then the report page by page, every visual with its fields
by role, its filters, the fields its formatting reads and its sort, filters at
report, page and visual scope, bookmarks, custom visuals and the measures
defined in the report rather than the model; then which measures the report
reaches and which columns nothing uses, the DAX functions by family (naming
the ones whose meaning depends on the engine's evaluation state, which need
their own decision before a translation can claim them), the Power Query
functions, every expression the tokenizers could not read, and a feature-gap
report of counts only. A `.pbix` is read without Power BI Desktop: the report
is JSON inside the file and the model is decoded by pbixray (MIT;
`pip install "power-migrate[powerbi]"`), rows included. Map stage only: no
translation yet, so nothing is guessed. Try it on the synthetic
`samples/retail_report` project, or on Microsoft's MIT samples
(`python scripts/fetch_pbi_samples.py`).

## Power BI: does the report still show the same numbers?

A semantic model gets rebuilt, consolidated, moved to another storage mode,
or edited by a person or an agent. `power-migrate baseline-pbi <report>
--workspace <id> --model <name>` reads the report, asks the published model
every question its visuals put to it (each visual at its own grain and as
its grand total, a matrix also at its outer row levels, under the filters of
the report, the page and the visual) and writes the answers to
`baseline.json`, with `baseline.md` for a reader. `power-migrate check-pbi
<baseline.json> --model <other>` asks another model, or the same one later,
the same questions and writes `model_check.md`: the result first, then every
value that differs with its before and after, every question the engine
answered before and refuses now (asked again a measure at a time, to name
the one that stopped), and what could not be asked at all. The exit code is
0 when nothing differs and 4 when something does.

Both sides are Power BI's own engine, so nothing is translated and nothing
is approximated: real numbers must agree within a relative 1e-9
(`--tolerance`), everything else exactly. What a visual has that cannot be
asked yet (a visual calculation, a top N or relative date filter, a level
of an automatic date hierarchy) is left out and named, never replaced, and
a measure that reads the clock or the signed-in user is recorded but not
compared. A slicer's saved selection is applied to the visuals of its page
that it reaches, as the report opens with it; what a viewer does afterwards
(a selection, a bookmark, a drill) is not.

A rebuilt model usually renames things. `check-pbi` first asks the model for
the names it has, and lists before anything else the names the report reads
that it lacks, each beside the names this model has that the first one did
not (a hint for you, never used). It writes them to `rename_map.json` with a
blank beside each; write what each is called now and run again with
`--renames rename_map.json`:

```json
{
  "tables": {"Product": "Item"},
  "columns": {"Product[Category]": "Product Group", "Store[Country]": "Store[Country Name]"},
  "measures": {"Net Sales": "Net Revenue"}
}
```

A renamed table, column or measure is then asked for by its new name and
compared under its old one, and a measure that moved to another table is
found by its name with no map at all. Nothing in a map is inferred, an entry
no question reads is named in the report (it may be a slip), and values are
not renamed: a member called North before and N now is a difference.
Listing a model's names uses the engine's `INFO.VIEW` functions, for which
Microsoft asks more permission than a query needs; where the engine will not
list them the check runs without the list and says so.

The commands ask the model in your own workspace under your own sign-in
(`az login`, or tokens in `PM_FABRIC_TOKEN` and `PM_POWERBI_TOKEN`) and
write to this machine; nothing goes anywhere else. They use Power BI's
query API, for which Microsoft asks that your account has access to the
workspace and read and build permission on the model, and that your tenant's
setting "Dataset Execute Queries REST API" is on. The baseline certifies
the questions it holds, each written beside its answer as the DAX that was
sent.

## Hosted converter and the site

`power_migrate/web/` is a FastAPI service over the same pipeline: upload a
workbook, pick a target, poll the job, read the evidence pack in the browser
(reconciliation, workbook map, dependency graph, generated code) and download
the package. It runs no AI step and no Excel, keeps each upload in its own
folder and deletes it after a few hours. `site/` is power-migrate.com: an
Astro site whose content pages are plain HTML at build time, with React only
for the converter, and whose sample pages are the tool's own evidence packs
published by `scripts/publish_samples.py`.

```
pip install -e ".[sql,pandas,web]"
uvicorn power_migrate.web.app:app --reload          # API on http://127.0.0.1:8000
cd site && npm install && PUBLIC_API_BASE=http://127.0.0.1:8000 npm run dev
```

In production the API runs as a container on Azure Container Apps in UK South
(`Dockerfile` over the pinned `requirements.lock`) at
`https://api.power-migrate.com`, and the site is static files on the Krystal
host. Every push to main ships through the `release` GitHub workflow: the test
suite, then, when anything that goes into the image changed, the image build
(`build-image.yml`, called as a reusable workflow; no local Docker is needed)
and `az containerapp update --image` to the new tag, then the site build and
`scripts/deploy_site.py` over FTP with TLS. A site-only change never restarts
the API, which holds live results links in memory. The site build defaults
to the production API origin (`PROD_API_BASE` in `site/src/config.ts`).
Two things stay by hand: the container's configuration (environment
variables, secrets, probes, hostname) through `scripts/azure_deploy.sh
--image <tag>`, and the sample evidence packs under `site/public/samples/`,
which `scripts/publish_samples.py --variations 20 --apps` regenerates with
Excel and the Power Fx interpreter and `scripts/deploy_site.py` uploads; the
workflow never deletes a file from the host. The workflow's identity is the
`power-migrate-github-actions` app registration (GitHub OIDC; AcrPush on the
registry, Contributor on the Container App, Reader on the resource group) and
the `FTP_SERVER`, `FTP_USERNAME` and `FTP_PASSWORD` repository secrets. The
container runs no AI step and no Excel, holds each upload in its own folder
and deletes it within six hours.

The service records one JSON line per event (a job created, done, failed,
refused, deleted or expired; each download) carrying sizes, counts, durations,
targets, outcomes and an anonymous browser session id, never the workbook's
names, formulas or values (a failure records the exception type only). In
production those lines land in the Log Analytics workspace, and
`python scripts/usage_report.py --days 30` turns them into the
numbers that inform pricing and the product. Page views and funnel
events go to GoatCounter (cookieless, no personal identifiers) at
power-migrate.goatcounter.com; a production build uses that site, and
`PUBLIC_GOATCOUNTER_URL` overrides it.

The contact page (`/contact/`) posts to `/api/contact`, which validates the
message (a honeypot field, a minimum time on the form, a link limit, a rate
limit per connection) and emails it to the hello@ mailbox with the sender as
Reply-To; nothing from the form is stored on the server. The mailbox password
reaches the container as a Container Apps secret set by
`python scripts/azure_secrets.py` from the repo `.env`.

The help page (`/help/`) renders the assistant's knowledge base, the markdown
under `power_migrate/web/kb/`, and the "Ask a question" button on every page
posts to `/api/assistant`, which answers only from that knowledge base with
Claude Sonnet 5.5 (the knowledge base sits in a cached system prompt, so an
answer costs a fraction of a cent). In production the service authenticates
with Workload Identity Federation: the container's managed identity token is
exchanged for a short-lived Anthropic token, and no API key exists; locally
`ANTHROPIC_API_KEY` works. Questions and answers are never stored, the usage
event carries the outcome and token counts, and per-connection and per-day
limits sit on top of the Anthropic workspace's spend limit.

The command-line tool is a wheel built into the container image and served at
`/api/cli` (the download page links to it); downloads are counted by file name
only. The results page offers files to keep: `/api/jobs/<id>/download/<name>`
serves a report as a standalone HTML document (`reconciliation.html`,
`workbook_map.html`), the raw reports by name, or `evidence.zip`, the whole
output folder as the CLI writes it. Its feedback form posts to
`/api/feedback` (the contact form's honeypot and timing checks, a
per-connection limit), which emails the message to the mailbox and attaches
the run's feature-gap report and summary only when the box is ticked. A
workbook that holds no calculated values (written by openpyxl, or saved with
calculation deferred) is reported as such: `reference` is `none` in the job
summary, the report opens by saying nothing could be checked, and the CLI
prints the same advice. The beta programme's signed invitations and sign-up
form were removed when the product went general (October 2026); `/beta/`
redirects to `/download/`.

## Pipeline

1. **Parse** (`parse.py`): openpyxl for formulas and for the values Excel last
   calculated; the zip package for VBA, external links, connections, Power
   Query, pivots. Dates stay as Excel serial numbers.
2. **Dependency graph** (`graph.py`): every reference resolved; ranges are
   graph nodes so a lookup table read by 900 formulas is expanded once.
3. **Logic blocks** (`blocks.py`, `plan.py`): copied formulas share an R1C1
   signature and become one rectangle; blocks are ordered topologically and a
   block that reads itself gets a safe loop direction.
4. **Generate** (`codegen/python.py`): rules only. Names come from nearby
   sheet labels. Anything unsupported becomes `xl.UNSUPPORTED(reason)`, which
   propagates and is never caught by `IFERROR`.
5. **Reconcile** (`reconcile.py`): run the package on the workbook's own
   inputs and compare every formula cell with the stored value.

Alongside: `vba.py` inventories the VBA project (oletools) and translates
functions written in a small VBA subset; `ai/` builds the redacted payloads
each optional AI stage would send and prices them from `ai/pricing.json`,
which carries the date its rates were verified.

## Development

```
python -m venv %LOCALAPPDATA%\power-migrate\venv      # keep the venv out of OneDrive
%LOCALAPPDATA%\power-migrate\venv\Scripts\pip install -e .[dev]
pytest
```

Python 3.12, openpyxl only at runtime. The generated package has no
dependencies at all.

## Wording

The reconciliation report shows tested equivalence on the inputs it ran. It
is not a guarantee for other inputs, and it says so.
