diff --git a/.github/prerelease.json b/.github/prerelease.json
new file mode 100644
index 0000000..a45a224
--- /dev/null
+++ b/.github/prerelease.json
@@ -0,0 +1,3 @@
+{
+ "tag": "v1.2.0"
+}
diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml
new file mode 100644
index 0000000..2eb68fb
--- /dev/null
+++ b/.github/workflows/prerelease.yml
@@ -0,0 +1,107 @@
+name: Prerelease
+
+on:
+ push:
+ branches: [main]
+ paths: ['.github/prerelease.json']
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: publish-prerelease
+ cancel-in-progress: false
+
+jobs:
+ prepare:
+ if: github.ref == 'refs/heads/main'
+ runs-on: ubuntu-latest
+ outputs:
+ tag: ${{ steps.version.outputs.tag }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.13'
+ - id: version
+ name: Validate prerelease request
+ run: |
+ python - <<'PY'
+ import json, os, re
+ from pathlib import Path
+ tag = json.loads(Path('.github/prerelease.json').read_text())['tag']
+ manifest = json.loads(Path('custom_components/entity_replacer/manifest.json').read_text())
+ assert re.fullmatch(r'v\d+\.\d+\.\d+', tag), 'Invalid version tag'
+ assert tag == 'v' + manifest['version'], 'Tag and manifest version differ'
+ with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
+ output.write(f'tag={tag}\n')
+ PY
+
+ tests:
+ needs: prepare
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.13'
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ - run: python -m pip install -r requirements-dev.txt
+ - run: python -m unittest discover -s tests -v
+ - run: node tests/frontend_unit.cjs
+ - run: node --check custom_components/entity_replacer/frontend/panel.js
+ - run: python scripts/build_release.py --check-only --tag '${{ needs.prepare.outputs.tag }}'
+
+ recorder-tests:
+ needs: prepare
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.14'
+ - run: python -m pip install homeassistant==2026.3.0
+ - run: python -m unittest discover -s ha_tests -v
+
+ hassfest:
+ needs: prepare
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: home-assistant/actions/hassfest@master
+
+ hacs:
+ needs: prepare
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: hacs/action@main
+ with:
+ category: integration
+
+ publish:
+ needs: [prepare, tests, recorder-tests, hassfest, hacs]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.13'
+ - name: Build installation ZIP
+ env:
+ RELEASE_TAG: ${{ needs.prepare.outputs.tag }}
+ run: python scripts/build_release.py --tag "$RELEASE_TAG"
+ - name: Publish GitHub prerelease
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ needs.prepare.outputs.tag }}
+ run: |
+ gh release create "$RELEASE_TAG" dist/*.zip dist/SHA256SUMS.txt \
+ --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" \
+ --prerelease --latest=false --title "Device Replacer $RELEASE_TAG — prerelease" \
+ --notes-file RELEASE_NOTES.md
diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml
index 3c71d28..ea6affe 100644
--- a/.github/workflows/validate.yml
+++ b/.github/workflows/validate.yml
@@ -26,6 +26,16 @@ jobs:
- run: node --check custom_components/entity_replacer/frontend/panel.js
- run: python scripts/build_release.py --check-only
+ recorder-tests:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.14'
+ - run: python -m pip install homeassistant==2026.3.0
+ - run: python -m unittest discover -s ha_tests -v
+
hassfest:
runs-on: ubuntu-latest
steps:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1511d7c..5865d2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## 1.2.0 — prerelease
+
+- Add a separate reviewed statistics transfer for compatible disabled measurement sensors with an unused destination statistics ID.
+- Use recorder metadata APIs, preserve both statistics tables, verify completion, and leave raw history/configuration unchanged.
+- Block existing destination statistics, cumulative counters, incompatible units/classes, and unverifiable sources.
+- Persist statistics audit records, prevent blind retries after uncertain outcomes, and exclude them from configuration Restore.
+- Add standalone and real Home Assistant 2026.3 SQLite recorder tests.
+
## 1.1.3 — 2026-10-10
- Hide the panel header sidebar toggle in desktop/wide mode.
diff --git a/README.md b/README.md
index 3fe3aa7..20a7920 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ The integration updates literal references in YAML and saved UI dashboards. Comp
It adds a **Device Replacer** page to the administrator sidebar. There is no dashboard card, frontend resource entry, or `configuration.yaml` setup. The internal domain, installation directory and panel URL remain `entity_replacer` and `/entity-replacer` so existing Entity Replacer installs upgrade in place.
-Maintained by [FortranFour](https://github.com/FortranFour). Current release: **1.1.3**. Requires **Home Assistant 2026.3.0 or newer**, including the bundled local brand images. It uses Home Assistant's existing Python dependencies and has no frontend CDN or additional pip requirements.
+Maintained by [FortranFour](https://github.com/FortranFour). Prerelease version: **1.2.0** (for testing; latest stable remains **1.1.3**). Requires **Home Assistant 2026.3.0 or newer**, including the bundled local brand images. It uses Home Assistant's existing Python dependencies and has no frontend CDN or additional pip requirements.
@@ -137,11 +137,11 @@ The limits are 8 MiB per file or dashboard, 64 MiB of filesystem content, 10,000
**UI helpers and integration settings:** Open **Settings → Devices & services**, select the named integration or helper, and edit its referenced entity through the owning UI. Some integrations require a helper to be recreated. The report shows the physical storage path and location for identification, but the integration never rewrites those internal stores directly.
-**Energy dashboard:** Enable **Additional scan options → Report references in other internal storage (manual review)** to report literal matching references in Energy settings. Change the configured sensor under **Settings → Dashboards → Energy**. Energy configuration is report-only in this release. Replacing an entity reference does not migrate or merge the old sensor's historical energy statistics.
+**Energy dashboard:** Enable **Additional scan options → Report references in other internal storage (manual review)** to report literal matching references in Energy settings. Change the configured sensor under **Settings → Dashboards → Energy**. Energy configuration is report-only in this release. Replacing an entity reference does not migrate or merge the old sensor's historical energy statistics. The separate statistics transfer below intentionally excludes cumulative energy counters.
**Cross-domain changes:** Replacing a `switch` with a `light`, or a `sensor` with a `binary_sensor`, can require different actions, values, conditions, and card types. This release restricts automatic replacement to the same domain. Even within a domain, inspect device capabilities, service data, thresholds, and units in the preview.
-**Computed references and external systems:** IDs assembled from pieces, wildcard/regex selections, aliases selected through areas or labels, former device/entity IDs you have not supplied after registry removal, and add-on-owned configurations such as Node-RED are not fully discoverable by a literal scan. Review those separately. Replacing references does not rename or delete the source entity, migrate recorder history or statistics, pair hardware, or transfer entity/device registry identity.
+**Computed references and external systems:** IDs assembled from pieces, wildcard/regex selections, aliases selected through areas or labels, former device/entity IDs you have not supplied after registry removal, and add-on-owned configurations such as Node-RED are not fully discoverable by a literal scan. Review those separately. Replacing references does not rename or delete the source entity, migrate recorder history or statistics, pair hardware, or transfer entity/device registry identity. Statistics transfer is a separate, explicitly reviewed operation with the limits below.
## Report-only use
@@ -230,3 +230,44 @@ Report issues at [FortranFour/device-replacer/issues](https://github.com/Fortran
- [Native storage persistence source](https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/storage.py)
The integration reads version-dependent Lovelace objects to enumerate dashboards and identify their storage paths. If those interfaces are unavailable, unsupported dashboard references remain manual-review items rather than being written by an unsafe fallback.
+
+## Historical statistics transfer (limited first version)
+
+This operation addresses [issue #1](https://github.com/FortranFour/device-replacer/issues/1) for compatible **measurement** sensors. It renames the existing recorder statistics series to the replacement entity ID through Home Assistant's Python recorder API. Hourly and retained five-minute statistics remain attached to the same numeric metadata ID. It does not copy measurements, merge two series, change raw state history, rewrite configuration, or change Energy Dashboard settings.
+
+Requirements are deliberately strict:
+
+- A running recorder and the supported metadata API (Home Assistant 2026.3+).
+- Both entities remain registered, are disabled, and have no loaded state. Simply being unavailable is insufficient. Removed sources cannot be verified in this version.
+- Both registry entries declare `state_class: measurement`, the same known device class, and the same nonempty unit. The source's stored unit must match exactly. No unit conversion is attempted.
+- The source contains recorder-owned arithmetic-mean statistics and at least one retained hourly or five-minute record.
+- The replacement has **no statistics metadata**, including an empty metadata record. Existing replacement statistics are never deleted to make room.
+- `total`, `total_increasing`, cumulative energy counters, external statistics and circular means are unsupported.
+
+### Transfer a fresh replacement
+
+1. Create and verify a current backup that includes your recorder database. Device Replacer's configuration backups do **not** contain that database. For an external database, use its appropriate backup process.
+2. Disable the old sensor and keep it disabled. Pair the replacement, verify its role, then disable its sensor before it accumulates statistics. Wait for both sensors to unload; reload their integration or restart Home Assistant if necessary. Do not delete either entity from the registry.
+3. In Device Replacer, choose the pair in **Single entity**, or load and confirm whole-device entity mappings. Open **Transfer historical statistics** and click **Check statistics** for one pair. This read-only check works even if there are no configuration references to replace.
+4. Review the pair, class, units and latest retained periods. Confirm the measurement role and database backup, then select **Transfer reviewed statistics**. The preview is session-bound, expires after 15 minutes, and is checked again at execution.
+5. Wait for the verified result, then enable **only the replacement sensor**. Review its statistics in Developer tools. Replace configuration references separately; if the replacement is disabled during that scan, enable **Allow unavailable or disabled replacements** for reference edits only.
+
+Home Assistant can refuse a rename without raising an exception. Device Replacer therefore waits for recorder completion and verifies the destination metadata and numeric ID rather than trusting the callback. No database schema migration or direct SQL is used.
+
+### Audit and recovery
+
+Each attempt writes a durable audit manifest under `.entity_replacer_backups//manifest.json` before queuing recorder work. Statistics audit entries appear separately in the panel and cannot be selected for configuration Restore; the backend also rejects that operation. There is no automatic database undo after recording resumes.
+
+A timeout, cancellation, failed verification, or interrupted transfer has an **unverified outcome**: recorder work may still finish. The reviewed token is consumed, and unresolved audit entries block further transfers involving either ID even after restart. Do not retry blindly. Inspect the database, Home Assistant log and audit manifest; recover using your database-inclusive backup if needed. Use **Check outcome** in the statistics audit to verify a late completion without submitting another recorder job. It clears the unresolved audit only when the original numeric metadata ID is provably at the destination and the source is absent. Otherwise it stays blocked: inspect/recover the database and audit record. This version does not offer a force/retry button. Do not change these sensors' registry settings from another session while a transfer is running.
+
+### Development checks
+
+The ordinary unit suite uses HA stubs. Run real recorder tests separately so those stubs cannot mask API compatibility:
+
+```bash
+uv venv --python 3.14 /tmp/device-replacer-ha
+uv pip install --python /tmp/device-replacer-ha/bin/python homeassistant==2026.3.0
+/tmp/device-replacer-ha/bin/python -m unittest discover -s ha_tests -v
+```
+
+These tests use a temporary SQLite database and real Home Assistant recorder APIs. They check hourly/five-minute row preservation, metadata ID continuity, unchanged raw history, and collision refusal. No production Home Assistant connection is used.
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index f82dc10..83ddd04 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,5 +1,9 @@
-# Device Replacer 1.1.3
+# Device Replacer 1.2.0 — prerelease
-Hide the duplicate hamburger menu in desktop/wide view. Retain it in Home Assistant’s mobile/narrow view so navigation remains accessible. Visibility follows the narrow layout property supplied by Home Assistant and updates when the layout changes.
+Add a separate statistics transfer workflow for compatible arithmetic measurement sensors. The source and replacement must both be disabled and unloaded, retain verifiable registry metadata, and use matching units/classes. The replacement must have no stored statistics metadata.
-The cyan icon, device replacement, single-entity replacement, backups and restore remain available. Update through HACS, restart Home Assistant, and refresh the browser/app to load the new frontend. No new integration entry is needed.
+Transfer uses recorder's metadata API and verifies the result. Hourly and retained five-minute measurements keep their existing metadata ID; raw state history and configuration are unchanged. Cumulative counters (including Energy sensors), merges, unit conversion and removed/unverifiable sources are excluded in this first version.
+
+A database-inclusive backup is required for recovery. Statistics operations have separate audit records and are never undone by configuration Restore. Uncertain recorder outcomes consume the preview and block further transfers involving the pair until reconciled.
+
+This is a prerelease for testing before a stable release. Real recorder tests target Home Assistant 2026.3.0 with SQLite; other database engines and production installations still need validation.
diff --git a/custom_components/entity_replacer/const.py b/custom_components/entity_replacer/const.py
index 03a97d2..5008330 100644
--- a/custom_components/entity_replacer/const.py
+++ b/custom_components/entity_replacer/const.py
@@ -1,7 +1,7 @@
"""Constants for Device Replacer."""
DOMAIN = "entity_replacer"
-VERSION = "1.1.3"
+VERSION = "1.2.0"
PANEL_PATH = "entity-replacer"
PANEL_NAME = "entity-replacer-panel"
STATIC_PATH = "/entity_replacer_static"
diff --git a/custom_components/entity_replacer/device_manager.py b/custom_components/entity_replacer/device_manager.py
index efafea6..e62a758 100644
--- a/custom_components/entity_replacer/device_manager.py
+++ b/custom_components/entity_replacer/device_manager.py
@@ -311,7 +311,7 @@ async def scan_device(self, owner, source, target, mappings, confirmed_mappings=
mode="device", mappings=rows, source_device=source, target_device=target, registry_snapshot=fingerprint, device_blocks=blocks)
if old is None:
warnings.append("The old device is removed. Only its entered device ID and explicitly supplied entity/registry IDs can be found; omitted former entities cannot be discovered.")
- warnings.append("Review unassigned entities and manual device blocks. Pairing, identities, areas/labels, and historical statistics are not transferred.")
+ warnings.append("Review unassigned entities and manual device blocks. Pairing, identities, areas/labels, and historical statistics are not transferred by reference replacement; eligible measurement statistics have a separate transfer action.")
return await self._public_preview(preview_id, preview, warnings + notes, file_count, dashboard_count)
async def _check_device_preview(self, preview, selected):
diff --git a/custom_components/entity_replacer/engine.py b/custom_components/entity_replacer/engine.py
index 55475a1..3882ad3 100644
--- a/custom_components/entity_replacer/engine.py
+++ b/custom_components/entity_replacer/engine.py
@@ -709,13 +709,36 @@ def history(self) -> list[dict]:
continue
try:
manifest = self.load(directory.name)
- result.append({key: manifest[key] for key in ("job_id", "created", "source", "target", "status")})
+ result.append({**{key: manifest[key] for key in ("job_id", "created", "source", "target", "status")}, "mode": manifest.get("mode", "entity")})
except (OSError, ValueError, KeyError, ReplacementError):
continue
if len(result) >= 30:
break
return result
+ def statistics_conflicts(self, source: str, target: str) -> list[str]:
+ """Find unresolved recorder operations, including across HA restarts.
+
+ Unlike the UI history this scan is not capped at 30 records. Refuse a
+ damaged manifest rather than overlooking an unknown pending operation.
+ """
+ base = safe_path(self.root, BACKUP_DIR)
+ if not base.exists():
+ return []
+ conflicts = []
+ for directory in base.iterdir():
+ if not JOB_ID.fullmatch(directory.name):
+ continue
+ try:
+ manifest = self.load(directory.name)
+ except (OSError, ValueError, KeyError, ReplacementError) as err:
+ raise ReplacementError(f"Cannot verify audit record {directory.name}; inspect it before transferring statistics.") from err
+ if (manifest.get("mode") == "statistics"
+ and manifest.get("status") in {"statistics_applying", "statistics_outcome_unknown"}
+ and {source, target} & {manifest["source"], manifest["target"]}):
+ conflicts.append(manifest["job_id"])
+ return conflicts
+
def render_report(preview: dict) -> str:
lines = [
@@ -728,7 +751,7 @@ def render_report(preview: dict) -> str:
lines += ["## Confirmed entity mappings", "", "| Source entity | Replacement entity | Old registry ID | New registry ID |", "| --- | --- | --- | --- |"]
for row in preview.get("mappings", []):
lines.append(f"| `{row['source']}` | {('`' + row['target'] + '`') if row['target'] else 'Unmapped; unchanged'} | {row.get('source_registry_id') or 'Unknown'} | {row.get('target_registry_id') or 'None'} |")
- lines += ["", "Device automation selector groups must be selected together. Unsupported blocks must be rebuilt in their owning editor.", "Pairing, unique IDs, areas/labels and historical statistics are not transferred.", ""]
+ lines += ["", "Device automation selector groups must be selected together. Unsupported blocks must be rebuilt in their owning editor.", "Pairing, unique IDs, areas/labels and historical statistics are not transferred by reference replacement; eligible measurement statistics have a separate transfer action.", ""]
for warning in preview["warnings"]:
lines += ["- " + warning]
for document in preview["documents"]:
diff --git a/custom_components/entity_replacer/frontend/panel.js b/custom_components/entity_replacer/frontend/panel.js
index 2a09747..a19cdaf 100644
--- a/custom_components/entity_replacer/frontend/panel.js
+++ b/custom_components/entity_replacer/frontend/panel.js
@@ -1,4 +1,4 @@
-/* Device Replacer 1.1.3. No external frontend libraries or build step. */
+/* Device Replacer 1.2.0. No external frontend libraries or build step. */
const escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
}[character]));
@@ -30,6 +30,7 @@ class EntityReplacerPanel extends HTMLElement {
this._notice = "";
this._preview = null;
this._review = null;
+ this._statisticsPreview = null;
this._started = false;
this._render();
}
@@ -96,6 +97,9 @@ class EntityReplacerPanel extends HTMLElement {
}
_invalidate() {
+ this._statisticsPreview = null;
+ const statistics = this._query("#statistics-section");
+ if (statistics) { statistics.innerHTML = this._renderStatistics(); this._bindStatistics(); }
this._preview = null;
this._review = null;
this._selected.clear();
@@ -242,6 +246,59 @@ class EntityReplacerPanel extends HTMLElement {
});
}
+ _statisticsPairs() {
+ return this._mode === "device"
+ ? (this._mappingConfirmed ? this._mappings.filter((row) => row.source.startsWith("sensor.") && row.target) : [])
+ : (this._source.trim() && this._target.trim() ? [{ source: this._source.trim(), target: this._target.trim() }] : []);
+ }
+
+ async _previewStatistics(index) {
+ const pair = this._statisticsPairs()[index];
+ if (!pair) return;
+ this._statisticsPreview = null;
+ await this._run("Checking stored statistics and disabled sensors…", async () => {
+ this._statisticsPreview = await this._request("statistics_preview", { source: pair.source.trim(), target: pair.target.trim() });
+ });
+ }
+
+ async _applyStatistics() {
+ if (!this._statisticsPreview?.eligible || !this._query("#statistics-confirm")?.checked) return;
+ const previewId = this._statisticsPreview.preview_id;
+ await this._run("Transferring statistics through recorder and verifying the result…", async () => {
+ let result;
+ try {
+ result = await this._request("statistics_apply", { preview_id: previewId, confirmed: true });
+ } finally {
+ // A timeout can leave recorder work queued. Never keep a retry button.
+ this._statisticsPreview = null;
+ }
+ this._notice = `${result.message} Audit: ${result.job_id}`;
+ await this._refreshHistory();
+ });
+ }
+
+ _statisticsTime(timestamp) {
+ return timestamp == null ? "none" : new Date(timestamp * 1000).toLocaleString();
+ }
+
+ async _verifyStatistics(jobId) {
+ await this._run("Checking recorder metadata without retrying the transfer…", async () => {
+ const result = await this._request("statistics_verify", { job_id: jobId });
+ this._notice = result.message;
+ await this._refreshHistory();
+ });
+ }
+
+ _renderStatistics() {
+ const pairs = this._statisticsPairs();
+ const preview = this._statisticsPreview;
+ const audit = (this._history || []).filter((item) => item.mode === "statistics");
+ return `
Transfer historical statistics (limited preview)
Separate from reference replacement. Supports arithmetic measurement sensors with identical units; existing replacement statistics and cumulative counters are blocked.
Keep both sensors registered, disable them in Settings → Devices & services → Entities, and wait until unloaded. The old sensor must remain disabled afterward. No measurements or raw state history are copied.
Audit records contain no database backup. An unverified outcome blocks further transfers involving those sensors until the audit/database is reconciled.
Choose the old and new devices, confirm their entity roles, then review and apply selected changes with backups. Single-entity replacement is also available.
YAML formatting and comments are preserved. UI dashboards are saved through Home Assistant. Device blocks are selectable only when their selectors and replacement capabilities can be validated. Unsupported blocks and other storage get manual instructions.
- ${this._busy ? `
${escapeHtml(this._busyMessage)}
` : ""}
${this._renderResults()}
-
Restore a replacement
Restore checks every file/dashboard first and refuses to overwrite newer edits. Backups survive Home Assistant restarts.
${this._history.length ? `` : '
No replacements have been applied yet.
'}
+ ${this._busy ? `
${escapeHtml(this._busyMessage)}
` : ""}
${this._renderResults()}
${this._renderStatistics()}
+
Restore a replacement
Restore checks every file/dashboard first and refuses to overwrite newer edits. Backups survive Home Assistant restarts.