diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ca79ca5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7e92154 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: Quality checks + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - run: node --check app.js && node --check core.js && node --check sw.js + - run: python3 scripts/validate_pwa.py + - run: python3 scripts/validate_release_disclosures.py + - run: python3 scripts/verify_hand_checks.py + - run: npm test + - run: python3 scripts/build_pages.py + - run: python3 scripts/validate_pages_artifact.py diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..2c6f97b --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,47 @@ +name: Deploy GitHub Pages + +on: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: github-pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + - run: node --check app.js && node --check core.js && node --check sw.js + - run: python3 scripts/validate_pwa.py + - run: python3 scripts/validate_release_disclosures.py + - run: python3 scripts/verify_hand_checks.py + - run: npm test + - run: python3 scripts/build_pages.py + - run: python3 scripts/validate_pages_artifact.py + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: _site + + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.gitignore b/.gitignore index 12ff667..89019bc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .DS_Store .AppleDouble .LSOverride +_site/ diff --git a/CALCULATION_MODEL.md b/CALCULATION_MODEL.md new file mode 100644 index 0000000..972d178 --- /dev/null +++ b/CALCULATION_MODEL.md @@ -0,0 +1,37 @@ +# Gridshift calculation contract + +This document describes the deterministic model in `core.js` (calculation version 1.2). **No independent qualified power-system engineering or climate/accounting review has been completed.** The model is an exploratory planning aid, not approved for utility investment, engineering, or regulatory use. + +## Emissions + +- Asset annual SF₆ loss is either the entered measured mass (`kg/year`) or nameplate capacity (`kg`) multiplied by the entered annual loss fraction. +- The baseline applies that annual loss in every year of the planning horizon. It assumes the entered annual rate remains constant; it does not age, decay, or otherwise forecast the loss rate. +- Annual CO₂-equivalent emissions are `annual SF₆ loss (kg) × SF₆ GWP₁₀₀` and are reported internally in `kg CO₂e`. +- The default for new projects is 24,300 over 100 years, from IPCC AR6 WGI Supplementary Material Table 7.SM.7 ([official table](https://www.ipcc.ch/report/ar6/wg1/downloads/report/IPCC_AR6_WGI_Chapter07_SM.pdf)). The exact value and source can be changed in project assumptions. +- A replacement is modeled at the start of its assigned year: normal annual SF₆ leakage is omitted in that year, and end-of-life emissions are `remaining SF₆ mass × (1 − recovery efficiency) × GWP`. +- From the replacement year onward, annual alternative equipment emissions are added when a profile value is supplied. Unknown alternative emissions are flagged as incomplete. +- The model does not currently include manufacturing, construction, upstream gas production, grid dispatch effects, or other lifecycle emissions unless a user-entered alternative annual emissions value represents them. Profile fields do not guarantee that it does. + +## Costs + +- Baseline annual cost is the sum of entered asset operating and maintenance costs. +- In a replacement year, scenario cost adds replacement capital, installation, decommissioning, gas recovery, and the selected technology's annual operating and maintenance costs. Later years use the profile's annual operating and maintenance costs. +- A technology residual value is credited in the final modeled year for a replacement scheduled within the planning horizon. +- Net present cost discounts each year's modeled cost from the base year: `Σ cost(year) / (1 + discount rate)^(year − base year)`. The first modeled year has exponent zero. +- Incremental net present cost is scenario NPC minus continued-operation NPC. The annual budget check compares only replacement capital expenditure with the scenario budget; it does not limit operating cost. +- Blank cost fields remain unknown for new and imported records and cause the result to be flagged partial. This includes replacement technology residual value whenever the technology is scheduled within the modeled horizon. Enter zero when there is no residual value. An entered zero is treated as a deliberate zero. Older versions stored blank costs as zero; Gridshift migrates those project fields to unknown and marks affected saved snapshots for review without changing their stored calculation inputs. + +## Scenarios and incomplete data + +- A saved scenario stores asset and technology inputs, emissions assumptions, currency, price year, discount rate, planning years, calculation version, and replacement assignments. +- Existing scenarios keep their saved values when shared project assumptions change. The previous Gridshift 25,200 default is migrated to 24,300 at the project level, while saved scenarios with that value keep their number and receive a review warning. +- Missing annual loss, end-of-life recovery, alternative emissions, or cost data is reported as incomplete. Cost per tonne avoided is unavailable when the calculation is incomplete or avoided emissions are not positive. Other partial totals remain visible and must be read with their warnings. +- Technology comparisons and candidate rankings are preliminary data screens; they do not determine equipment compatibility or engineering approval. + +## Open review decisions + +Before results from this model inform operational, investment, or regulatory decisions, qualified power-system and climate/accounting reviewers must confirm the time convention, emissions boundary, treatment of end-of-life gas and alternative gases, cost categories, residual value, annual budget definition, discounting convention, and the applicability of the selected GWP metric. Jurisdictional reporting requirements and project-specific manufacturer evidence also require review. + +The repository's unit tests check arithmetic and selected boundary cases. `scripts/verify_hand_checks.py` separately reproduces the release packet's example arithmetic using Decimal operations. These checks do not replace an independent domain review or validate real asset data. + +The current product stores a single-browser workspace in local storage and limits serialized app data to approximately 3 MB. This is a conscious first-release constraint for modest planning workspaces; larger portfolios require IndexedDB or a separately reviewed shared-data architecture. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a424c58..56a89f6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ Thanks for your interest in improving Gridshift. Bug reports, thoughtful feature ## Running Gridshift locally -Gridshift is a static web app with no package installation or build step. From the repository root, run: +Gridshift is a static web app with no runtime dependencies or build step. From the repository root, run: ```sh python3 -m http.server 8000 @@ -28,6 +28,8 @@ python3 -m http.server 8000 Open [http://localhost:8000](http://localhost:8000). A local server is needed to exercise service-worker installation and offline caching. You can open `index.html` directly for a quick visual check. +With Node.js 22 or later, run `npm test` for calculation, CSV, backup-validation, and service-worker checks. Run `python3 scripts/validate_pwa.py` to verify the manifest and install assets. Browser install, offline, and update behavior still needs a browser smoke check. + Before submitting, review your change in a current browser and check the relevant workflow. If you cannot check a particular browser or workflow, mention that in the pull request. ## Pull request expectations diff --git a/README.md b/README.md index 71e0998..0a7fe3d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Gridshift is a local-first planning workspace for electricity teams exploring th **Build an inventory. Compare alternatives. Shape a transition plan.** +> **Independent review status: not independently reviewed.** No independent qualified power-system engineering or climate/accounting review has been completed. Gridshift is for exploratory estimates only. Verify assumptions and obtain qualified review before operational, investment, or regulatory decisions. + ## What you can do - **Understand the portfolio.** Organize equipment by site and capture ratings, installation and retirement dates, condition, and annual SF₆ loss. @@ -21,6 +23,8 @@ Gridshift is a local-first planning workspace for electricity teams exploring th - **Keep a reviewable record.** Inspect assumptions and calculation notes, export inventory and scenario CSVs, and save or restore a complete JSON backup. - **Work locally.** Project data stays in this browser. No account or cloud sync is required. +The default SF₆ GWP₁₀₀ assumption is **24,300**, from IPCC AR6 WGI Supplementary Material Table 7.SM.7 ([official source](https://www.ipcc.ch/report/ar6/wg1/downloads/report/IPCC_AR6_WGI_Chapter07_SM.pdf)). New projects use this value. When an older project still has Gridshift’s prior 25,200 default and its matching source label, Gridshift updates the project assumption and marks saved scenario snapshots for review. The old scenario value is retained so its historical calculation remains reproducible; edit and save that scenario to recalculate it. + ## A straightforward planning flow 1. Create a project and set its planning horizon, currency, and emissions factor assumptions. @@ -47,7 +51,7 @@ The app icon is maintained in `icon.svg`; `assets/gridshift-mark.svg` is the tra ## Try Gridshift -Gridshift is a static web app. For a full local experience, including offline caching, serve the project directory over localhost: +Gridshift is a static web app with no build step or runtime dependencies. For a full local experience, including offline caching, serve the project directory over localhost: ```sh python3 -m http.server 8000 @@ -55,18 +59,30 @@ python3 -m http.server 8000 Then open [http://localhost:8000](http://localhost:8000). You can also open `index.html` directly for a quick preview; service-worker installation and offline caching require localhost or HTTPS. +### Release support target + +The release target is current and previous major versions of desktop Chrome, Edge, Firefox, and Safari, plus current iOS/iPadOS Safari and Android Chrome. Install and offline behavior must be checked on each supported platform before a production release. The planned public host is GitHub Pages at `https://boredpolymath.github.io/Gridshift/`; local development uses localhost. The app uses relative URLs for the project-site path, which still needs live browser verification. + +The repository includes a GitHub Actions Pages workflow. Repository Settings → Pages must select GitHub Actions as the publishing source before deployment. GitHub Pages does not expose arbitrary response-header configuration; see [RELEASE_RUNBOOK.md](RELEASE_RUNBOOK.md) for the accepted header limitation and launch checks. + +The service worker caches the current app shell for offline use and checks for a newer version. When an update is ready, choose **Update ready · Reload** to activate it. The app does not synchronize local project data between browsers or devices. + ## Designed for transparent planning -Gridshift keeps measured annual losses separate from estimated loss rates, shows incomplete inputs, and preserves key assumptions with saved scenarios. Its estimates can support early planning and comparison; they do not replace engineering studies, manufacturer documentation, regulatory review, or approval by qualified professionals. Manufacturing and construction emissions are not included in the current model. +Gridshift keeps measured annual losses separate from estimated loss rates, shows incomplete inputs, and preserves key assumptions with saved scenarios. See [CALCULATION_MODEL.md](CALCULATION_MODEL.md) for the current equations, boundaries, and open review decisions. Its estimates can support early planning and comparison; they do not replace engineering studies, manufacturer documentation, regulatory review, or approval by qualified professionals. Manufacturing and construction emissions are not included in the current model. ## Your data, in your browser -Gridshift stores project data in browser-local storage. It does not sync project data to a server. Browser storage can be cleared or evicted, so export a JSON backup and store it securely. Local storage is not an enterprise access-control or encryption system; use care on shared devices. +Gridshift stores modest project workspaces in browser-local storage, with a 3 MB serialized-data ceiling to leave room under typical browser quotas. Larger portfolios should be split into smaller workspaces; IndexedDB or a managed data service would be needed for a higher-volume release. It does not sync project data to a server. Browser storage can be cleared or evicted, so export a JSON backup and store it securely. Local storage is not an enterprise access-control or encryption system; use care on shared devices and browser profiles. Browser extensions granted access to this site may read or change site data or page content ([Chrome host permissions](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions), [MDN content scripts](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)). Use only trusted extensions in a profile that holds planning records. Downloaded JSON backups contain readable project data, are not encrypted by Gridshift, and must be protected or deleted separately. + +The planned GitHub Pages URL is under `boredpolymath.github.io`. Other pages on that exact host share the browser storage origin even when their URL paths differ. Code on another page served from that host can read, change, or delete Gridshift data if you visit it in the same browser profile. This does not apply to unrelated website origins. Do not store confidential utility records on the planned host unless every publisher and page on that origin is trusted; a dedicated Gridshift hostname is required to isolate the browser storage. + +The app code does not send project data to an application server or analytics service. GitHub says it logs and stores visitors' IP addresses for security when a GitHub Pages site is visited ([Pages data collection](https://docs.github.com/en/pages/getting-started-with-github-pages/what-is-github-pages#data-collection)); its documentation does not state a Pages-specific retention period. Review [GitHub's Privacy Statement](https://docs.github.com/en/site-policy/privacy-policies/github-privacy-statement) before using the public site. The app provides local export and deletion controls; deleting browser data does not remove downloaded backup files. ## Project policies -Contributions are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). For vulnerability reports, follow [SECURITY.md](SECURITY.md). Gridshift is released under the [MIT License](LICENSE). +Gridshift is maintained by **Bored Polymath Studios**. For bugs and product feedback, use the repository's [issue templates](https://github.com/boredpolymath/Gridshift/issues/new/choose); do not include private utility records. No separate support email was provided for this release. For vulnerability reports, follow [SECURITY.md](SECURITY.md). Gridshift is released under the [MIT License](LICENSE). --- -**Gridshift is a planning prototype.** Results depend on the assumptions and source data entered by the user and should be independently reviewed before they inform investment or operational decisions. +**Gridshift is an explicitly unreviewed planning tool.** Results depend on the assumptions and source data entered by the user. No independent qualified power-system engineering or climate/accounting review has been completed; do not use these estimates alone for operational, investment, or regulatory decisions. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..7f75d6c --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,52 @@ +# Release notes + +## 0.2.3 — explicitly unreviewed release candidate + +- Disclose that pages on the planned `boredpolymath.github.io` host share the browser storage origin, and warn against storing confidential records there unless all same-origin publishers are trusted. +- Bump the app version to 0.2.3 and the service-worker cache to v8 so installed users can receive the updated privacy guidance through the user-controlled update flow. +- Record the owner's 2026-11-03 decision to retain the shared Pages origin and accept its localStorage exposure, with the warning visible and confidential utility records excluded unless all same-origin publishers are trusted. + +This is not a published release. Detailed browser records, live Pages checks, remaining manual reviews, and final deployment approval remain open. + +## 0.2.2 — explicitly unreviewed release candidate + +- Make the absence of independent power-system engineering and climate/accounting review prominent on every app screen and in scenario-results CSV exports. +- Revise the owner-approved launch criteria to permit public release with the model explicitly labeled unreviewed; retain exploratory-use boundaries and require qualified review before operational, investment, or regulatory decisions. +- Bump the service-worker cache to v7 for the current disclosure, contrast, and user-controlled update changes. +- Keep a waiting update action visible after navigating between screens, until the user accepts it. +- Wrap long workspace names and stack planning panels at tablet widths to prevent horizontal page overflow. +- Improve contrast for table headings, screening notices, source links, metric icons, the breadcrumb separator, and mobile inventory Remove actions after local seven-screen desktop and mobile probes. +- Keep Reports within narrow mobile viewports for large supported-range values by wrapping metric values, stacking report cards, and sizing cumulative-chart axes from their labels; verified all seven screens at five viewport widths with synthetic boundary inputs. +- Build and validate the exact allowlisted Pages artifact in both quality CI and deployment, rejecting missing, extra, modified, or symbolic-link assets before publication. + +This is not a published release. Utility-user feedback, detailed browser records, live Pages deployment checks, and final release-owner approval remain open. + +## 0.2.1 — release-readiness work in progress + +- Treat an unknown replacement technology residual value as incomplete lifecycle cost data; enter zero to explicitly state there is no residual credit. +- Migrate ambiguous legacy residual-value zeroes to unknown and flag saved scenario snapshots for review. +- Add dialog focus restoration, including a page-heading fallback when an action replaces its invoking control. +- Add public-release social-card metadata and package the branded preview image in the GitHub Pages artifact. +- Bump the service-worker cache so users can receive this app and calculation update through the user-controlled update flow. +- Add a separate Decimal-based arithmetic check for the reviewer packet examples and run it in CI before deploy. + +This is not a published release. Independent domain review, utility-user review, browser testing, and production hosting checks remain open. + +## 0.2.0 — release-readiness work in progress + +- Corrected new-project SF₆ GWP₁₀₀ default to 24,300 and linked the official IPCC AR6 WGI supplementary table. +- Preserved old scenario calculations while marking legacy factor and ambiguous zero-cost inputs for review. +- Kept blank cost inputs unknown, reported missing cost categories as partial, and fixed the final-year residual value boundary. +- Added complete backup preview and deeper nested record validation, CSV limits/validation, spreadsheet formula escaping, and damaged-storage recovery. +- Added mobile access to project switching and data tools, site/scenario deletion, keyboard state labels, and update/install UI. +- Added raster and maskable PWA icons, an explicit versioned service-worker update flow, core regression tests, and CI checks. +- Added [CALCULATION_MODEL.md](CALCULATION_MODEL.md), [RELEASE_READINESS_CHECKLIST.md](RELEASE_READINESS_CHECKLIST.md), and [RELEASE_RUNBOOK.md](RELEASE_RUNBOOK.md). + +This is not a published release. Domain approval, accessibility/browser testing, production hosting, and the release-owner sign-off are still required. + +## Release preparation + +- Added a GitHub Pages workflow for the public project site and a minimal, explicit static artifact builder. +- Bounded imported scenario snapshot assumptions and added a calculator guard against unsupported horizons. +- Added a reviewer packet with independent hand-check examples and a browser/device session record. +- Documented the GitHub Pages response-header limitation and the accepted launch risk. diff --git a/RELEASE_READINESS_CHECKLIST.md b/RELEASE_READINESS_CHECKLIST.md new file mode 100644 index 0000000..0ee703f --- /dev/null +++ b/RELEASE_READINESS_CHECKLIST.md @@ -0,0 +1,156 @@ +# Gridshift PWA: prototype to release checklist + +Updated 2026-11-03 after implementation and repository-level validation. `[x]` means implemented or documented in the repository; relevant code checks are listed below. It does not mean a human, browser, or production review has passed. `[ ]` items in “Release gates still open” remain launch gates. Hosting target is GitHub Pages; Bored Polymath Studios is the release owner. The owner revised the criteria to permit an explicitly unreviewed release; browser-session details and a live deployment remain outstanding. + +## 1. Product scope and launch decision + +- [x] Record a first-release scope: single-device, browser-local tool for exploratory SF₆ transition planning, with projects, sites, assets, technology profiles, scenarios, reports, and CSV/JSON exchange. See `README.md`. +- [x] Record the storage decision and constraint: modest workspaces up to about 3 MB serialized in browser local storage; larger portfolios need IndexedDB or a separately reviewed shared-data design. See `CALCULATION_MODEL.md` and `README.md`. +- [x] Document intended browser families and HTTPS hosting. GitHub Pages serves the project at `/Gridshift/`; the app uses relative URLs and the release workflow packages only the app shell. Verify this path on the live site before release. +- [x] State that outputs are estimates for exploratory planning, not engineering approval, certified compliance, or formal investment advice. See README and in-app report/disclaimer language. +- [x] Decide the release audience and hosting target: public release on GitHub Pages. Bored Polymath Studios is the release owner; the repository issue templates are the support/feedback route, with no separate support email. +- [x] Resolve the shared-origin localStorage release decision: on 2026-11-03 Bored Polymath Studios chose to keep the GitHub Pages URL and explicitly accepted that any page on `boredpolymath.github.io` can access Gridshift browser storage when opened in the same profile. Keep the disclosure visible; do not store confidential utility records there unless all same-origin publishers are trusted. The code cannot isolate localStorage by project path. +- [x] Draft concrete release acceptance criteria in `RELEASE_REVIEW_PACKET.md`; Bored Polymath Studios approved them on 2026-11-03. +- [x] Revise the acceptance criteria to permit a public release without independent domain reviewers, provided the app and its documentation/exports clearly disclose that no qualified power-system engineering or climate/accounting review has occurred and limit outputs to exploratory use. +- [x] Assign acting ongoing owners for support, security updates, browser support, and calculation-source updates to Bored Polymath Studios, the current sole developer; no backup maintainer is named. +- [ ] Walk through the workflow with representative utility users; verify labels, data requirements, defaults, ranking, and reports against their planning process. Bored Polymath Studios confirmed on 2026-11-03 that no session is arranged. +- [x] Prepare a utility-user session protocol in `RELEASE_REVIEW_PACKET.md`, including sample-data tasks, think-aloud observations, completion criteria, and follow-up questions. The participant review itself remains open. +- [x] Confirmed current scenario cards are sufficient for launch; dedicated side-by-side report is not a launch requirement. Reports compare the selected scenario with the baseline. + +## 2. Core planning workflows + +- [x] Create and edit projects; switch, duplicate, and delete projects with confirmation. Manage sites, assets, technology profiles, and scenarios; destructive actions confirm and preserve or explain related records. +- [x] Import asset CSV; export inventory and scenario results CSV; export and restore JSON backups with preview and conflict choices. +- [x] Compare scenarios with continued operation, view a roadmap and reports, and retain scenario input snapshots and calculation versions. +- [x] Keep sample data illustrative and disclose that users must replace it with verified project data. +- [x] Show incomplete inputs and legacy assumption warnings in calculations and relevant views. Blank costs are unknown; they are not silently treated as zero. +- [ ] Review full lifecycle-cost coverage and assumptions with domain users, including replacement timing, cost categories, discounting, residual value, price year, and budget constraints. +- [ ] Review ranking criteria, score normalization, weights, missing-data behavior, and explanation with domain users. +- [x] Exercise first-run, project switching, empty states, validation errors, import conflicts, storage-full failures, and offline recovery in local Chromium against the built Pages artifact. Supported-browser/device and independent repeat coverage remain open. + +## 3. Calculation correctness and evidence + +- [x] Document the model equations, units, time conventions, replacement-year treatment, baseline, recovery, alternative emissions, discounting, costs, budget check, and residual-value behavior in `CALCULATION_MODEL.md`. +- [x] Correct the default SF₆ GWP₁₀₀ to 24,300 and cite IPCC AR6 WGI Supplementary Material Table 7.SM.7. The source/value are linked in README and recorded in the model document. +- [x] Prepare [RELEASE_REVIEW_PACKET.md](RELEASE_REVIEW_PACKET.md) with independent hand-check values and fields for reviewer decisions and browser/device sessions. +- [x] Add an external reviewer request template and qualifications/scope guidance to `RELEASE_REVIEW_PACKET.md`. +- [x] Define code behavior for missing/invalid values and selected boundary cases; unknown inputs surface as incomplete, unsupported negative values are rejected, and incomplete lifecycle costs suppress cost-per-tonne results. +- [x] Display manufacturing/construction scope limits in the app and include the lifecycle boundary in scenario CSV exports. +- [x] Include units, period, currency/price year, factor/model provenance, and review flags in reports and result exports where applicable. +- [x] Preserve saved scenario snapshots and calculation versions; migrate prior project GWP defaults while flagging older scenario snapshots and ambiguous legacy zero costs for review. +- [x] Label technology screening as a preliminary recorded-data screen; do not describe a profile as engineering reviewed without a project-team review record. +- [x] Show a persistent in-app status that no independent qualified power-system or climate/accounting review has been completed; include the same status in the README, model document, and scenario-results CSV. Keep the exploratory-use and qualified-review-before-decisions limitation explicit. +- [x] Reproduce the release packet's calculation examples with a separate Decimal-based arithmetic check and matching unit assertions; this verifies arithmetic only and is not domain approval. + +## 4. Data handling and resilience + +- [x] Keep records in browser local storage; provide a storage estimate, CSV export, JSON backup, and JSON restore. +- [x] Decide and document the 3 MB first-release local-data limit and when a different storage architecture is needed. +- [x] Add recovery handling for unavailable/corrupt storage, quota/save errors, cross-tab changes, and explicit user-directed clearing; preserve recoverable raw data when parsing fails. +- [x] Validate backup structure, nested scenarios, identifiers/references, ranges, counts, and size before restore; preview merge/replace choices and block oversized merges before mutation. +- [x] Verify in local Chromium that malformed JSON restore does not open a preview or alter stored data, and a 1.53 MB CSV that would push a workspace over the 3 MB limit is rejected without partial import or storage mutation. +- [x] Verify local JSON restore conflict choices in Chromium: cancel preserves the original workspace; import-as-separate adds a copy with a new project ID; replace changes the matching project only after explicit confirmation. +- [x] Bound scenario snapshot years, horizon, discount, GWP, currency, and price year; reject invalid horizons again in the calculator before array allocation. Regression tests cover empty replacement maps and malformed snapshot fields. +- [x] Validate CSV headers, rows, fields, ranges, limits, JSON custom attributes, and malformed quoting; handle BOM, quoted fields/newlines, and formula-leading export cells. Automated tests cover representative cases. +- [x] Confirm site, asset, technology, scenario, project, and all-data deletion paths before destructive changes; site deletion reassigns attached assets to Unassigned. +- [x] Explain browser/device-local scope, no cloud sync, lack of encryption/access control, export/restore, and product privacy behavior in README/in-app settings. +- [x] Release owner reports personally testing the listed app flows across Android, iOS, macOS, Windows, Linux, and ChromeOS, including install/offline/update, data import/export/restore, and accessibility checks. See the owner-reported rows in `RELEASE_REVIEW_PACKET.md`. +- [x] Run local Chromium storage-recovery checks against built `_site`: corrupt JSON remained available as an exact recovery download until explicit confirmation cleared it; denied storage and quota errors produced warnings while preserving current-tab state; edits and confirmed clearing propagated to a second open tab. +- [ ] Record owner device models, browser versions, test date, build/URL, and detailed results; exercise storage eviction, private browsing, and representative large workspaces on the supported matrix. Device/session details were intentionally marked `not recorded` by the owner on 2026-11-03; independent repeat testing remains open. Malformed restore and an oversized workspace import were exercised in local Chromium, as recorded below. +- [x] Disclose GitHub Pages visitor-IP logging in README and record that the Pages docs do not specify a retention period. +- [x] Owner accepts GitHub Pages visitor-IP logging and the lack of a Pages-specific retention period as host behavior; the app itself does not transmit project data. + +## 5. PWA install, offline use, and updates + +- [x] Include a manifest, standalone display, app metadata, service worker, 192/512 raster icons, maskable icon, favicon, and Apple touch icon. `python3 scripts/validate_pwa.py` checks asset sizes/references, service-worker registration and required shell entries, and confirms the worker plus all precache assets are present in the Pages allowlist. +- [x] Provide an install action with browser-specific Add to Home Screen guidance when the install prompt API is unavailable. +- [x] Implement a versioned shell cache, optional-asset resilience, app-owned cache cleanup, cache-first same-origin assets, and a user-controlled update/reload action. +- [x] Increment the shell-cache version to v8 for app version 0.2.3, including the shared-origin privacy disclosure, so existing installations can discover the current shell. PWA asset validation, exact Pages artifact validation, local v8 offline smoke, and staged v7→v8 update acceptance pass. +- [x] Simulate a staged update against the built Pages artifact in local Chromium: v6 remained active while v7 waited, the update action remained visible after navigating to Settings, and accepting it reloaded a v0.2.3 fixture while preserving project data and removing the old owned cache. Production Pages update behavior remains unverified. +- [x] Unit-test worker optional asset failure, scoped cache deletion, explicit skip-waiting, and navigation caching. +- [x] Exercise offline editing, CSV import/export, scenario-results CSV export, JSON backup/restore, offline reload, and an uncached request against the built `_site` artifact under `/Gridshift/` in local Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64. Local data and exports passed; the uncached request failed with the expected network `TypeError`; no page errors occurred. This is one local browser profile, not cross-browser/device or live Pages evidence. +- [x] Verify the v7 worker from the built `_site` at a local HTTP `/Gridshift/` path in Chromium 148.0.7778.96: the worker controlled the page, installed `gridshift-shell-v7`, a sample project was saved, offline reload reopened the dashboard, Settings navigation worked offline, and the saved project remained. No page errors occurred. This is historical v7 evidence; GitHub Pages and native installation remain unverified. Current v8 offline and staged-update checks are recorded below. +- [x] Verify v8 from the built `_site` at a local HTTP `/Gridshift/` path in Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64: a fresh profile installed `gridshift-shell-v8`, loaded the sample workspace, displayed the version and same-origin warning in Settings, had no horizontal overflow at 390×844, and reloaded offline to Dashboard; Settings remained accessible through the mobile More menu offline. No page errors occurred. This does not verify GitHub Pages or native installation. +- [x] Simulate the current staged v7→v8 update under local `/Gridshift/`: v7 remained active while v8 waited, the update action stayed visible after navigation to Settings, and accepting it activated v8, removed the v7 cache, preserved the exact saved sample-project JSON, and reloaded with version 0.2.3 visible in Settings. Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64; no page errors. Production-host and native-device behavior remain unverified. +- [ ] Test install, launch, update, uninstall/reinstall, and offline behavior on supported desktop browsers, iOS/iPadOS Safari, and Android Chrome. +- [x] Add a GitHub Pages Actions deployment workflow and a minimal app-shell packaging script. Actions are pinned to immutable SHAs. +- [x] Document Pages project path, HTTPS, MIME types, relative URLs, rollback, and response-header limitations in `RELEASE_RUNBOOK.md` and `SECURITY.md`. +- [ ] Publish the prepared workflow and select GitHub Actions as the repository Pages source. The earlier 2026-11-03 repository check reported Pages disabled. A later same-day GitHub API recheck found zero Actions runs and no `.github/workflows` directory on remote `main`; the available web tool could not open the Pages URL, so its HTTP status is not established. After deployment, verify headers, manifest/worker MIME types, `/Gridshift/` URLs, HTTPS, update behavior, and rollback. + +## 6. Accessibility, usability, and compatibility + +- [x] Add responsive navigation support, current-page semantics, reduced-motion handling, and a mobile More menu for secondary actions. +- [x] Fix identified small-text contrast pairs in mobile inventory/ranking cards; retain visible focus styling and labels in reviewed source. +- [x] Implement dialog focus restoration to the invoking control, with a page-heading fallback if the control was replaced. Browser and assistive-technology validation remains open. +- [x] Release owner reports personally completing accessibility checks on the listed operating systems. +- [ ] Record keyboard-only and screen-reader/browser/assistive-technology details, issues, and results; qualified independent accessibility review remains open. +- [ ] Complete full-interface contrast, text resizing, browser zoom, and WCAG 2.2 AA review against a defined target. A local Chromium text scan is recorded below, but it checks only visible text against composed solid ancestor backgrounds and does not model gradients, images, overlays, text resizing, zoom, or assistive technology. +- [x] Verify native required-field focus, retention after a custom validation error, successful-save heading fallback, and close/cancel focus restoration in local Playwright Chromium 148 on macOS 27.2 arm64; other browser and assistive-technology behavior remains open. +- [x] Run a local DOM accessibility smoke probe at 390×844 on Dashboard, Assets, Tech, Plan, Roadmap, Reports, and Settings: zero unnamed buttons, unlabeled form fields, or images without alt attributes; each screen's document width stayed within the viewport. This source-level check does not establish keyboard, screen-reader, contrast, or WCAG conformance. +- [x] Exercise all seven screens at 320, 360, 390, 768, and 1280 px with a 173-character project name and 120 imported assets; no document horizontal overflow. Visually inspect the 320 px and 768 px render. This exposed and fixed long-name overflow in the top bar, project selector, and tablet page header. +- [x] Audit visible buttons and form controls on all seven screens at 390 and 1280 px against a 24×24 CSS-pixel target threshold. Site Edit/Remove buttons were 22 px high; setting a 24 px minimum removed all below-threshold findings. Reduced-motion emulation reported the media query active, `scroll-behavior: auto`, and near-zero button transition duration. +- [x] Scan visible text on Dashboard, Inventory, Technology, Scenarios, Roadmap, Reports, and Settings in local Chromium 148.0.7778.96 at 1280×900 and 390×844, under light and dark color-scheme emulation. The solid-background probe found and fixed low-contrast table headings, a screening notice, the IPCC source link, metric icons, the breadcrumb separator, and mobile inventory Remove actions; the rerun reported zero below-threshold text pairs across all 28 screen/viewport/scheme combinations. Gradients, images, overlays, text resizing, browser zoom, and WCAG conformance are not covered. +- [x] Run a focused local keyboard smoke: Tab/Enter opens the project chooser, starts project creation, and submits the form; at 390 px, keyboard navigation opens the mobile More dialog, Escape closes it, and focus returns to More. Full keyboard-only coverage remains open. +- [ ] Check unusual values, browser zoom, locales, currencies, and browser-specific behavior in the supported matrix; those checks remain open. Local empty-state and three locale/currency checks are recorded below but do not complete the matrix. +- [x] In local Chromium 148 at 390×844 under `/Gridshift/`, create an empty project and open all seven screens, including Settings through More; expected empty cards appeared on Dashboard, Inventory, Technology, Scenarios, and Reports, and all screens stayed within the viewport. On the sample scenario, `en-US`/USD, `fr-FR`/EUR, and `ja-JP`/JPY displayed the locale-appropriate currency mark/grouping without overflow or page errors. These checks do not cover other browsers, zoom, or unusual input values. +- [x] Exercise supported-range synthetic boundary values on all seven screens at 320, 390, 640, 768, and 1280 px in local Chromium 148. The first 320 px Reports render overflowed with large metric values; wrapping report metrics into one mobile column and sizing cumulative-chart axes from their labels fixed the issue. The rerun passed all 35 screen/viewport combinations with no horizontal overflow or page errors. This is a layout check with synthetic extremes, not domain validation, cross-browser coverage, or zoom testing. + +## 7. Security and abuse resistance + +- [x] Retain escaped user text in reviewed render paths, a declared CSP, and private vulnerability reporting guidance in `SECURITY.md`. +- [x] Validate untrusted imported data, lengths, numeric ranges, references, object counts, file sizes, malformed backups, and CSV content before mutation/storage. +- [x] Record dependency and asset provenance policy: no runtime/build dependencies; CI actions are pinned to immutable commit SHAs and Dependabot checks GitHub Actions weekly. +- [x] Document why inline styles remain and the production response headers required in `SECURITY.md` and `RELEASE_RUNBOOK.md`. +- [x] Complete a repository-wide security scan (report dated 2026-11-03) and source-level diff reviews of the 0.2.1 and later working-tree snapshots, including imports/exports, CSP, service worker, CI/deploy permissions, release tooling, disclosure UI, and validators. The scan reported the shared-origin localStorage exposure, now disclosed with an open owner/hosting gate. No source-backed XSS/import injection, worker/cache, CI permission, or credential finding was reported. Neither source review verifies a live browser or Pages deployment. +- [ ] Verify CSP behavior and actual response headers against GitHub Pages on the live site. +- [x] Document shared-device, browser-extension, downloaded-backup, and local-data exposure guidance in README, Settings, and SECURITY.md; cite official browser-extension permissions guidance. The owner approved this wording on 2026-11-03. +- [x] Review the shared-device, browser-extension, downloaded-backup, and local-data exposure guidance with the product owner; Bored Polymath Studios approved the wording on 2026-11-03. +- [x] Disclose the planned GitHub Pages same-origin boundary in README, Settings, and SECURITY.md after a repository-wide source review identified it. Owner review of this additional risk is pending and its release gate remains unchecked in section 1. + +## 8. Quality, operations, and release process + +- [x] Add Node built-in tests for calculation logic, migrations, validation, CSV handling, and service-worker behavior; add GitHub Actions CI with syntax, PWA asset, and exact built Pages artifact validation. +- [x] Add a release smoke-test checklist and rollback instructions in `RELEASE_RUNBOOK.md`. +- [x] Keep telemetry/error reporting out of the app; README says no app analytics or server-side project data. Hosting logs remain subject to provider policy. +- [x] Add version `0.2.3` release notes and visible app/model versions `0.2.3` / `1.2` in Settings. This is a pre-release work version, not a published release. +- [x] Update README, in-app help/settings, model limits, privacy/data handling, browser targets, and backup guidance for consistency. +- [x] Document the owner and existing GitHub issue/private vulnerability-report routes; no separate support contact was provided. +- [x] Record acting owners for support, security updates, browser support, and calculation-source updates: Bored Polymath Studios, currently the sole developer; no backup maintainer is named. Reassign if ownership changes. +- [x] Add Open Graph and social-card metadata using the planned GitHub Pages URL and existing branded hero image. App-store install screenshots do not apply to the Pages-only launch channel. +- [ ] Run CI and the Pages workflow in the GitHub repository and pass the manual smoke checklist on the live Pages site. +- [ ] Tag and archive a reproducible release source/artifact after all human, browser, owner, and hosting gates pass. + +## Validation evidence completed in this workspace + +- The built-in Node test runner executed `tests/core.test.cjs` and `tests/service-worker.test.cjs` through `node:test.run`: all 19 tests passed on 2026-11-03. This run caught and fixed a stale service-worker assertion that did not expect v7 cache cleanup after advancing the active cache to v8. The shell does not provide `node` or `npm`, so the package's exact `npm test` command and GitHub Actions runner still need to run in CI. +- `python3 scripts/validate_pwa.py`: passed manifest, icon-size/dimension, asset-reference, script-order, service-worker registration, required-shell, precache existence, and Pages-allowlist coverage checks. A negative check confirmed it rejects an allowlist that omits `sw.js`. +- `python3 scripts/validate_release_disclosures.py`: verifies the explicit unreviewed status and local-data/extension/backup disclosures are present in the app, scenario-results CSV export, README, model documentation, security policy, and approved release packet. +- `python3 scripts/verify_hand_checks.py`: independently reproduced the release packet's baseline and replacement emissions/cost examples; it does not replace domain review. +- Ruby YAML parsing passed for both Actions workflows and all three issue-template YAML files. The five unique immutable action SHAs in the local workflows resolve to commits in their official GitHub action repositories; this does not mean a workflow has run. +- `python3 scripts/build_pages.py`: produced the minimal Pages shell; all 12 allowlisted files, including the social preview image, were present in `_site`. +- `python3 scripts/validate_pages_artifact.py`: after the Pages build, verifies all 12 allowlisted files are present, no unapproved files or symbolic links are included, and every artifact file is byte-identical to its source. Both CI and Pages workflows now run this check after building the artifact; remote CI has not run because the workflows are not yet present on GitHub `main`. +- Local Playwright 1.60.0 with Chromium 148.0.7778.96 on macOS 27.2 arm64 loaded the `/Gridshift/` path, displayed the unreviewed banner, loaded the sample workspace and report, exported CSV with the review-status row, cached the required shell, and reopened offline. A staged local v6→v7 update kept v6 active until user acceptance, kept the update action visible after navigation, then reloaded with project data preserved and the old cache removed. A later run against the allowlisted `_site` artifact at `/Gridshift/` also verified offline asset editing and persistence across reload, CSV import and inventory export, scenario-results CSV export, JSON backup, and restoration into a separate profile containing an unrelated sample project. The service worker controlled the page; an uncached request failed with the expected network `TypeError`; no page errors occurred. A 390×844 view was inspected; the initial screenshot exposed a low-contrast banner, which was corrected and re-rendered with light text on a dark panel. Required-field focus, validation-error data retention, save-heading fallback, and dialog close/cancel focus restoration passed. Separate v8 runs against the current built artifact verified cache installation, the shared-origin Settings warning, 390 px no-overflow, offline reload, offline navigation to Settings, and user-controlled v7→v8 update acceptance with local project data preserved. Native install/update lifecycle on supported devices, storage eviction/private-browsing behavior, screen reader, and live hosting were not tested. +- A separate local DOM smoke probe on those seven screens at 390×844 found zero unnamed buttons, unlabeled form fields, or images missing an `alt` attribute, with no horizontal document overflow. It does not check semantic reading order, keyboard-only operation, screen-reader output, full contrast, or WCAG conformance. +- A local Playwright layout probe checked all seven screens at 320, 360, 390, 768, and 1280 px with a 173-character project name and 120 imported assets. It first exposed document overflow caused by project-name text and tight tablet columns; CSS wrapping and the tablet stacking breakpoint fixed it. The rerun found no document overflow at any of the 35 screen/viewport combinations, and the 320 px and 768 px screenshots were visually inspected. This does not cover browser zoom or other browser engines. +- A local control-size probe checked visible buttons and form controls on all seven screens at 390 and 1280 px. After increasing site-row action buttons to 24 px minimum height, no checked control was below 24×24 CSS px. Emulated reduced motion activated the preference, used `scroll-behavior: auto`, and reduced button transitions to 0.00001 seconds. This does not establish WCAG conformance or screen-reader support. +- A local Chromium 148.0.7778.96 scan checked visible leaf text against composed solid ancestor backgrounds across all seven screens at 1280×900 and 390×844 in light and dark color-scheme emulation. It initially found low-contrast table headings, notice text, an external source link, metric icons, the breadcrumb separator, and mobile inventory Remove actions. These pairs were corrected; the rerun found zero below-threshold text pairs in the 28 screen/viewport/scheme combinations. The probe does not model gradients, images, overlays, browser zoom, text resizing, or assistive technology and is not a WCAG audit. +- Local Chromium keyboard smoke used Tab and Enter to open the project chooser, start a project form, type a name, and submit; at 390 px it opened the More dialog and used Escape to close it, with focus restored to the invoking control. It does not cover all form, confirmation, project-switch, chart/table, or export controls and is not an assistive-technology review. +- Local Chromium 148.0.7778.96 exercised corrupt-storage recovery and confirmed clearing, storage-denial and quota-error warnings with in-memory state retained, cross-tab edit and clear propagation, malformed JSON restore non-mutation, cancel/separate/confirmed-replace restore conflict choices, and atomic rejection of a 1.53 MB CSV import that would exceed the 3 MB workspace limit against built `_site` v0.2.2 at `/Gridshift/`. This does not cover eviction, private browsing, every browser's storage policy, or real-device behavior. +- Local Chromium 148.0.7778.96 in a fresh profile created a project, created and switched to a second project, and opened all seven planning/settings screens with empty inventory, technology, scenario, roadmap, and report states. No page errors occurred. +- Local Chromium 148.0.7778.96 at 390×844 under `/Gridshift/` created a new empty project and opened all seven screens, using More to reach Settings; expected empty-state headings appeared and no screen overflowed. A sample scenario formatted USD in `en-US`, EUR in `fr-FR`, and JPY in `ja-JP` as `$1,333,605`, `1 333 605 €`, and `¥1,333,605`; all remained within the viewport and no page errors occurred. This is not a supported-browser matrix or zoom test. +- Local Chromium 148.0.7778.96 exercised synthetic supported-range boundary values (including 2200 base/price year, 50-year horizon, 1% discount, JPY, 100,000,000 kg asset capacity, and large annual cost values) across Dashboard, Inventory, Technology, Scenarios, Roadmap, Reports, and Settings at 320, 390, 640, 768, and 1280 px. The first pass exposed overflow in the 320 px Reports metric cards; mobile single-column report metrics and dynamically sized cumulative-chart axes corrected it. All 35 combinations then had no horizontal document overflow or page errors. These synthetic inputs test responsive rendering only and are not evidence that the values or resulting estimates are realistic. +- Node `vm.Script` syntax validation passed for `app.js`, `core.js`, and `sw.js` after the final code edit. `git diff --check` passed. +- This one local Chromium render does not establish supported browser/device coverage, utility-domain correctness, assistive-technology behavior, or production hosting. + +## Release gates still open + +1. Utility-user workflow review. This remains open in the checklist and was not changed by the domain-review waiver. +2. Complete the owner's six-platform report with device/browser/build, date, per-flow results, accessibility tools/results, and known gaps; exercise remaining storage and PWA edge cases in real browsers. +3. Enable GitHub Pages Actions publishing, inspect actual response headers, review request-log/privacy terms, and pass the live smoke test. +4. Tag and archive a reproducible release source/artifact only after the owner, browser, CI, and hosting gates pass. The release must remain explicitly labeled unreviewed. + +## Deferred domain validation (not a public-launch gate under revised criteria) + +- Bored Polymath Studios has no power-system or climate/accounting experts and no external reviewers are arranged. The owner chose neither reviewer research nor owner-led sourcing, then revised the release criteria to permit an explicitly unreviewed launch. Do not imply domain approval. Qualified independent review is still needed before results inform operational, investment, or regulatory decisions. + +Do not represent this repository as release-ready until these open gates are completed and recorded. diff --git a/RELEASE_REVIEW_PACKET.md b/RELEASE_REVIEW_PACKET.md new file mode 100644 index 0000000..734d87e --- /dev/null +++ b/RELEASE_REVIEW_PACKET.md @@ -0,0 +1,186 @@ +# Gridshift release review packet + +Use this packet to record review and test evidence. The release owner has approved public release without independent domain review, provided the product is conspicuously labeled unreviewed and remains limited to exploratory use. This packet is not evidence that a reviewer has approved the model or the product. + +## Review record + +- Reviewer name and organization: +- Review area: power-system engineering / climate accounting / utility workflow / accessibility / browser testing +- Date: +- App version: +- Browser and version (if applicable): +- Device and operating system (if applicable): +- Decision: approved / approved with changes / not approved +- Evidence, comments, and follow-up issues: + +## Calculation hand-check + +Use these inputs to reproduce a known result independently. +The arithmetic is also checked by `scripts/verify_hand_checks.py`; this does not constitute power-system or climate/accounting approval. + +### Continued operation + +- Base year: 2026 +- Horizon: 2 years +- SF₆ GWP₁₀₀: 24,300 kg CO₂e/kg SF₆ +- One asset loses 1 kg SF₆ per year +- Annual operating cost: $100; annual maintenance cost: $50; currency: USD; price year: 2026 +- Expected annual baseline emissions: `1 × 24,300 = 24,300 kg CO₂e` +- Expected two-year baseline emissions: `48,600 kg CO₂e` +- Annual O&M: $150; discount rate: 0% +- Expected baseline net present cost: `$300` + +### Replacement in the first year + +Keep the baseline inputs above, then add a replacement in 2026: + +- Remaining gas at replacement: 10 kg +- Recovery efficiency: 90% +- Unrecovered end-of-life gas: `10 × (1 − 0.90) = 1 kg SF₆` +- Replacement technology annual emissions: 5 kg CO₂e/year +- Replacement technology annual O&M: $30 +- Replacement capital and installation: $1,000 total +- Entered decommissioning cost: $0; gas recovery cost: $0; technology residual value: $0. Enter zero to make these costs explicitly known; leaving them blank marks lifecycle costs incomplete. +- Expected scenario emissions: year 2026 = `24,305 kg CO₂e`; year 2027 = `5 kg CO₂e`; total = `24,310 kg CO₂e` +- Expected avoided emissions vs. baseline: `24,290 kg CO₂e` +- Expected scenario net present cost: `$1,060`; incremental NPC vs. baseline: `$760` + +Check that the report labels units, horizon, factor source/version, currency and price year, and that results remain estimates within the documented operational-emissions boundary. + +## Domain review questions + +Record a response and evidence for each item: + +1. Are the leakage inputs, end-of-life recovery treatment, replacement-year convention, and baseline appropriate for the intended utility planning process? +2. Are all lifecycle-cost categories, discounting, price-year handling, residual value, and budget checks understandable and adequate for exploratory planning? +3. Is GWP₁₀₀ = 24,300 applicable to the intended use and source jurisdiction? Is the cited IPCC source clear? +4. Are alternative technology emissions represented with enough evidence? Are unquantified lifecycle impacts and compatibility limits conspicuous? +5. Are ranking dimensions and weights useful for prioritization without implying engineering approval? +6. Are the report and export language clear about estimates, missing inputs, scope exclusions, and regulatory limitations? + +## Utility workflow review session + +Use this session with a utility asset planner, maintenance planner, or other representative user. It evaluates workflow fit and clarity; it is not technical approval of the calculation model. Use the illustrative sample workspace or invented values only. Do not enter confidential utility records. + +### Session record + +- Participant role and relevant workflow experience (no personal name required): +- Organization type / utility context (optional, non-identifying): +- Facilitator: +- Date: +- App version / URL / browser / device: +- Session length: +- Consent to record anonymized observations: +- Critical misunderstandings or blockers: +- Follow-up issue IDs: +- Overall result: usable for exploratory workflow / changes required / unable to complete: + +As of 2026-11-03, Bored Polymath Studios has no representative utility planner session arranged; the workflow review remains open. + +### Task script + +Ask the participant to think aloud. Do not explain a label or calculation until after noting whether they can interpret it unaided. + +1. Start a new workspace, create a project, set the horizon and currency, and add two sites. Ask which project assumptions they expected to set first. +2. Add one asset using an estimated annual loss and a second using measured annual loss. Identify the evidence source for each. Ask whether the distinction and units are clear. +3. Import an illustrative CSV, correct one invalid row, and export the inventory. Ask whether the required columns and error feedback match their workflow. +4. Add a replacement technology profile with a source and at least one unknown specification. Ask what evidence they would need before treating the profile as a candidate. +5. Create a continued-operation scenario and a phased replacement scenario. Assign one asset to a replacement year, record recovery efficiency and cost inputs, and leave one cost blank. Ask the participant to explain what is unknown and what is treated as zero. +6. Compare scenario cards, inspect Roadmap and Reports, and explain the ranking, emissions difference, lifecycle-cost outputs, and warning labels in their own words. +7. Export scenario results and identify the input sources, units, year convention, factor provenance, exclusions, and independent-review status. +8. Download and restore a backup in a separate test profile. Find the local-storage and shared-device/backup disclosure. + +### Observation record + +For each task, record completion (completed / completed with help / blocked), time if practical, labels misunderstood, values entered incorrectly, missing information, unexpected behavior, and the participant's own suggested wording. Separate observed behavior from facilitator interpretation. Record severity and whether the issue prevents safe exploratory use. + +### Follow-up questions + +- Which fields, defaults, or terms do not match your normal planning process? +- Which data are measured, estimated, or unavailable in your workflow, and does Gridshift distinguish them clearly? +- Can you explain what the ranking score does and does not mean? +- Do the scenario cards and report answer the comparison questions you need? What is missing? +- Which warnings would you need before sharing or acting on an exported result? +- What would make this workflow unsuitable even for early-stage exploration? + +Do not mark a session passed solely because the participant completed the tasks. Resolve every critical misunderstanding or record it prominently as an unresolved use limitation. + +## External reviewer request + +Bored Polymath Studios is a lone-developer project and has no power-system engineering or climate/accounting experts attached. Independent external review has not been arranged and is not a public-launch gate under the owner's revised acceptance criteria. The app and exported scenario results must identify the model as not independently reviewed. Qualified review is still needed before results are used for operational, investment, or regulatory decisions. The request template below is retained for future review; a power-system reviewer should have practical experience reviewing utility switchgear/equipment planning or replacement assumptions, and a climate/accounting reviewer should have experience with GHG inventory or emissions accounting, GWP factors, leakage/recovery treatment, and lifecycle boundaries. Reviewers should state relevant experience and scope; this request is for technical review, not certification. + +### Request template + +**Subject:** Independent review request: Gridshift SF₆ transition planning model + +Hello, + +Bored Polymath Studios is preparing Gridshift, a public, browser-local planning tool for exploring transitions away from SF₆ electrical equipment. The owner permits public release with an explicit unreviewed status, and we are seeking independent technical review before results are used beyond exploratory planning. + +Would you review the attached [calculation model](CALCULATION_MODEL.md) and [release review packet](RELEASE_REVIEW_PACKET.md)? The review should cover the areas matching your expertise, check the hand-calculation examples independently, identify unsupported assumptions or misleading language, and record a decision with qualifications, date, findings, and any conditions. The tool is intended for exploratory planning; the review is not a request to certify regulatory compliance, project data, equipment compatibility, or investment decisions. + +We can provide the current code and a test workspace containing illustrative data only. Please do not use or request confidential utility records in public issues or sample files. + +Thank you, + +Bored Polymath Studios + +### Reviewer decision record + +- Reviewer and organization: +- Relevant experience / qualifications: +- Review scope: +- Conflicts or limitations declared: +- Hand-check independently reproduced: +- Findings and required changes: +- Decision: approved / approved with conditions / not approved +- Date: + +## Browser and device session + +Target operating systems supplied for testing are Android, iOS/iPadOS, macOS, Windows, Linux, and ChromeOS. The owner reports personally testing all listed flows on each OS, but device model, exact browser/version, test date, build/URL, detailed results, and known gaps were not recorded. On 2026-11-03, the owner asked to mark those details `not recorded` and keep the gate open. Use Chrome on Android, Safari on iOS/iPadOS, and the documented desktop browser targets where available. Record one row per device/browser session; mark unknown details as `not recorded` and do not infer a passing result from OS coverage alone. + +| Reviewer | Test date | Device model / OS | Browser and version | App URL / build | Install / launch result | Offline / update result | Data exchange / recovery result | Accessibility tools / result | Known gaps, evidence, decision | +|---|---|---|---|---|---|---|---|---|---| +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / Android | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / iOS/iPadOS | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / macOS | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / Windows | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / Linux | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Bored Polymath Studios (owner-reported self-test) | Not recorded | Model not recorded / ChromeOS | Not recorded | Not recorded | Owner reports tested | Owner reports tested | Owner reports tested | Owner reports tested; tools and findings not recorded | Owner reports all listed flows tested; outcomes and evidence not recorded | +| Codex local automated smoke | 2026-11-03 | Model not recorded / macOS 27.2 arm64 | Chromium 148.0.7778.96 via Playwright 1.60.0 (headless) | Local worktree and built `_site` v0.2.2 at `/Gridshift/` | Fresh profile project creation and switching passed; all seven screens opened with expected empty states | Service worker controlled the page, v6 shell cached, offline edit persisted across reload; uncached fetch failed with expected network `TypeError`. Simulated v6→v7 update kept v6 active until acceptance, kept the update button visible after navigation, then reloaded v0.2.3 with project data preserved and the old owned cache removed | Inventory CSV import/export, scenario-results CSV with review-status row, JSON backup, and no-conflict restore passed; malformed JSON restore left storage unchanged; cancel, separate-copy, and confirmed replace paths passed; 1.53 MB CSV rejected atomically when it would exceed the 3 MB workspace limit | 390×844 DOM/screenshot checks and all seven screens at 320/360/390/768/1280 px with a 173-character project name and 120 imported assets: no document overflow. Visible buttons/form controls at 390 and 1280 px met a 24×24 px target threshold after fixing 22 px site-action buttons; reduced-motion emulation passed. Required validation, error retention, heading fallback, dialog close/cancel focus, and a focused Tab/Enter/Escape project-create/mobile-More smoke passed. A separate solid-background text scan across all seven screens in light and dark emulation found and fixed several low-contrast pairs, then reported zero remaining; it is not a full WCAG audit. Full keyboard-only and screen-reader audits remain open | 320 px and 768 px layouts visually inspected. Corrupt-data recovery/confirmed clear, denied storage, quota failure with current-tab state retained, and cross-tab edit/clear propagation passed. No page errors. Not a physical-device or production-host test; native install/update, eviction/private browsing, and assistive-technology checks remain open | +| Codex local v8 smoke | 2026-11-03 | Model not recorded / macOS 27.2 arm64 | Chromium 148.0.7778.96 via Playwright 1.60.0 (headless) | Built `_site` v0.2.3 served over loopback at `/Gridshift/` | Fresh profile loaded; illustrative sample workspace opened; Settings showed app version 0.2.3 | Worker controlled the page and installed `gridshift-shell-v8`; offline reload returned to Dashboard, and Settings remained reachable via the mobile More menu. A staged v7→v8 update left v7 active until the user accepted; after acceptance v8 activated, v7 cache was removed, and sample project data was unchanged | No import/export or restore flows in this session | At 390×844, Settings showed the shared-origin warning and had no horizontal overflow; no page errors. Not a full accessibility check | This tests the local Pages-path artifact, not GitHub Pages, a physical device, or native install | + +After the recorded update simulation, the local release candidate advanced its service-worker cache from v6 to v7 for the final app-shell edits. The contrast recheck loaded the current files directly and did not exercise service-worker update behavior. At 390×844, the mobile text scan found and fixed low contrast on inventory Remove actions; its rerun found no below-threshold text pairs on the seven screens under light or dark emulation. This remains a solid-background probe, not a full WCAG audit. + +Additional v7 PWA smoke on 2026-11-03: Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64 loaded the built local shell under `http://127.0.0.1:8779/Gridshift/`. A fresh profile was controlled by the service worker, installed the v7 cache, saved a sample project, reloaded the dashboard offline, opened Settings offline, and retained the project. No page errors occurred. This loopback test is not GitHub Pages or physical-device evidence. + +Additional v8 PWA smoke on 2026-11-03: Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64 loaded the built `_site` under a local `/Gridshift/` path. A fresh profile installed `gridshift-shell-v8`, opened the illustrative workspace and Settings, displayed the 0.2.3 version and shared-origin warning, and had no horizontal overflow at 390×844. After going offline, reload returned to the Dashboard; the mobile More menu opened Settings offline. No page errors occurred. A separate staged-update run is recorded below. This does not test GitHub Pages, native installation, or physical devices. + +Additional v7→v8 staged-update smoke on 2026-11-03: Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64 started from a fresh profile with a v7 worker, then received the v8 worker from the local `/Gridshift/` fixture. The v7 cache remained active while the v8 update waited; the update action stayed visible after navigating to Settings. Accepting the action activated v8, removed the v7 cache, preserved the exact saved sample-project JSON, and reloaded with Gridshift 0.2.3 visible in Settings. No page errors occurred. This validates the local worker update flow only, not GitHub Pages or native device installation. + +Additional empty-state and locale smoke on 2026-11-03: Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64 created an empty project at 390×844 under a local `/Gridshift/` path, opened all seven screens (including Settings through More), and found no horizontal overflow. The sample scenario rendered USD for `en-US`, EUR for `fr-FR`, and JPY for `ja-JP`, with the expected grouping/symbols and no overflow or page errors. Other locales, unusual values, browser zoom, and browser/device differences remain untested. + +Additional synthetic boundary-value layout smoke on 2026-11-03: Chromium 148.0.7778.96 / Playwright 1.60.0 on macOS 27.2 arm64 exercised supported-range extreme values on all seven screens at 320, 390, 640, 768, and 1280 px. The initial 320 px Reports view overflowed; stacking report metric cards, allowing large values to wrap, and adapting cumulative-chart axis width to label length resolved it. The rerun passed all 35 screen/viewport combinations without horizontal overflow or page errors. Inputs were synthetic layout stressors and do not establish realistic domain assumptions, zoom behavior, or browser/device coverage. + +Run the scenarios in `RELEASE_RUNBOOK.md`, including first launch, an empty workspace, project and scenario creation, CSV import/export, JSON restore/cancel/conflict handling, offline launch and editing, update acceptance, storage recovery, keyboard navigation, screen-reader use, zoom, and narrow layouts. + +## Release owner decision + +- Product/release owner: Bored Polymath Studios +- Support route: GitHub issue templates and private vulnerability reporting; no separate support email supplied +- Internal expertise: Bored Polymath Studios is a lone-developer project; no power-system engineering or climate/accounting experts are attached. +- External qualified reviewers: none arranged. On 2026-11-03 the owner confirmed there are no relevant experts on the project and chose neither reviewer research nor owner-led sourcing. The owner subsequently revised the launch criteria to allow an explicitly unreviewed release. No domain approval is implied; qualified review remains necessary before operational, investment, or regulatory use. +- Intended public audience: public users; primary audience is electricity utility teams exploring early-stage transition planning, consistent with the README scope. +- Owner-approved release acceptance criteria (approved 2026-11-03; the added same-origin item below is pending approval): + 1. The app, README, model documentation, and scenario-results exports state that the model has not received independent qualified power-system engineering or climate/accounting review. Outputs remain described as exploratory estimates, with qualified review required before operational, investment, or regulatory decisions. Domain review is not a public-launch gate under this revised criterion. + 2. The 19 automated tests pass in repository CI, and the owner's six-platform test report includes device, browser/version, date, URL/build, results, and known gaps. + 3. The published GitHub Pages project path serves the manifest, worker, icons, and app shell correctly over HTTPS; install, offline launch, user-controlled update, backup restore, and recovery pass on the agreed platform matrix. + 4. The release owner accepts local-only storage limits, host visitor-IP logging, and GitHub Pages' lack of custom response headers. + 5. Bored Polymath Studios accepted retaining the planned shared GitHub Pages origin on 2026-11-03, understanding that any page on `boredpolymath.github.io` can read, change, or delete Gridshift localStorage when opened in the same browser profile. Keep the warning visible, and do not store confidential utility records on the shared origin unless every publisher on it is trusted. This is a separate accepted risk; it does not imply that the origin provides storage isolation. + 6. Public support/security routes and ongoing maintenance owners are recorded; rollback is available from a retained source revision. +- Accepted limitations: Bored Polymath Studios accepts GitHub Pages visitor-IP logging and its response-header limits for the planned release; live verification is pending. +- Privacy disclosure review: Bored Polymath Studios approved the shared-device, extension-permission, and readable/unencrypted JSON-backup wording in README, Settings, and SECURITY.md on 2026-11-03. +- Same-origin disclosure and risk decision: wording was added to README, Settings, and SECURITY.md on 2026-11-03 after the source-level security scan found the shared-host localStorage exposure. On 2026-11-03 Bored Polymath Studios chose to retain the planned GitHub Pages URL and explicitly accept this exposure for the release, subject to the visible warning and no confidential utility records unless every same-origin publisher is trusted. +- Acting maintenance owners: Bored Polymath Studios, currently the sole developer, owns support triage, security updates, browser support decisions, and calculation-source updates until reassigned. No backup maintainer or named individual is recorded. +- Final decision and date: diff --git a/RELEASE_RUNBOOK.md b/RELEASE_RUNBOOK.md new file mode 100644 index 0000000..f8e4f51 --- /dev/null +++ b/RELEASE_RUNBOOK.md @@ -0,0 +1,50 @@ +# Static release runbook + +This runbook targets a public GitHub Pages project site at `https://boredpolymath.github.io/Gridshift/`. The earlier 2026-11-03 repository check reported Pages disabled. A later check that day found no GitHub Actions runs and no `.github/workflows` directory on remote `main`; the available web tool could not open the Pages URL, so its HTTP status is not established. The local workflow is prepared; it must be reviewed and published before the Pages setup below can run. + +## Before publishing + +1. Confirm the release owner has approved the audience, exploratory-use boundary, calculation model, and release acceptance criteria. +2. Confirm the app, README, calculation model, and scenario-results CSV disclose that no independent qualified power-system or climate/accounting review has been completed. Under the owner's revised criteria, this disclosure is required and domain review is not a public-launch gate; qualified review is still required before operational, investment, or regulatory use. +3. Run the GitHub Actions quality workflow and resolve failures. + The workflow builds `_site` and checks that it contains exactly the allowlisted files, byte-identical to their sources, before considering the change valid. +4. Run the manual smoke checks below on the supported browser/device matrix. +5. Review the release notes and confirm the version in `package.json` and `core.js` agree. +6. Export and restore representative test workspaces. Never use real customer records in test fixtures or public issues. +7. Confirm the product owner accepts the local-storage, shared-device, browser-extension, readable-backup, and same-origin Pages disclosures in README and Settings. The planned `boredpolymath.github.io/Gridshift/` project path does not isolate localStorage from other pages on that host. Use a dedicated hostname for actual origin isolation; owner acceptance of disclosure alone does not prevent access by same-origin pages. + +## GitHub Pages setup and hosting limits + +- Enabling GitHub Actions as the Pages source makes each subsequent push to `main` publish the app publicly. Bored Polymath Studios accepted the shared-origin storage exposure on 2026-11-03; keep its warning visible and do not store confidential utility records on that origin unless every publisher is trusted. Do not enable this source until the remaining launch gates are complete and the owner explicitly approves the initial public deployment. +- In repository Settings → Pages, choose **GitHub Actions** as the build and deployment source. The workflow publishes only the static app shell from `_site` when `main` is updated. See GitHub's [custom workflow guide](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages). +- The project site is served under `/Gridshift/`, not at the host root. Manifest, script, style, icon, and service worker references are relative so they resolve within this project path. Verify the complete path after the first deployment. +- GitHub Pages project paths under `boredpolymath.github.io` share one browser origin. A script on another page at that host can access Gridshift localStorage if the user visits it in the same profile. The path-based project site is not a security boundary. Prefer a dedicated custom hostname; if retaining the shared host, require trusted control over every published page there and warn users not to store confidential utility records. +- GitHub Pages provides HTTPS. Confirm the live URL redirects or serves securely before inviting users. +- Serve `manifest.webmanifest` as `application/manifest+json` (or a browser-recognized JSON MIME type) and `sw.js` as `text/javascript` or `application/javascript`. +- Serve `sw.js` and `index.html` with revalidation enabled (`Cache-Control: no-cache` is suitable). Avoid long-lived immutable caching for the worker script. +- Keep all files listed in the service worker's required shell in the same deployment. Publish a complete revision atomically so clients cannot receive a partial app shell. +- Preserve the HTML Content Security Policy and ensure it permits same-origin scripts, styles, images, and the same-origin service worker. +- GitHub Pages does not provide per-response-header configuration in this repository workflow. GitHub's [Pages header discussion](https://github.com/orgs/community/discussions/54257) confirms custom headers are not supported. The HTML meta CSP cannot set `frame-ancestors`; response headers such as `X-Content-Type-Options` and `Permissions-Policy` cannot be added by this app. Treat this as an accepted launch limitation, inspect the actual headers after deployment, and reconsider hosting if policy requires those headers. +- GitHub's [Pages data-collection notice](https://docs.github.com/en/pages/getting-started-with-github-pages/what-is-github-pages#data-collection) says visitor IP addresses are logged and stored for security. The Pages documentation does not specify a retention period. Bored Polymath Studios accepts this as GitHub hosting behavior; Gridshift itself does not transmit planning records or send analytics. Keep the disclosure in README and review GitHub's [Privacy Statement](https://docs.github.com/en/site-policy/privacy-policies/github-privacy-statement) if its policy changes. + +## Manual smoke checks + +- [ ] New browser profile: create a project and verify all six planning screens and Settings load. +- [ ] Import the CSV template, edit records, create more than one scenario, compare the scenario tiles, and export inventory/results. +- [ ] Download a JSON backup, restore it into an empty profile, verify the preview counts, then exercise cancel, separate-copy, and replace flows. +- [ ] Use keyboard-only navigation for project switching, More on mobile, dialogs, forms, confirmations, chart/table switch, and export controls. +- [ ] Test 320 px wide through desktop widths, zoom, long project/asset names, empty states, and large but supported inventories. +- [ ] Install from the browser and verify the app name/icon on supported platforms. +- [ ] With the worker active, go offline, launch the app, navigate, edit saved data, and export; verify the expected behavior for an uncached request. +- [ ] Publish a staging update and verify the previous shell remains coherent until the user chooses the update button, then reload and verify local data remains. +- [ ] Repeat install/offline/update checks on current and previous major desktop Chrome, Edge, Firefox, Safari, current iOS/iPadOS Safari, and Android Chrome. +- [ ] Verify local storage denied, full, corrupted, and cleared states; verify another tab changing or clearing data does not silently overwrite the visible workspace. + +## Rollback + +1. Retain the exact source revision and complete static artifact for each published release. +2. To roll back, atomically publish the previous full revision at the root and allow the service-worker update check to discover it. +3. Verify the update prompt, activate the prior shell, and confirm backups and local project data remain intact. +4. If any data migration is not backward-compatible, stop rollback and use a version-specific recovery plan before asking users to open the older app. + +Do not tag or announce a release until the owner-approved disclosure criteria, CI, Pages deployment, response-header review, and manual platform checks are complete. No domain approval may be implied; a release without that review must remain explicitly labeled unreviewed. diff --git a/SECURITY.md b/SECURITY.md index 0a5e4d7..ec1ec77 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -10,4 +10,14 @@ Please do not report security vulnerabilities in public issues or pull requests. If private vulnerability reporting is unavailable, contact the repository owner through GitHub at [@boredpolymath](https://github.com/boredpolymath) and request a private channel. Please include steps to reproduce, the affected file or workflow, and the potential impact. Avoid sharing real project data or other sensitive information. -The maintainers will acknowledge reports as soon as practical, investigate them, and coordinate any fix and disclosure with the reporter. Please allow time for a fix before public disclosure. +The release owner will acknowledge reports as soon as practical, investigate them, and coordinate any fix and disclosure with the reporter. Please allow time for a fix before public disclosure. + +## Local project data + +Gridshift stores project records in the current browser profile and does not provide account-level access control or encryption. Other people with access to the same profile or device may view or change those records. Browser extensions granted access to the site can inspect or alter site content; use only trusted extensions in a profile that holds planning data. The JSON backup is readable and is not encrypted by Gridshift. Protect downloaded backups and delete them separately when no longer needed. Clearing Gridshift data in the browser does not remove backup files. + +The planned GitHub Pages URL is `https://boredpolymath.github.io/Gridshift/`. Browser storage is scoped to the full origin, not the `/Gridshift/` path. Any other page published on `boredpolymath.github.io` can read, change, or delete Gridshift's localStorage data if opened in the same browser profile. This risk is separate from access by an unrelated website. Do not store confidential utility records on this shared origin unless all content publishers on it are trusted. A dedicated Gridshift hostname is required for origin isolation; disclosure alone does not prevent same-origin access. + +## Deployment notes + +The HTML includes a restrictive Content Security Policy. `style-src 'unsafe-inline'` remains because the current UI emits inline style attributes for charts and layout; script execution remains same-origin only. The selected host is GitHub Pages. Its repository workflow serves static files and has no per-response-header configuration, so this app cannot add `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, or a restrictive `Permissions-Policy` there. A meta CSP cannot enforce `frame-ancestors`. Inspect actual response headers after deployment and revisit hosting if the release owner requires these headers. diff --git a/app.js b/app.js index 1cc24fc..b94b8d1 100644 --- a/app.js +++ b/app.js @@ -1,14 +1,26 @@ (() => { const KEY = 'gridshift-planner-v1'; - const CALC_VERSION = '1.0'; - const FACTOR = { value: 25200, horizon: '100-year', source: 'IPCC Sixth Assessment Report, WG I, Table 7.15 (SF₆)', version: 'AR6' }; + const {APP_VERSION,CALC_VERSION,MAX_STATE_CHARS,calc,parseCsv,csvValue,validateBackup,migrateLegacyFactor,migrateLegacyCosts}=GridshiftCore; + const FACTOR = { value: 24300, horizon: '100-year', source: 'IPCC AR6 WGI Supplementary Material, Table 7.SM.7 (SF₆)', version: 'AR6 WGI 2021' }; + const MODEL_REVIEW_STATUS = 'Not independently reviewed'; const app = document.querySelector('#app'), dialog = document.querySelector('#dialog'), toastEl = document.querySelector('#toast'); - let toastTimer; + let toastTimer, dialogOpener=null, workerRegistration=null, applyWorkerUpdate=false; + dialog.addEventListener('close',()=>{ + if(dialog.open)return; + const target=dialogOpener;dialogOpener=null; + if(target?.isConnected&&!target.disabled){target.focus();if(document.activeElement===target)return} + const heading=document.querySelector('#view h1, #view h2'); + if(heading){heading.tabIndex=-1;heading.focus({preventScroll:true})} + }); const uid = () => crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`; const yearNow = new Date().getFullYear(); const blankState = () => ({ version: 1, projects: [], activeProjectId: null, updatedAt: null }); - let state; - try { state = JSON.parse(localStorage.getItem(KEY)) || blankState(); if (!Array.isArray(state.projects)) state = blankState(); } catch { state = blankState(); } + let state, storageCorruptRaw=null, storageUnavailable=false; + try { const raw=localStorage.getItem(KEY);state=raw?JSON.parse(raw):blankState();if(!state||state.version!==1||!Array.isArray(state.projects)||state.projects.some(p=>!p||!Array.isArray(p.assets)||!Array.isArray(p.sites)||!Array.isArray(p.technologies)||!Array.isArray(p.scenarios)))throw new Error('Stored workspace has an unsupported structure.');try{validateBackup({format:'gridshift-backup',version:1,data:state})}catch{throw new Error('Stored workspace has an unsupported structure.')} } + catch(e){state=blankState();if(e instanceof SyntaxError||e.message==='Stored workspace has an unsupported structure.')storageCorruptRaw=(()=>{try{return localStorage.getItem(KEY)}catch{return null}})();else storageUnavailable=true;} + const legacyFactorSource='IPCC Sixth Assessment Report, WG I, Table 7.15 (SF₆)'; + const migratedFactorProjects=storageCorruptRaw?0:migrateLegacyFactor(state,legacyFactorSource,FACTOR); + const migratedCostProjects=storageCorruptRaw?0:migrateLegacyCosts(state); let page = 'dashboard', searchText = '', filterCategory = 'All categories'; const current = () => state.projects.find(p => p.id === state.activeProjectId) || state.projects[0] || null; const activeScenario = p => p?.scenarios.find(s => s.id === p.activeScenarioId) || p?.scenarios[0] || null; @@ -16,10 +28,13 @@ const money = (v, currency='USD', digits=0) => Number.isFinite(v) ? new Intl.NumberFormat(undefined,{style:'currency',currency,maximumFractionDigits:digits,minimumFractionDigits:digits}).format(v) : 'Unavailable'; const num = (v,d=1) => Number.isFinite(v) ? new Intl.NumberFormat(undefined,{maximumFractionDigits:d}).format(v) : '—'; const fmtDate = v => v ? new Date(v).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}) : 'Not saved'; + const fitsLocalDataLimit=value=>JSON.stringify(value).length<=MAX_STATE_CHARS; function save(message='Changes saved locally') { + if(storageCorruptRaw!==null){toast('Existing browser data may be damaged. Export a recovery copy and reset local data before saving.',true);return} + const priorUpdatedAt=state.updatedAt; state.updatedAt = new Date().toISOString(); - try { localStorage.setItem(KEY, JSON.stringify(state)); renderTop(); if (message) toast(message); } - catch (e) { try { state=JSON.parse(localStorage.getItem(KEY))||blankState(); } catch { state=blankState(); } renderTop(); toast(`Save failed: ${e.name === 'QuotaExceededError' ? 'browser storage is full. Export a backup and free space.' : e.message}. Previously saved records were preserved.`, true); } + try { const payload=JSON.stringify(state);if(payload.length>MAX_STATE_CHARS){const error=new Error('Gridshift local-data limit exceeded.');error.name='QuotaExceededError';throw error}localStorage.setItem(KEY,payload);renderTop();if(message)toast(message); } + catch (e) { state.updatedAt=priorUpdatedAt;renderTop();toast(`Save failed: ${e.name === 'QuotaExceededError' ? 'browser storage is full. Export a JSON backup, then free browser space.' : 'browser storage is unavailable. Export a JSON backup before leaving this tab.'} Your current edits remain visible in this tab.`, true); } } function toast(message, error=false) { toastEl.textContent=message;toastEl.style.background=error?'#8c352c':'#173f35';toastEl.classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>toastEl.classList.remove('show'),3200); } function mkProject(name, description='', horizon=10) { return {id:uid(),name,description,baseYear:yearNow,horizon:Number(horizon),currency:'USD',priceYear:yearNow,discountRate:0.04,gwp:FACTOR.value,gwpHorizon:FACTOR.horizon,gwpSource:FACTOR.source,factorVersion:FACTOR.version,sites:[],assets:[],technologies:[],scenarios:[],activeScenarioId:null,weights:{age:35,emissions:40,condition:25},createdAt:new Date().toISOString()}; } @@ -30,74 +45,64 @@ const scount=document.querySelector('#scenario-count'); if(scount)scount.textContent=p?.scenarios.length||0; renderStatus(); } + function syncUpdateButton(){const button=document.querySelector('#update-app');if(!button)return;const waiting=workerRegistration?.waiting,controlled='serviceWorker'in navigator&&navigator.serviceWorker.controller;if(!waiting||!controlled){button.hidden=true;return}button.hidden=false;button.disabled=false;button.textContent='Update ready · Reload';button.onclick=()=>{const worker=workerRegistration?.waiting;if(!worker)return;applyWorkerUpdate=true;button.disabled=true;button.textContent='Updating…';worker.postMessage({type:'SKIP_WAITING'})}} const navItems=[['dashboard','◫','Overview'],['inventory','▤','Asset inventory'],['technology','⌘','Technology library'],['scenarios','◷','Scenarios'],['roadmap','↗','Roadmap'],['reports','▧','Reports & export']]; function shell() { - app.innerHTML=`
${sub}
Create a project to organize sites, inventory SF₆ equipment, compare preliminary technology profiles, and model a phased transition. Data is stored locally in this browser.
Planning estimates only. Compatibility screening does not constitute engineering approval.
`} function wireEmpty(){document.querySelector('[data-action="new-project"]')?.addEventListener('click',()=>projectForm());document.querySelector('[data-action="demo-project"]')?.addEventListener('click',seedDemo)} - function calc(p,s){ - const baseYear=s?.baseYearSnapshot??p.baseYear,horizon=s?.horizonSnapshot??p.horizon,gwp=s?.gwpSnapshot??p.gwp,start=baseYear,end=start+horizon-1, years=Array.from({length:horizon},(_,i)=>start+i), replacement=s?.replacements||{}, assets=s?.inputSnapshot?.assets??p.assets, technologies=s?.inputSnapshot?.technologies??p.technologies, annual=years.map(year=>({year,baseline:0,scenario:0,cost:0,capital:0,baselineCost:0,assets:[]}));let incomplete=[];let npc=0,baselineNpc=0;const discount=Number(s?.discountSnapshot??p.discountRate)||0; - for(const a of assets){const plan=replacement[a.id];const repYear=plan?.year;const cap=Number(a.capacityKg),rate=Number(a.lossRate),measured=Number(a.measuredLoss),rawLoss=a.lossMode==='measured'?measured:cap*rate,loss=Number.isFinite(rawLoss)&&rawLoss>=0?rawLoss:0; - if(!Number.isFinite(rawLoss)||rawLoss<0)incomplete.push(`${a.assetId}: missing/invalid annual SF₆ loss input; emissions total is partial`); - const tech=technologies.find(t=>t.id===plan?.technologyId); if(plan&&plan.yearAnnual loss is treated as a full-year estimate until the year before replacement. In the replacement year, annual leakage is excluded and explicitly modeled end-of-life loss is included. Manufacturing and construction emissions are not included.
Add an SF₆ asset to see portfolio emissions and replacement candidates.
Annual loss is treated as a full-year estimate until the year before replacement. In the replacement year, annual leakage is excluded and explicitly modeled end-of-life loss is included. Manufacturing and construction emissions are not included.
Add an SF₆ asset to see portfolio emissions and replacement candidates.
| Asset | Site / type | kV | SF₆ (kg) | Loss / year | Install / retire | Condition | Actions |
|---|---|---|---|---|---|---|---|
| ${esc(a.assetId)} ${esc(a.manufacturer||'Manufacturer not recorded')} | ${esc(a.site)} ${esc(a.category)} | ${num(Number(a.voltageKv),0)} kV ${esc(a.characteristics||'Ratings not detailed')} | ${num(Number(a.capacityKg),1)} kg | ${a.lossMode==='measured'?`${num(Number(a.measuredLoss),2)} kg`:`${num(Number(a.lossRate)*100,2)}% / yr`} ${a.lossMode==='measured'?'Measured':'Estimated'} · ${esc(a.lossSource||'source not recorded')} | ${a.installYear||'—'} / ${a.retirementYear||'—'} | ${esc(a.condition||'Unknown')} |
${p.assets.length?'Try a different search or category filter.':'Add equipment individually or import a CSV inventory. Required data and units are validated before it is saved.'}
${p.assets.length?'':` `}${esc(t.description||'No profile notes recorded.')}
Source: ${esc(t.source||'No reference supplied')}
Add user-maintained alternatives with insulation type, voltage ratings, gas composition, and source references. Missing specifications stay visible.
${esc(s.description||'No description recorded')} · ${esc(s.mode||'Phased transition')}
Assign candidate technologies and replacement years, set an annual capital budget, then compare costs and modeled emissions with continued operation.
| Rank / asset | Score | Retirement | Emissions | Condition | Screening |
|---|---|---|---|---|---|
| ${i+1}. ${esc(a.assetId)} ${esc(a.site)} · ${esc(a.category)} | ${num(a.score*100,0)} | ${a.retirementYear||'Unknown'} | ${num(a.annual*Number(p.gwp)/1000,1)} t/yr | ${esc(a.condition||'Unknown')} | ${missing?'Review required':'Profile linked'} |
Add assets to rank candidates.
Create a scenario to see planned capital expenditure against the annual budget.
`}${s&&c.costsByYear.some(r=>r.over)?'Create a scenario to assign replacement projects to years.
'}${esc(t.description||'No profile notes recorded.')}
Source: ${esc(t.source||'No reference supplied')}
Add user-maintained alternatives with insulation type, voltage ratings, gas composition, and source references. Missing specifications stay visible.
${esc(s.description||'No description recorded')} · ${esc(s.mode||'Phased transition')}
Assign candidate technologies and replacement years, set an annual capital budget, then compare costs and modeled emissions with continued operation.
| Rank / asset | Score | Retirement | Emissions | Condition | Screening |
|---|---|---|---|---|---|
| ${i+1}. ${esc(a.assetId)} ${esc(a.site)} · ${esc(a.category)} | ${num(a.score*100,0)} | ${a.retirementYear||'Unknown'} | ${num(a.annual*Number(p.gwp)/1000,1)} t/yr | ${esc(a.condition||'Unknown')} | ${missing?'Review required':'Profile linked'} |
Add assets to rank candidates.
Create a scenario to see planned capital expenditure against the annual budget.
`}${s&&c.costsByYear.some(r=>r.over)?'Create a scenario to assign replacement projects to years.
'}No replacements assigned. Edit the scenario to schedule selected assets.
';return `| Year | Baseline | Scenario | Avoided / (increase) |
|---|---|---|---|
| ${r.year} | ${num(r.baseline,1)} kg | ${num(r.scenario,1)} kg | ${num(r.baseline-r.scenario,1)} kg |
Discount rate ${num(p.discountRate*100)}%
Compared with continued-operation baseline
Continued operation using recorded asset costs
Only available when cumulative avoided emissions are positive
Capital, installation, recovery, operating, and maintenance
Baseline NPC includes the recorded annual operating and maintenance costs for continuing assets. Replacement scenario NPC uses the technology profile operating and maintenance costs after replacement.
${esc(c.factor.source)} · ${esc(c.factor.horizon)} horizon · reference ${esc(c.factor.version)}
Measured annual loss or capacity × estimated annual loss rate, per asset
Full year leakage before replacement; replacement year uses remaining gas × (1 − recovery efficiency)
Excluded; results do not represent complete lifecycle climate impact
Planning estimates only. No emissions result represents measured leakage unless the source asset input was recorded as measured. Factors and reporting requirements vary by jurisdiction; this tool does not certify regulatory compliance or equipment compatibility.
Once you create a scenario, this page will show emissions, lifecycle costs, assumptions, and export actions.
${p.baseYear} · ${p.horizon} years (${p.baseYear}–${p.baseYear+p.horizon-1})
${esc(p.currency)} · ${p.priceYear}
${num(p.discountRate*100)}% annual
${num(p.gwp,0)} GWP · ${esc(p.gwpHorizon)} · ${esc(p.factorVersion)}
${esc(p.gwpSource)}
${esc(s.region||'Region not recorded')} · ${p.assets.filter(a=>a.site===s.name).length} assets ${s.notes?`· ${esc(s.notes)}`:''}
No sites yet. Add sites to organize your inventory.
'}Use an install prompt when supported, or follow your browser’s Add to Home Screen option.
No live factor feed is configured; review your source and version when policy changes.
Versioned JSON with projects, sites, assets, profiles, and scenarios. Store it somewhere safe.
Validates the file before changing anything. Existing project IDs prompt for cancel, replace, or separate copy.
Checking browser storage usage…
Deletes every project saved by this planner from this browser. This cannot be undone.
Browser-local storage is convenient for offline planning, but it does not provide enterprise access control or encryption. Shared devices and browser storage eviction can expose or remove project data. Keep a backup.
| Year | Baseline | Scenario | Avoided / (increase) |
|---|---|---|---|
| ${esc(r.year)} | ${num(r.baseline,1)} kg | ${num(r.scenario,1)} kg | ${num(r.baseline-r.scenario,1)} kg |
Discount rate ${num(p.discountRate*100)}%
Compared with continued-operation baseline
Continued operation using recorded asset costs
Only available when cumulative avoided emissions are positive
Capital, installation, recovery, operating, and maintenance
Baseline NPC includes the recorded annual operating and maintenance costs for continuing assets. Replacement scenario NPC uses the technology profile operating and maintenance costs after replacement.
${esc(c.factor.source)} · ${esc(c.factor.horizon)} horizon · reference ${esc(c.factor.version)}
Measured annual loss or capacity × estimated annual loss rate, per asset
Full year leakage before replacement; replacement year uses remaining gas × (1 − recovery efficiency)
Excluded; results do not represent complete lifecycle climate impact
Planning estimates only. No emissions result represents measured leakage unless the source asset input was recorded as measured. Factors and reporting requirements vary by jurisdiction; this tool does not certify regulatory compliance or equipment compatibility.
Once you create a scenario, this page will show emissions, lifecycle costs, assumptions, and export actions.
${p.baseYear} · ${p.horizon} years (${p.baseYear}–${p.baseYear+p.horizon-1})
${esc(p.currency)} · ${p.priceYear}
${num(p.discountRate*100)}% annual
${num(p.gwp,0)} GWP · ${esc(p.gwpHorizon)} · ${esc(p.factorVersion)}
${esc(p.gwpSource)}${p.gwpSource===FACTOR.source?` · Open IPCC AR6 table ↗`:''}
${esc(s.region||'Region not recorded')} · ${p.assets.filter(a=>a.site===s.name).length} assets ${s.notes?`· ${esc(s.notes)}`:''}
No sites yet. Add sites to organize your inventory.
'}Gridshift ${APP_VERSION} · calculation ${CALC_VERSION}
Use an install prompt when supported, or follow your browser’s Add to Home Screen option.
No live factor feed is configured; review your source and version when policy changes.
Versioned JSON with projects, sites, assets, profiles, and scenarios. Store it somewhere safe.
Validates the file before changing anything. Existing project IDs prompt for cancel, replace, or separate copy.
Checking browser storage usage…
Deletes every project saved by this planner from this browser. This cannot be undone.
Browser-local storage is convenient for offline planning, but it does not provide enterprise access control or encryption. Shared devices and browser storage eviction can expose or remove project data. Browser extensions with permission to access this site may inspect or change site data or displayed records. The planned GitHub Pages URL is on boredpolymath.github.io; any other page on that exact host shares this storage origin and can read, change, or delete Gridshift data if opened in this profile. Do not store confidential utility records there unless every publisher on the host is trusted; a dedicated hostname is required for isolation. Downloaded JSON backups contain readable project data, are not encrypted by Gridshift, and must be protected or deleted separately. See README for more information.
No project exists yet.
'}${esc(sub||'')}
${esc(sub||'')}
Project data remains in this browser until you choose to clear it. Do not close this page before downloading the recovery copy.
`);dialog.querySelector('#download-recovery').onclick=()=>{download(`gridshift-local-recovery-${new Date().toISOString().slice(0,10)}.json`,storageCorruptRaw||'','application/json');toast('Recovery copy downloaded')};dialog.querySelector('#reset-recovery').onclick=()=>{closeDialog();confirmDialog('Clear damaged local data?','This deletes the unreadable workspace from this browser. Download a recovery copy first if you may need it.',()=>{try{localStorage.removeItem(KEY);storageCorruptRaw=null;state=blankState();page='dashboard';render();toast('Damaged local data cleared')}catch{toast('Browser storage could not be cleared. Your recovery copy remains available.',true)}})}} function confirmDialog(title,text,fn){showDialog(title,text,``);dialog.querySelector('#cancel').onclick=closeDialog;dialog.querySelector('#confirm').onclick=()=>{closeDialog();fn()}} function form(title,sub,fields,submitLabel,handler){showDialog(title,sub,``);dialog.querySelector('#cancel-form').onclick=closeDialog;dialog.querySelector('#form').onsubmit=e=>{e.preventDefault();const fd=new FormData(e.currentTarget),data=Object.fromEntries(fd.entries());const invalid=e.currentTarget.querySelector(':invalid');if(invalid){invalid.focus();invalid.reportValidity();return}try{handler(data,e.currentTarget)}catch(err){toast(err.message||'Could not save changes',true)}};return dialog.querySelector('#form')} function field(label,name,value='',type='text',opts={}){const req=opts.required?'required':'';const min=opts.min!==undefined?`min="${opts.min}"`:'';const max=opts.max!==undefined?`max="${opts.max}"`:'';const step=opts.step?`step="${opts.step}"`:'';const hint=opts.hint?`${esc(opts.hint)}`:'';const cls=opts.full?'full':'';if(opts.options)return `| Specification | ${esc(a.name)} | ${esc(b.name)} |
|---|---|---|
| ${r[0]} | ${esc(r[1]??'Not recorded')} | ${esc(r[2]??'Not recorded')} |
| Criterion | Asset | Profile | Result |
|---|---|---|---|
| ${label} | ${esc(av||'Missing')} | ${esc(tv||'Missing')} | ${missing?'Information missing':mismatch?'Potential mismatch':'Recorded'} |
Add assets to build assignments.
'}Add assets to build assignments.
'}${conflicts.map(p=>esc(p.name)).join(', ')}
`);dialog.querySelector('#import-cancel').onclick=closeDialog;dialog.querySelector('#import-separate').onclick=()=>{mode='separate';closeDialog();merge()};dialog.querySelector('#import-replace').onclick=()=>{confirmDialog('Replace existing projects?','Matching local project IDs and all their data will be replaced by the backup.',()=>{mode='replace';merge()})}}catch(e){toast(`Backup not imported: ${e.message}`,true)}} - function storageEstimate(force=false){if(!navigator.storage?.estimate){const x=document.querySelector('#storage-status');if(x)x.textContent='Storage estimate is not supported by this browser.';return}navigator.storage.estimate().then(({usage=0,quota=0})=>{const x=document.querySelector('#storage-status');if(x)x.textContent=`${(usage/1024/1024).toFixed(2)} MB used of ${(quota/1024/1024).toFixed(0)} MB browser quota. Project data stays local.`;if(usage>45*1024*1024)toast('Browser storage is approaching the planner’s 50 MB guidance threshold. Export a backup.',true)}).catch(()=>{const x=document.querySelector('#storage-status');if(x)x.textContent='Could not read browser storage estimate.'})} + + function restoreJson(text){try{ + const incoming=validateBackup(JSON.parse(text)),conflicts=incoming.projects.filter(p=>state.projects.some(x=>x.id===p.id)); + const counts={projects:incoming.projects.length,sites:incoming.projects.reduce((n,p)=>n+p.sites.length,0),assets:incoming.projects.reduce((n,p)=>n+p.assets.length,0),profiles:incoming.projects.reduce((n,p)=>n+p.technologies.length,0),scenarios:incoming.projects.reduce((n,p)=>n+p.scenarios.length,0)}; + showDialog('Review backup contents','No data changes until you choose an import action.',`Matching local projects: ${conflicts.map(p=>esc(p.name)).join(', ')}. You can import separate copies or replace those projects.
`:'No project identifiers conflict with this browser’s saved projects.
'}`); + dialog.querySelector('#import-cancel').onclick=closeDialog; + dialog.querySelector('#import-continue').onclick=()=>{closeDialog();if(!conflicts.length){merge('add');return}showDialog('Project IDs already exist','Choose how to handle matching project identifiers.',`${conflicts.map(p=>esc(p.name)).join(', ')}
`);dialog.querySelector('#import-cancel-conflicts').onclick=closeDialog;dialog.querySelector('#import-separate').onclick=()=>{closeDialog();merge('separate')};dialog.querySelector('#import-replace').onclick=()=>{closeDialog();confirmDialog('Replace existing projects?','Matching local project IDs and all their data will be replaced by the backup.',()=>merge('replace'))}}; + function merge(mode){const next=structuredClone(state);for(const source of incoming.projects){const project=structuredClone(source),i=next.projects.findIndex(x=>x.id===project.id);if(i>=0){if(mode==='replace')next.projects[i]=project;else if(mode==='separate'){project.id=uid();project.name+=` (imported)`;next.projects.push(project)}}else next.projects.push(project)}if(!fitsLocalDataLimit(next)){toast('Backup not restored; the combined workspace exceeds Gridshift’s 3 MB local-data limit. Export current data and restore into a separate empty browser workspace.',true);return}state=next;state.activeProjectId=incoming.activeProjectId&&state.projects.some(p=>p.id===incoming.activeProjectId)?incoming.activeProjectId:state.projects[0]?.id||null;save('Backup restored');render()} + }catch(e){toast(`Backup not imported: ${e.message}`,true)}} + function storageEstimate(force=false){const x=document.querySelector('#storage-status');const chars=JSON.stringify(state).length;if(x)x.textContent=`Gridshift data: ${(chars*2/1024).toFixed(0)} KB of 2,930 KB local-data limit. This is a single-browser workspace; export a backup before approaching the limit.`;if(chars>MAX_STATE_CHARS*0.85)toast('Gridshift local data is approaching its 3 MB limit. Export a backup and split large workspaces.',true);if(!navigator.storage?.estimate)return;if(force&&x)x.textContent+=` Browser quota estimate is also being checked.`;navigator.storage.estimate().then(({usage=0,quota=0})=>{const target=document.querySelector('#storage-status');if(target)target.textContent+=` Browser origin usage: ${(usage/1024/1024).toFixed(2)} MB of ${(quota/1024/1024).toFixed(0)} MB; this is shared with other site data.`}).catch(()=>{const target=document.querySelector('#storage-status');if(target)target.textContent+=' Browser quota estimate is unavailable.'})} function seedDemo(){const p=mkProject('North Valley Grid Transition','Illustrative sample workspace · replace with verified utility records.',10);p.sites=[{id:uid(),name:'Cedar Ridge',region:'North District'},{id:uid(),name:'Lake Junction',region:'Central District'},{id:uid(),name:'Summit East',region:'East District'}];p.technologies=[{id:uid(),name:'Clean air GIS — 145 kV',insulation:'Dry air / vacuum interruption',gasComposition:'Clean dry air; composition reference required',voltageClass:'145 kV',voltageKv:145,interrupting:'31.5 kA',source:'Illustrative profile; replace with manufacturer specification',status:'Unverified',altAnnualCO2e:null,description:'User-maintained example profile for preliminary screening.'},{id:uid(),name:'Vacuum breaker — 72.5 kV',insulation:'Vacuum interruption / clean air insulation',gasComposition:'No fluorinated insulation gas specified in this example',voltageClass:'72.5 kV',voltageKv:72.5,interrupting:'25 kA',source:'Illustrative profile; replace with manufacturer specification',status:'Unverified',altAnnualCO2e:null,description:'User-maintained example profile; alternative lifecycle impacts not quantified.'}];p.assets=[['CB-114','Cedar Ridge','Circuit breaker',145,18,2008,2033,.006,'Fair'],['GIS-042','Lake Junction','Gas-insulated switchgear',72.5,32,2011,2036,.004,'Good'],['CB-208','Summit East','Circuit breaker',145,21,2002,2029,.009,'Poor'],['GIS-105','Cedar Ridge','Gas-insulated switchgear',72.5,26,2015,2040,.003,'Good'],['CB-311','Lake Junction','Circuit breaker',145,17,2006,2031,.007,'Fair']].map(([assetId,site,category,voltageKv,capacityKg,installYear,retirementYear,lossRate,condition])=>({id:uid(),assetId,site,category,manufacturer:'Example — verify',voltageKv,characteristics:'Interrupting rating requires verification',capacityKg,installYear,retirementYear,lossMode:'estimated',lossRate,lossSource:'Illustrative assumed annual loss rate — replace with utility data',condition,maintenanceNotes:'Sample data only',remainingGasKg:capacityKg*.45,recoveryEfficiency:.95,annualOpex:1500,annualMaintenance:2600,capex:category==='Circuit breaker'?320000:480000,installCost:80000,decommissionCost:19000,recoveryCost:6000}));const s={id:uid(),name:'Steady transition · 2027–2035',description:'Illustrative phased replacement for demonstration.',mode:'Phased transition',budget:600000,replacements:{},calcVersion:CALC_VERSION,gwpSnapshot:p.gwp,factorVersion:p.factorVersion,discountSnapshot:p.discountRate,baseYearSnapshot:p.baseYear,horizonSnapshot:p.horizon,inputSnapshot:snapshotScenario(p)};s.replacements[p.assets[2].id]={year:p.baseYear+2,technologyId:p.technologies[1].id};s.replacements[p.assets[0].id]={year:p.baseYear+4,technologyId:p.technologies[0].id};s.replacements[p.assets[1].id]={year:p.baseYear+6,technologyId:p.technologies[1].id};p.scenarios.push(s);p.activeScenarioId=s.id;state.projects.push(p);state.activeProjectId=p.id;page='dashboard';save('Sample workspace loaded. Replace illustrative inputs with verified data.');render()} function renderStatus(){const el=document.querySelector('#connection-status');if(!el)return;const online=navigator.onLine,saved=state.updatedAt?`Saved · ${fmtDate(state.updatedAt)}`:state.projects.length?'Saved locally':'Nothing saved yet';el.innerHTML=`${online?'Online':'Offline · local mode'} · ${esc(saved)}`} function setOnline(){renderStatus()} window.addEventListener('online',setOnline);window.addEventListener('offline',setOnline); + window.addEventListener('storage',event=>{if(event.key!==KEY)return;try{const next=event.newValue?JSON.parse(event.newValue):blankState();if(!next||next.version!==1||!Array.isArray(next.projects))throw new Error('Invalid shared workspace');validateBackup({format:'gridshift-backup',version:1,data:next});state=next;if(dialog.open)closeDialog();render();toast('Workspace updated from another open tab.')}catch{storageCorruptRaw=event.newValue||'null';showRecoveryDialog()}}); window.addEventListener('beforeinstallprompt',e=>{e.preventDefault();window.installPrompt=e;}); - if('serviceWorker' in navigator && location.protocol!=='file:')navigator.serviceWorker.register('./sw.js').catch(()=>{}); shell(); + if((migratedFactorProjects||migratedCostProjects)&&!storageCorruptRaw){save(null);const notes=[];if(migratedFactorProjects)notes.push(`updated the AR6 SF₆ factor in ${migratedFactorProjects} project${migratedFactorProjects===1?'':'s'}`);if(migratedCostProjects)notes.push(`marked older zero cost entries for review in ${migratedCostProjects} project${migratedCostProjects===1?'':'s'}`);toast(`Gridshift ${notes.join(' and ')}. Saved scenarios were preserved and flagged where needed.`,true)} + if(storageCorruptRaw!==null)showRecoveryDialog();else if(storageUnavailable)toast('Browser storage is unavailable. Changes can be exported from this tab but will not persist after it closes.',true); + if('serviceWorker' in navigator && location.protocol!=='file:')navigator.serviceWorker.register('./sw.js').then(registration=>{ + workerRegistration=registration; + const revealUpdate=()=>syncUpdateButton(); + if(registration.waiting&&navigator.serviceWorker.controller)revealUpdate(); + registration.addEventListener('updatefound',()=>{const worker=registration.installing;worker?.addEventListener('statechange',()=>{if(worker.state==='installed'&&navigator.serviceWorker.controller)revealUpdate()})}); + navigator.serviceWorker.addEventListener('controllerchange',()=>{if(applyWorkerUpdate)location.reload()}); + registration.update().catch(()=>{}); + }).catch(()=>{}); })(); diff --git a/core.js b/core.js new file mode 100644 index 0000000..8abfd65 --- /dev/null +++ b/core.js @@ -0,0 +1,87 @@ +(() => { + const CALC_VERSION = '1.2'; + const APP_VERSION = '0.2.3'; + const MAX_STATE_CHARS = 1_500_000; + + function calc(p,s){ + const baseYear=Number(s?.baseYearSnapshot??p.baseYear),horizon=Number(s?.horizonSnapshot??p.horizon),gwp=Number(s?.gwpSnapshot??p.gwp); + if(!Number.isInteger(baseYear)||baseYear<2000||baseYear>2200)throw Error('Calculation base year must be between 2000 and 2200.'); + if(!Number.isInteger(horizon)||horizon<1||horizon>50)throw Error('Calculation horizon must be between 1 and 50 years.'); + const start=baseYear,end=start+horizon-1,years=Array.from({length:horizon},(_,i)=>start+i),replacement=s?.replacements||{},assets=s?.inputSnapshot?.assets??p.assets,technologies=s?.inputSnapshot?.technologies??p.technologies,annual=years.map(year=>({year,baseline:0,scenario:0,cost:0,capital:0,baselineCost:0,assets:[]}));let incomplete=[];let npc=0,baselineNpc=0;const discount=Number(s?.discountSnapshot??p.discountRate)||0; + for(const a of assets){const plan=replacement[a.id],repYear=plan?.year,cap=Number(a.capacityKg),rate=Number(a.lossRate),measured=Number(a.measuredLoss),rawLoss=a.lossMode==='measured'?measured:cap*rate,loss=Number.isFinite(rawLoss)&&rawLoss>=0?rawLoss:0; + if(!Number.isFinite(rawLoss)||rawLoss<0)incomplete.push(`${a.assetId}: missing/invalid annual SF₆ loss input; emissions total is partial`); + for(const key of ['annualOpex','annualMaintenance'])if(a[key]===undefined||a[key]===null||a[key]==='')incomplete.push(`${a.assetId}: ${key==='annualOpex'?'annual operating':'annual maintenance'} cost missing; lifecycle cost total is partial`); + const tech=technologies.find(t=>t.id===plan?.technologyId);if(plan&&plan.year