Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

mobile-apps: a build plan the user can watch, with a trust report (#668)

Priyanshu Agrawal27632c79eee8
diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.json
index 0780b1b71..c1c0e810a 100644
--- a/plugins/mobile-apps/.claude-plugin/plugin.json
+++ b/plugins/mobile-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.3.4",
+ "version": "0.4.0",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.json
index 0780b1b71..c1c0e810a 100644
--- a/plugins/mobile-apps/.plugin/plugin.json
+++ b/plugins/mobile-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.3.4",
+ "version": "0.4.0",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 53e49a627..ae81a8c77 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -78,10 +78,11 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
- In `/create-mobile-app` only, `NEEDS_CONTEXT: dataverse-planning-mode:<required|connector-only>` from the `gate-only` architecture pass is a phase-completion signal, not a retry. The canonical handler validates the approved architecture before continuing; other phases cannot use it to change the data platform.
- Special early-return signals (`INDUSTRY_CONFIRM_REQUESTED:`, `DESIGN_VIBE_REQUESTED:`) pre-date this protocol and remain in effect — they are special-cased "ask the user one question and re-spawn me" handoffs, not terminal returns.
- The canonical orchestrator handler lives in [`skills/create-mobile-app/SKILL.md`](./skills/create-mobile-app/SKILL.md) Step 3.0. Future skills that spawn agents should reference it rather than duplicating the switch.
-13. **Metro lifecycle is project-local** — template `metro.config.js` delegates to `createPowerAppsMetroConfig`, whose host implementation writes sanitized `.powernative/metro-logs/` output during normal `npm run dev`; `/debug-app` locates and tails those files directly, with its cursor, health, and audit state under `.powernative/debug-app/`. Do not restore required `BashOutput`/terminal-ID behavior or host-specific project state directories. Host terminal APIs may be optional conveniences only. Never write unsanitized Metro output to disk, and never diagnose a log unless the logged PID/port still look live.
-14. **First-party native package defects are reported, not patched in customer projects** — a `node_modules/@microsoft/power-apps-native-*` frame alone is not proof of package ownership; first rule out invalid app usage against the package's public contract. Once a defect is confirmed inside one of these packages, do not edit `node_modules/`, generate `patch-package` or postinstall rewrites, vendor or fork the package, replace it with a git/tarball/local dependency, or shadow it through resolver aliases. Capture sanitized reproduction evidence and route to `/report-issue`.
-15. **Custom events are Application Insights-specific and opt-in** — Each generated app targets one customer-owned, workspace-based Application Insights resource. `app.json` → `expo.extra.appInsightsConfig` defaults to disabled and stores its connection string, matching the Power Apps canvas-app model. Treat the value as sensitive project configuration: do not print it, write it to `memory-bank.md`, or include it in summaries. Keep `includeUserId` false unless explicitly approved.
-16. **Plugin update notification** — Immediately after the frontmatter of every `user-invocable: true` skill except `/check-updates`, run `node "${PLUGIN_ROOT}/scripts/check-version.js"` and show any output before proceeding. The check is best-effort and must never block the requested workflow. `/check-updates` owns its explicit plugin-version check in Step 1 and must not run a duplicate startup check.
+13. **Every run documents itself in `docs/`** - [`scripts/app-docs.js`](scripts/app-docs.js) writes `<app>/docs/create-app-plan.html`, a living Fluent-format plan in the same visual language as the Power Pages `/create-site` artifacts (shared encoder ported to [`scripts/lib/render-template.js`](scripts/lib/render-template.js)). It records the environment, the confirmed brief, the Gate 1 architecture, the Gate 2 data model with a colour-coded ER diagram, the screen plan, and the design system, plus per-phase progress. Sections are written **when the decision is made**, so an aborted run still explains itself. The ER, column tables and new/reused/extended colouring are all derived from `dataModel.tables[]`, so populate those structurally rather than only shipping a Mermaid string. It is best-effort and must never gate, retry, or fail a build.
+14. **Metro lifecycle is project-local** — template `metro.config.js` delegates to `createPowerAppsMetroConfig`, whose host implementation writes sanitized `.powernative/metro-logs/` output during normal `npm run dev`; `/debug-app` locates and tails those files directly, with its cursor, health, and audit state under `.powernative/debug-app/`. Do not restore required `BashOutput`/terminal-ID behavior or host-specific project state directories. Host terminal APIs may be optional conveniences only. Never write unsanitized Metro output to disk, and never diagnose a log unless the logged PID/port still look live.
+15. **First-party native package defects are reported, not patched in customer projects** — a `node_modules/@microsoft/power-apps-native-*` frame alone is not proof of package ownership; first rule out invalid app usage against the package's public contract. Once a defect is confirmed inside one of these packages, do not edit `node_modules/`, generate `patch-package` or postinstall rewrites, vendor or fork the package, replace it with a git/tarball/local dependency, or shadow it through resolver aliases. Capture sanitized reproduction evidence and route to `/report-issue`.
+16. **Custom events are Application Insights-specific and opt-in** — Each generated app targets one customer-owned, workspace-based Application Insights resource. `app.json` → `expo.extra.appInsightsConfig` defaults to disabled and stores its connection string, matching the Power Apps canvas-app model. Treat the value as sensitive project configuration: do not print it, write it to `memory-bank.md`, or include it in summaries. Keep `includeUserId` false unless explicitly approved.
+17. **Plugin update notification** — Immediately after the frontmatter of every `user-invocable: true` skill except `/check-updates`, run `node "${PLUGIN_ROOT}/scripts/check-version.js"` and show any output before proceeding. The check is best-effort and must never block the requested workflow. `/check-updates` owns its explicit plugin-version check in Step 1 and must not run a duplicate startup check.
## Telemetry
@@ -103,6 +104,7 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro
- ✅ Connection model: per-environment connections, with platform-specific auth (`expo-msal-intune` on native, `expo-auth-session` on web)
- ✅ Auth: `/create-mobile-app` resolves the tenant from the selected Power Platform environment (`scripts/resolve-environment.js`), lists every tenant app registration visible to the signed-in Azure CLI user, evaluates the native runtime permission profile as one boolean, shows passing registrations first, and paginates the rest. The baseline requires Dynamics CRM `user_impersonation` and Power Platform API `PowerApps.Apps.Read`; when the approved plan contains non-Dataverse connectors, the checker also requires Azure API Connections `Runtime.All` plus the four Power Platform API connector read/write/user-consent scopes. The list uses self-contained `✓ All required permissions configured` / `✗ Missing required permissions` labels; missing details appear after selection. Discovery is best-effort: any CLI, Graph, tenant, response, or permission-check failure immediately falls back to the original pasted-client-ID flow with status unavailable. `/set-app-registration-native` infers connector use from the persisted plan or nonempty `power.config.json.connectionReferences` and provides the same read-only discovery, verification, ranking, pagination, and fallback behavior. Power Apps Wrap remains the final authority for redirect platforms, packaging permissions, third-party-app allowlisting, and admin consent.
- ✅ `/add-native` v0 scope: camera, location, push, biometrics, secure-store (already in template)
+- ✅ Build documentation: every run writes `docs/create-app-plan.html` - environment, requirements, architecture, a colour-coded Dataverse ER diagram, screen plan, design system, and live phase progress - in the Power Pages plan format. The page also carries a phone frame that advances from a building state to the generated screens to the device QR code. The folder survives the run so the app carries its own design record.
- ✅ Cross-host Metro diagnostics: user-owned `npm run dev`, port-probe liveness and stale-PID protection, sanitized project-local logs, a durable debug cursor, and read-only `status` plus foreground-loop `stop` commands
- ✅ Template is supplied as a fresh `microsoft/power-platform-skills/plugins/mobile-apps/template#main` folder before `/create-mobile-app` runs; users materialize it with `degit`, run `npm install`, then invoke the skill from that folder. The skill validates/prepares the folder and runs `npx power-apps init`.
- ✅ `brand/` directory convention: `/design-system` (Step 6.75) writes `brand/design-system.md` (spec), `brand/tokens.ts` (importable Tamagui tokens), and `brand/design-system.html` (visual gallery). Screen-builders MUST read `brand/design-system.md` if present; `## Negatives` = HARD RULES. `/create-mobile-app` Step 9b imports `brand/tokens.ts` via `skills/design-system/references/tamagui-integration.md`. Projects without `brand/` fall back to `## Design Direction` only — no breakage.
diff --git a/plugins/mobile-apps/assets/README.md b/plugins/mobile-apps/assets/README.md
new file mode 100644
index 000000000..9f094e931
--- /dev/null
+++ b/plugins/mobile-apps/assets/README.md
@@ -0,0 +1,42 @@
+# Plugin assets
+
+## `power-apps-icon.svg`
+
+The Power Apps product mark. The build plan (`assets/run-plan.html`, rendered into the app's
+`docs/` by `scripts/app-docs.js`) shows it in the topbar and inside the phone frame while an app
+is being generated, mirroring the Power Pages `/create-site` scaffold loader.
+
+Sourced from the official Power Platform scalable icon set (`PowerApps_scalable.svg`),
+96x96 viewBox, 4.4 KB.
+
+### How it is used
+
+`brandIconDataUri()` reads this file at render time and inlines it as a base64 `data:` URI, which
+the page carries in a single `<img id="brandLogo">`. The phone frame reads the same value back
+from that element rather than fetching anything.
+
+Inlined rather than copied beside the page for two reasons:
+
+- The plan ships a strict CSP whose `img-src` allows `data:` only. The page is opened over
+ `file://`, where the origin is opaque, so `img-src 'self'` would not reliably match a sibling
+ file — and loosening `img-src` to make one work would weaken the policy that keeps injected
+ mockup markup from fetching anything.
+- It makes the plan a single shareable file. A sibling asset is lost the moment someone mails the
+ HTML on its own.
+
+Reading the file is best-effort: a missing or unreadable source yields an empty `src` and the page
+renders without the mark rather than failing. There is no PNG fallback and no lettermark.
+
+### Replacing it
+
+Keep the replacement an SVG at this exact path — `brandIconDataUri()` hard-codes both the filename
+and the `image/svg+xml` media type, and neither is derived from the file.
+
+Size matters more than it would for a sibling file: the mark is inlined into the plan on **every**
+rewrite, and the plan is rewritten at each phase boundary. Base64 adds about a third. At 4.4 KB
+this is negligible; something in the hundreds of kilobytes would not be.
+
+Prefer a mark that reads at 62x62 CSS pixels, the size the phone frame draws it at.
+
+`template/assets/adaptive-icon.png` is **not** a substitute — it is a solid colour square used as
+the Android adaptive-icon foreground, not a logo.
diff --git a/plugins/mobile-apps/assets/power-apps-icon.svg b/plugins/mobile-apps/assets/power-apps-icon.svg
new file mode 100644
index 000000000..0316a7f5a
--- /dev/null
+++ b/plugins/mobile-apps/assets/power-apps-icon.svg
@@ -0,0 +1,57 @@
+<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_4303_1230)">
+<g clip-path="url(#clip1_4303_1230)">
+<path d="M44.1553 9.77196L62.9254 42.6196C64.8305 45.9536 64.8305 50.0464 62.9254 53.3804L44.1553 86.228C38.7808 95.6334 25.219 95.6335 19.8445 86.228L2.2525 55.4421C-0.382637 50.8306 -0.382645 45.1694 2.25249 40.5579L19.8445 9.77196C25.219 0.366551 38.7808 0.366549 44.1553 9.77196Z" fill="url(#paint0_linear_4303_1230)"/>
+<path d="M44.1553 9.77196L62.9254 42.6196C64.8305 45.9536 64.8305 50.0464 62.9254 53.3804L44.1553 86.228C38.7808 95.6334 25.219 95.6335 19.8445 86.228L2.2525 55.4421C-0.382637 50.8306 -0.382645 45.1694 2.25249 40.5579L19.8445 9.77196C25.219 0.366551 38.7808 0.366549 44.1553 9.77196Z" fill="url(#paint1_radial_4303_1230)"/>
+<path d="M65.9999 48L44.1553 86.228C38.7808 95.6334 25.219 95.6334 19.8445 86.228L1.99988 55C7.30568 64.2852 20.6941 64.2852 25.9999 55L47.9999 16.5L65.9999 48Z" fill="url(#paint2_linear_4303_1230)"/>
+<path d="M65.9999 48L44.1553 86.228C38.7808 95.6334 25.219 95.6334 19.8445 86.228L1.99988 55C7.30568 64.2852 20.6941 64.2852 25.9999 55L47.9999 16.5L65.9999 48Z" fill="url(#paint3_linear_4303_1230)"/>
+<path d="M54.9458 28.6554L81.9999 76L93.3881 56.0705C96.2458 51.0696 96.2458 44.9304 93.3881 39.9295L76.1553 9.77196C70.7808 0.366554 57.219 0.366554 51.8445 9.77197L41.0539 28.6554C44.1251 23.2809 51.8747 23.2809 54.9458 28.6554Z" fill="url(#paint4_linear_4303_1230)"/>
+<path d="M54.9458 28.6554L81.9999 76L93.3881 56.0705C96.2458 51.0696 96.2458 44.9304 93.3881 39.9295L76.1553 9.77196C70.7808 0.366554 57.219 0.366554 51.8445 9.77197L41.0539 28.6554C44.1251 23.2809 51.8747 23.2809 54.9458 28.6554Z" fill="url(#paint5_linear_4303_1230)"/>
+<path d="M79.7318 23.9691L47.9999 79.5L51.8445 86.228C57.219 95.6334 70.7808 95.6335 76.1553 86.228L94.0308 54.9459C96.4902 50.6419 96.4902 45.3581 94.0308 41.0541L79.7318 16.0309C81.1372 18.4903 81.1372 21.5096 79.7318 23.9691Z" fill="url(#paint6_linear_4303_1230)"/>
+<path d="M51.8445 86.228L47.9999 79.5L65.9999 48L81.9999 76L76.1553 86.228C70.7808 95.6334 57.219 95.6334 51.8445 86.228Z" fill="url(#paint7_linear_4303_1230)"/>
+</g>
+</g>
+<defs>
+<linearGradient id="paint0_linear_4303_1230" x1="15.9999" y1="60.5" x2="27.9994" y2="5.00001" gradientUnits="userSpaceOnUse">
+<stop stop-color="#520B56"/>
+<stop offset="1" stop-color="#742774"/>
+</linearGradient>
+<radialGradient id="paint1_radial_4303_1230" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(31.4999 8.00002) rotate(123.811) scale(65.5935 20.3157)">
+<stop offset="0.512391" stop-color="#4C1E4C" stop-opacity="0"/>
+<stop offset="1" stop-color="#4C1E4C"/>
+</radialGradient>
+<linearGradient id="paint2_linear_4303_1230" x1="11.9999" y1="71" x2="59.4999" y2="41.5" gradientUnits="userSpaceOnUse">
+<stop stop-color="#D467B9"/>
+<stop offset="0.308079" stop-color="#982F90"/>
+<stop offset="1" stop-color="#742774"/>
+</linearGradient>
+<linearGradient id="paint3_linear_4303_1230" x1="43.9999" y1="53.4998" x2="67.5" y2="50.9998" gradientUnits="userSpaceOnUse">
+<stop stop-color="#742774" stop-opacity="0"/>
+<stop offset="1" stop-color="#520B56"/>
+</linearGradient>
+<linearGradient id="paint4_linear_4303_1230" x1="42.9999" y1="29" x2="82.4999" y2="56" gradientUnits="userSpaceOnUse">
+<stop stop-color="#E9A1CB"/>
+<stop offset="0.40829" stop-color="#D467B9"/>
+<stop offset="1" stop-color="#BB35A4"/>
+</linearGradient>
+<linearGradient id="paint5_linear_4303_1230" x1="67.4999" y1="23.5" x2="80.9999" y2="26.5" gradientUnits="userSpaceOnUse">
+<stop stop-color="#E48CC7" stop-opacity="0"/>
+<stop offset="1" stop-color="#BB35A4"/>
+</linearGradient>
+<linearGradient id="paint6_linear_4303_1230" x1="89.2565" y1="77.1621" x2="76.4515" y2="41.3836" gradientUnits="userSpaceOnUse">
+<stop stop-color="#E48CC7"/>
+<stop offset="1" stop-color="#F7C4E2"/>
+</linearGradient>
+<linearGradient id="paint7_linear_4303_1230" x1="75.1999" y1="77.5801" x2="54.869" y2="32.0777" gradientUnits="userSpaceOnUse">
+<stop stop-color="#E48CC7" stop-opacity="0"/>
+<stop offset="0.67724" stop-color="#D467B9" stop-opacity="0.5"/>
+<stop offset="1" stop-color="#BB35A4"/>
+</linearGradient>
+<clipPath id="clip0_4303_1230">
+<rect width="96" height="96" fill="white"/>
+</clipPath>
+<clipPath id="clip1_4303_1230">
+<rect width="96" height="96" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/plugins/mobile-apps/assets/run-plan.html b/plugins/mobile-apps/assets/run-plan.html
new file mode 100644
index 000000000..9313c295c
--- /dev/null
+++ b/plugins/mobile-apps/assets/run-plan.html
@@ -0,0 +1,1815 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
+<!--
+ The carousel inserts screen mockups whose text comes from the user's own requirements, so this
+ page treats that markup as untrusted. The sanitizer below strips scripts and handlers; this
+ policy is the backstop that holds even if the sanitizer is wrong.
+
+ - `default-src 'none'` so anything not named here simply cannot load.
+ - `script-src` is the nonce alone. The Mermaid tag carries it, and a nonce admits an external
+ script as well as an inline one. Naming the CDN host as well would admit every script on
+ jsDelivr, so an injected script tag whose src named any npm package there would run; with the
+ nonce alone, an injected script element carries no nonce and will not run. Inline
+ event-handler attributes are refused because 'unsafe-inline' is absent from script-src.
+ - `style-src 'unsafe-inline'` is required: this page ships a `<style>` block, the mockups carry
+ `style=` attributes, and Mermaid injects stylesheets. Inline CSS cannot execute.
+ - `img-src data:` only - the brand mark and the QR are both inlined, so no image is ever
+ fetched, and an injected `<img src=...>` cannot call out.
+ - No `connect-src`, `frame-src` or `object-src`: the plan never talks to the network.
+-->
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-__ATTR_CSP_NONCE__'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'"/>
+<title>__PLAN_TITLE__ - __APP_NAME__</title>
+<!--
+ Mermaid is pinned to an exact version and checked against a hash of its bytes.
+
+ `@11` floated: it resolved to whatever the latest 11.x was at the moment the plan was opened,
+ so the code running inside a page that holds the environment URL, tenant id and the whole plan
+ could change without anything changing here. The CSP pins where a script may come from; only
+ integrity pins what it is. A file that does not match is refused, and the page already falls
+ back to showing each diagram's source, so a refusal degrades rather than breaks.
+
+ `crossorigin="anonymous"` is required for integrity to be enforced on a cross-origin script.
+
+ To upgrade: pick the new version, then
+ curl -sSL https://cdn.jsdelivr.net/npm/mermaid@<version>/dist/mermaid.min.js \
+ | openssl dgst -sha384 -binary | openssl base64 -A
+ and put "sha384-<output>" here. Cross-check jsDelivr's published hash for the same file at
+ https://data.jsdelivr.com/v1/packages/npm/mermaid@<version>?structure=flat before trusting it.
+-->
+<script nonce="__ATTR_CSP_NONCE__"
+ src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"
+ integrity="sha384-EOXBFmc3gx5mb+vn0vPvvGqACToJD24hhacX5Yx+8NUUQrHIle/Qi5Bg9o3zKwW2"
+ crossorigin="anonymous"></script>
+<style>
+:root{
+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --border:#e1dfdd; --border-light:#c8c6c4;
+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e; --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020;
+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;
+ --warn:#ca5010; --warn-bg:#ca50100a; --warn-border:#ca501020;
+ --footer-h:38px;
+ --fail:#a4262c; --fail-bg:#a4262c0a; --fail-border:#a4262c20;
+ --mono:'Cascadia Code','Consolas',monospace; --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
+ --radius:8px; --radius-sm:4px; --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
+}
+*{margin:0;padding:0;box-sizing:border-box;}
+html{scroll-behavior:smooth;}
+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;padding-bottom:var(--footer-h);}
+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;position:sticky;top:0;}
+.topbar-left{display:flex;align-items:center;gap:14px;}
+.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}
+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}
+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;}
+.topbar-sep{opacity:0.5;}
+.topbar-right{display:flex;gap:6px;flex-wrap:wrap;align-items:center;}
+.pill{font-size:11px;padding:4px 10px;border-radius:999px;font-weight:600;letter-spacing:0.2px;border:1px solid transparent;}
+.pill-platform{background:var(--accent-bg);color:var(--accent);border-color:var(--accent-border);}
+.pill-progress{background:var(--purple-bg);color:var(--purple);border-color:var(--purple-border);}
+.pill-live{background:var(--pass-bg);color:var(--pass);border-color:var(--pass-border);}
+.shell{display:flex;align-items:flex-start;}
+.layout{display:flex;min-height:calc(100vh - 65px);flex:1;min-width:0;}
+.rail{width:430px;flex-shrink:0;position:sticky;top:65px;height:calc(100vh - 65px - var(--footer-h));display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px 20px;border-left:1px solid var(--border);background:var(--surface);}
+.rail-title{font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;}
+.device{width:300px;height:620px;border-radius:40px;background:#1f1f1f;border:9px solid #2e2e2e;box-shadow:var(--shadow-4),0 18px 46px rgba(0,0,0,0.22);position:relative;overflow:hidden;flex-shrink:0;}
+.device-notch{position:absolute;top:0;left:50%;transform:translateX(-50%);width:118px;height:22px;background:#2e2e2e;border-radius:0 0 14px 14px;z-index:5;}
+.device-screen{position:absolute;inset:0;background:#faf9f8;overflow:hidden;}
+.device-screen iframe{width:100%;height:100%;border:0;}
+/* Stage 1 - building */
+.bld{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;background:#faf9f8;padding:0 28px;text-align:center;}
+.bld-orbit{position:relative;width:132px;height:132px;display:grid;place-items:center;}
+.bld-ring{position:absolute;border:1px solid rgba(32,31,30,.12);border-radius:50%;animation:railSpin linear infinite;}
+.bld-ring:nth-child(1){width:96px;height:96px;animation-duration:9s;}
+.bld-ring:nth-child(2){width:132px;height:132px;animation-duration:16s;animation-direction:reverse;border-style:dashed;}
+@keyframes railSpin{to{transform:rotate(360deg);}}
+.bld-core{width:72px;height:72px;display:grid;place-items:center;animation:railFloat 4s ease-in-out infinite;}
+.bld-core img{width:62px;height:62px;}
+@keyframes railFloat{0%,100%{transform:translateY(0);}50%{transform:translateY(-6px);}}
+.bld-title{color:#201f1e;font-size:16px;font-weight:650;}
+.bld-msg{color:#605e5c;font-size:13px;min-height:36px;}
+.bld-bar{width:100%;height:4px;border-radius:4px;background:#eceaea;overflow:hidden;}
+.bld-bar span{display:block;height:100%;background:#0078d4;transition:width .5s ease;}
+.bld-caps{display:flex;flex-wrap:wrap;justify-content:center;gap:6px;}
+.bld-cap{font-size:10.5px;color:#605e5c;background:#ffffff;border:1px solid #e1dfdd;border-radius:999px;padding:3px 9px;opacity:0;animation:railFade .6s ease forwards;}
+@keyframes railFade{to{opacity:1;}}
+/* Stage 2 - carousel */
+.car{position:absolute;inset:0;background:#fff;}
+.car-frame{position:absolute;inset:0;overflow:auto;contain:layout paint;}
+/* `contain: paint` makes this a containing block for absolutely AND fixed positioned
+ descendants, so an injected `style="position:fixed;inset:0"` in a mockup is trapped in the
+ phone frame instead of covering the plan. Attribute styles survive sanitizing because they
+ are what makes a mockup look like the screen; this is what keeps them local.
+ https://developer.mozilla.org/en-US/docs/Web/CSS/contain */
+.car-nav{position:absolute;bottom:0;left:0;right:0;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 12px;background:linear-gradient(to top,rgba(0,0,0,.55),transparent);z-index:4;}
+.car-btn{width:30px;height:30px;border-radius:50%;border:0;background:rgba(255,255,255,.92);color:#201f1e;font-size:15px;cursor:pointer;display:grid;place-items:center;box-shadow:var(--shadow-4);}
+.car-btn:disabled{opacity:.35;cursor:default;}
+.car-dots{display:flex;gap:5px;}
+.car-dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.45);}
+.car-dot.on{background:#fff;}
+.rail-caption{font-size:12px;color:var(--text-dim);text-align:center;min-height:32px;padding:0 10px;}
+/* Stage 3 - QR */
+.qr{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;background:#fff;padding:0 26px;text-align:center;}
+.qr img{width:196px;height:196px;}
+.qr-title{font-size:16px;font-weight:700;color:#201f1e;}
+.qr-sub{font-size:12.5px;color:#605e5c;line-height:1.55;}
+.qr-url{font-family:var(--mono);font-size:11px;color:#0078d4;word-break:break-all;}
+@media(max-width:1180px){.shell{flex-direction:column;}.rail{width:100%;position:static;height:auto;border-left:none;border-top:1px solid var(--border);}}
+.sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}
+.nav-group-label{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;padding:16px 22px 6px;}
+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}
+.nav-btn:hover{color:var(--text);background:var(--surface2);}
+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}
+.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}
+.nav-btn.active .nav-icon{opacity:0.9;}
+.content{flex:1;padding:32px 40px 72px;max-width:1060px;}
+.section{display:none;}
+.section.active{display:block;animation:fadeIn 0.3s ease;}
+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
+h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}
+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}
+.section-desc code{color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;font-family:var(--mono);font-size:12px;}
+h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}
+.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}
+.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:24px;}
+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}
+.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;background:var(--accent);}
+.stat-card:nth-child(2)::after{background:var(--purple);}
+.stat-card:nth-child(3)::after{background:var(--warn);}
+.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;color:var(--text-bright);}
+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}
+.progress-track{height:6px;border-radius:999px;background:var(--surface2);border:1px solid var(--border);overflow:hidden;margin-bottom:8px;}
+.progress-fill{display:block;height:100%;background:var(--accent);transition:width 0.4s ease;}
+.progress-meta{display:flex;justify-content:space-between;font-size:12px;color:var(--text-dim);margin-bottom:24px;}
+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 20px;margin-bottom:10px;display:grid;grid-template-columns:22px 1fr auto;gap:14px;align-items:start;box-shadow:var(--shadow-4);}
+.card.is-active{border-color:var(--accent-border);background:var(--accent-bg);}
+.card.is-skipped{opacity:0.55;}
+.mark{width:18px;height:18px;border-radius:50%;border:2px solid var(--border-light);margin-top:3px;flex-shrink:0;}
+.is-done .mark{border-color:var(--pass);background:var(--pass);position:relative;}
+/* Tick drawn from two borders on a rotated box rather than a glyph, so it cannot fall back
+ to a missing character and needs no extra element in the card markup. */
+.is-done .mark::after{content:'';position:absolute;left:4.5px;top:1px;width:3.5px;height:8px;border:solid #fff;border-width:0 2px 2px 0;transform:rotate(45deg);}
+.is-active .mark{border-color:var(--accent);border-right-color:transparent;animation:spin 1s linear infinite;}
+.is-failed .mark{border-color:var(--fail);background:var(--fail);}
+.is-skipped .mark{border-style:dashed;}
+@keyframes spin{to{transform:rotate(360deg);}}
+.step-title{font-weight:600;color:var(--text-bright);}
+.step-detail{font-size:12.5px;color:var(--text-dim);}
+.step-note{font-size:12.5px;color:var(--accent);margin-top:4px;}
+.step-ref{font-size:11px;color:var(--text-dim);font-family:var(--mono);margin-top:4px;opacity:0.75;}
+.chip{display:inline-flex;align-items:center;gap:5px;font-size:11px;padding:3px 10px;border-radius:4px;font-weight:600;background:var(--surface2);border:1px solid var(--border);color:var(--text-dim);white-space:nowrap;}
+.chip-done{background:var(--pass-bg);border-color:var(--pass-border);color:var(--pass);}
+.chip-active{background:var(--accent-bg);border-color:var(--accent-border);color:var(--accent);}
+.chip-failed{background:var(--fail-bg);border-color:var(--fail-border);color:var(--fail);}
+.empty{color:var(--text-dim);font-size:13px;padding:18px 20px;background:var(--surface);border:1px dashed var(--border);border-radius:var(--radius);}
+.cap{background:var(--surface);border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:var(--radius);padding:16px 20px;margin-bottom:10px;box-shadow:var(--shadow-4);}
+.cap-connector{border-left-color:var(--purple);}
+.cap-offline-on{border-left-color:var(--pass);}
+.cap-offline-off{border-left-color:var(--border-light);}
+.cap-head{display:flex;align-items:center;gap:10px;margin-bottom:6px;}
+.cap-icon{flex:0 0 28px;height:28px;border-radius:8px;}
+.cap-icon svg{width:17px;height:17px;}
+.cap-connector .cap-icon{background:var(--purple-bg);color:var(--purple);}
+.cap-name{font-size:14px;font-weight:700;color:var(--text-bright);}
+.cap-kind{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.6px;padding:2px 8px;border-radius:3px;background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);}
+.cap-kind-connector{background:var(--purple-bg);color:var(--purple);border-color:var(--purple-border);}
+.cap-why{font-size:13px;color:var(--text-dim);line-height:1.6;}
+.perm{display:flex;gap:14px;align-items:flex-start;padding:14px 0;border-bottom:1px solid var(--border);}
+.perm:last-child{border-bottom:none;}
+.perm-icon{flex:0 0 34px;height:34px;display:grid;place-items:center;border-radius:9px;background:var(--surface2);color:var(--text-dim);}
+.perm-icon svg{width:19px;height:19px;display:block;}
+.perm-body{flex:1;min-width:0;}
+.perm-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:3px;}
+.perm-name{font-size:13.5px;font-weight:600;color:var(--text-bright);}
+.perm-badge{font-size:10.5px;font-weight:700;letter-spacing:.06em;padding:2px 8px;border-radius:999px;border:1px solid transparent;}
+.perm-good{background:var(--pass-bg);color:var(--pass);border-color:var(--pass-border);}
+.perm-info{background:var(--accent-bg);color:var(--accent);border-color:var(--accent-border);}
+.perm-warn{background:var(--warn-bg);color:var(--warn);border-color:var(--warn-border);}
+.perm-muted{background:var(--surface2);color:var(--text-dim);border-color:var(--border);}
+.perm-act{font-size:12.5px;color:var(--text-dim);margin-top:4px;opacity:.85;}
+.perm-why{font-size:13px;color:var(--text-dim);line-height:1.6;}
+.boundary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px;}
+.boundary{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;box-shadow:var(--shadow-4);}
+.boundary h4{margin:0 0 10px;font-size:13.5px;color:var(--text-bright);}
+.boundary .bullets{font-size:13px;color:var(--text-dim);}
+.ai-footer{position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;
+ color:var(--text-dim);border-top:1px solid var(--border);background:var(--surface);z-index:100;}
+.input-banner{position:fixed;top:78px;right:24px;z-index:100;display:flex;align-items:center;gap:12px;
+ background:var(--warn-bg);border:1px solid var(--warn-border);color:var(--warn);padding:12px 14px 12px 18px;
+ border-radius:999px;font-size:13.5px;max-width:min(380px,calc(100vw - 48px));
+ box-shadow:0 6px 20px rgba(0,0,0,.12);background-color:#fff8f2;}
+.input-banner[hidden]{display:none;}
+.input-banner-icon{font-size:11px;flex-shrink:0;animation:bannerPulse 1.6s ease-in-out infinite;}
+.input-banner-text{line-height:1.35;flex:1;min-width:0;}
+.input-banner-text b{display:block;font-weight:650;}
+.input-banner-text small{display:block;font-size:12px;opacity:.85;margin-top:2px;color:var(--text-dim);}
+.input-banner-close{width:24px;height:24px;border:0;border-radius:50%;background:rgba(202,80,16,.12);
+ color:var(--warn);cursor:pointer;font-size:17px;line-height:1;flex-shrink:0;}
+.input-banner-close:hover{background:rgba(202,80,16,.22);}
+@keyframes bannerPulse{0%,100%{opacity:1;}50%{opacity:.35;}}
+.store-row{display:flex;gap:8px;justify-content:center;margin-top:6px;}
+.store-btn{display:flex;align-items:center;gap:9px;padding:7px 13px;border-radius:9px;
+ background:#000;color:#fff;text-decoration:none;line-height:1.15;
+ border:1px solid rgba(255,255,255,.22);}
+.store-btn:hover{background:#141414;}
+.store-logo{flex:0 0 auto;display:grid;place-items:center;}
+.store-logo svg{width:21px;height:21px;display:block;}
+.store-text{display:flex;flex-direction:column;}
+.store-kicker{font-size:8.5px;letter-spacing:.03em;opacity:.9;}
+.store-name{font-size:14px;font-weight:600;letter-spacing:-.01em;}
+.rail-note{font-size:11.5px;color:var(--text-dim);text-align:center;max-width:300px;line-height:1.45;
+ padding:6px 10px;border-radius:8px;background:var(--surface2);}
+.rail-note[hidden]{display:none;}
+.rail-link{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:var(--accent);
+ text-decoration:none;padding:6px 12px;border-radius:999px;border:1px solid transparent;}
+.rail-link:hover{border-color:var(--accent-border);background:var(--accent-bg);}
+.plan-doc{display:inline-flex;align-items:center;gap:8px;margin-bottom:14px;padding:8px 14px;
+ background:var(--surface);border:1px solid var(--border);border-radius:999px;
+ font-size:13px;color:var(--accent);text-decoration:none;box-shadow:var(--shadow-4);}
+.plan-doc:hover{border-color:var(--accent-border);background:var(--accent-bg);}
+.plan-doc-raw{font-family:var(--mono);font-size:12px;color:var(--text-dim);text-decoration:none;margin-left:8px;align-self:center;}
+.plan-doc-raw:hover{color:var(--accent);text-decoration:underline;}
+.bullets{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:6px;}
+.bullets li{line-height:1.55;}
+.bullets li::marker{color:var(--text-dim);}
+.cap-why strong{color:var(--text);font-weight:600;}
+.approval{display:flex;align-items:center;gap:10px;padding:12px 16px;border-radius:var(--radius);margin-bottom:18px;font-size:13px;font-weight:600;}
+.approval-proposed{background:var(--warn-bg);border:1px solid var(--warn-border);color:var(--warn);}
+.approval-approved{background:var(--pass-bg);border:1px solid var(--pass-border);color:var(--pass);}
+.approval-dot{width:8px;height:8px;border-radius:50%;background:currentColor;flex-shrink:0;}
+.approval-proposed .approval-dot{animation:approvalPulse 1.6s ease-in-out infinite;}
+@keyframes approvalPulse{0%,100%{opacity:.35;}50%{opacity:1;}}
+.facts{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px;margin-bottom:8px;}
+.fact{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow-4);}
+.fact-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}
+.fact-value{font-size:13.5px;color:var(--text-bright);word-break:break-word;}
+.fact-value.mono{font-family:var(--mono);font-size:12.5px;}
+.diagram{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px;box-shadow:var(--shadow-4);overflow:auto;margin-bottom:8px;}
+.diagram pre{font-family:var(--mono);font-size:12px;color:var(--text-dim);white-space:pre;margin:0;}
+.diagram-note{font-size:11.5px;color:var(--text-dim);margin-bottom:18px;}
+.badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.6px;padding:2px 8px;border-radius:3px;}
+.badge-create{background:var(--pass-bg);color:var(--pass);border:1px solid var(--pass-border);}
+.badge-reuse{background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);}
+.badge-extend{background:var(--warn-bg);color:var(--warn);border:1px solid var(--warn-border);}
+.status-pill{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.6px;padding:3px 9px;border-radius:999px;white-space:nowrap;}
+.status-new{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}
+.status-modified{color:var(--warn);background:var(--warn-bg);border:1px solid var(--warn-border);}
+.status-reused{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}
+.key-badge{font-size:9px;font-weight:700;padding:1px 5px;border-radius:3px;font-family:var(--mono);}
+.key-PK{color:var(--accent);background:var(--accent-bg);}
+.key-FK{color:var(--purple);background:var(--purple-bg);}
+.type-chip{font-size:10px;font-family:var(--mono);color:var(--text-dim);background:var(--surface2);padding:1px 6px;border-radius:3px;border:1px solid var(--border);}
+.entity{background:var(--surface);border:1px solid var(--border);border-left:3px solid var(--border-light);border-radius:var(--radius);margin-bottom:10px;box-shadow:var(--shadow-4);overflow:hidden;}
+.entity.new{border-left-color:var(--accent);}
+.entity.modified{border-left-color:var(--warn);}
+.entity.reused{border-left-color:var(--pass);}
+.entity-head{display:flex;align-items:center;gap:10px;padding:14px 18px;cursor:pointer;}
+.entity-name{font-family:var(--mono);font-size:13px;font-weight:700;color:var(--text-bright);}
+.entity-display{font-size:12.5px;color:var(--text-dim);}
+.entity-spacer{flex:1;}
+.expand-chevron{color:var(--text-dim);font-size:12px;transition:transform 0.2s;}
+.entity.open .expand-chevron{transform:rotate(90deg);}
+.entity-summary{padding:0 18px 14px;display:grid;gap:6px;}
+.entity-body{display:none;padding:0 18px 16px;border-top:1px solid var(--border);margin-top:2px;padding-top:14px;}
+.entity.open .entity-body{display:block;}
+.col-table{width:100%;border-collapse:collapse;margin-top:4px;}
+.col-table th{text-align:left;font-size:10px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;padding:6px 8px;border-bottom:2px solid var(--border);background:var(--surface2);}
+.col-table td{padding:6px 8px;border-bottom:1px solid var(--border);font-size:12.5px;}
+.col-table .col-logical{font-family:var(--mono);font-size:11px;color:var(--text-bright);}
+.rel-line{font-size:12.5px;color:var(--text);padding:4px 0;}
+.rel-arrow{color:var(--accent);font-weight:700;font-family:var(--mono);}
+.er-toolbar{display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-bottom:10px;}
+.er-legend{display:flex;gap:14px;flex-wrap:wrap;}
+.er-legend-item{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--text-dim);font-weight:500;}
+.er-legend-swatch{width:12px;height:12px;border-radius:2px;border:2px solid;}
+.er-toggle{padding:5px 12px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text-dim);font-size:12px;font-weight:600;cursor:pointer;font-family:var(--sans);transition:all 0.15s;}
+.er-toggle:hover{border-color:var(--accent);color:var(--accent);}
+.er-toggle.active{background:var(--accent-bg);border-color:var(--accent);color:var(--accent);}
+.palette-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:12px;}
+.swatch-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;box-shadow:var(--shadow-4);}
+.swatch{height:64px;width:100%;display:block;}
+.swatch-meta{padding:9px 12px;}
+.swatch-name{font-size:12px;font-weight:600;color:var(--text-bright);}
+.swatch-value{font-size:11px;color:var(--text-dim);font-family:var(--mono);}
+@media(max-width:860px){
+ .layout{flex-direction:column;}
+ .sidebar{width:100%;display:flex;flex-wrap:wrap;border-right:none;border-bottom:1px solid var(--border);padding:8px;}
+ .nav-group-label{width:100%;}
+ .nav-btn{width:auto;border-left:none;border-bottom:2px solid transparent;padding:10px 14px;}
+ .nav-btn.active{border-left:none;border-bottom-color:var(--accent);}
+ .content{padding:24px 18px 60px;}
+ .stats-grid{grid-template-columns:1fr;}
+}
+</style>
+</head>
+<body>
+<div class="topbar">
+ <div class="topbar-left">
+ <img class="logo" id="brandLogo" src="__ATTR_BRAND_ICON__" alt="Power Apps"/>
+ <div>
+ <div class="topbar-title">__PLAN_TITLE__</div>
+ <div class="topbar-sub">
+ <span>__HTML_APP_NAME__</span>
+ <span class="topbar-sep">|</span>
+ <span id="updatedAt" data-generated="__ATTR_GENERATED_ISO__">Updated __HTML_GENERATED_AT__ UTC</span>
+ </div>
+ </div>
+ </div>
+ <div class="topbar-right">
+ <span class="pill pill-platform">Data: __HTML_DATA_PLATFORM__</span>
+ <span class="pill pill-progress" id="pillProgress">Step 0 of 0</span>
+ </div>
+</div>
+
+<div class="input-banner" id="inputBanner" hidden>
+ <span class="input-banner-icon">&#9679;</span>
+ <div class="input-banner-text">
+ <b>Waiting for your input</b>
+ <small id="inputBannerPrompt"></small>
+ </div>
+ <button type="button" class="input-banner-close" id="inputBannerClose" aria-label="Dismiss">&times;</button>
+</div>
+
+<div class="shell">
+<div class="layout">
+ <div class="sidebar">
+ <div class="nav-group-label">Plan</div>
+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">&#9673;</span> Overview</button>
+ <button class="nav-btn" data-tab="steps"><span class="nav-icon">&#9638;</span> Build steps</button>
+ <button class="nav-btn" data-tab="requirements"><span class="nav-icon">&#9998;</span> Requirements</button>
+ <button class="nav-btn" data-tab="datamodel"><span class="nav-icon">&#9636;</span> Data model</button>
+ <button class="nav-btn" data-tab="capabilities"><span class="nav-icon">&#9679;</span> Capabilities</button>
+ <button class="nav-btn" data-tab="screens"><span class="nav-icon">&#9635;</span> Screens</button>
+ <button class="nav-btn" data-tab="design"><span class="nav-icon">&#9728;</span> Design</button>
+ <button class="nav-btn" data-tab="trust"><span class="nav-icon">&#9670;</span> Trust report</button>
+ </div>
+
+ <div class="content">
+ <div class="section active" id="tab-overview">
+ <h2>Overview</h2>
+ <div class="section-desc">
+ How <code>/create-mobile-app</code> is building this app. This page is rewritten as each
+ phase completes and stays in <code>docs/</code> afterwards.
+ </div>
+
+ <div class="summary-box" id="summaryBox"></div>
+
+ <div class="progress-track"><span class="progress-fill" id="progressFill"></span></div>
+ <div class="progress-meta">
+ <span id="progressCurrent"></span>
+ <span id="progressCount"></span>
+ </div>
+
+ <div class="stats-grid">
+ <div class="stat-card"><div class="stat-num" id="statDone">0</div><div class="stat-label">Completed</div></div>
+ <div class="stat-card"><div class="stat-num" id="statRemaining">0</div><div class="stat-label">Remaining</div></div>
+ <div class="stat-card"><div class="stat-num" id="statSkipped">0</div><div class="stat-label">Not needed</div></div>
+ </div>
+
+ <h3>Environment</h3>
+ <div class="facts" id="environmentFacts"></div>
+
+ <h3>Architecture</h3>
+ <div id="approval-architecture"></div>
+ <div class="facts" id="architectureFacts"></div>
+ <div id="overviewPlanDoc"></div>
+ </div>
+
+ <div class="section" id="tab-steps">
+ <h2>Build steps</h2>
+ <div class="section-desc">
+ Each row groups several skill steps; the reference shows which ones.
+ </div>
+ <div id="stepsContainer"></div>
+ </div>
+ <div class="section" id="tab-requirements">
+ <h2>Requirements</h2>
+ <div class="section-desc">What you asked for, and the choices confirmed during the wizard.</div>
+ <div class="summary-box" id="briefBox"></div>
+ <h3>Your choices</h3>
+ <div class="facts" id="requirementsFacts"></div>
+ </div>
+
+ <div class="section" id="tab-datamodel">
+ <h2>Data model</h2>
+ <div class="section-desc">Tables approved at Gate 2, and how each one was sourced.</div>
+
+ <div id="approval-datamodel"></div>
+ <div class="stats-grid">
+ <div class="stat-card"><div class="stat-num" id="statNew">0</div><div class="stat-label">New tables</div></div>
+ <div class="stat-card"><div class="stat-num" id="statReused">0</div><div class="stat-label">Reused</div></div>
+ <div class="stat-card"><div class="stat-num" id="statModified">0</div><div class="stat-label">Extended</div></div>
+ </div>
+
+ <div class="er-toolbar">
+ <div class="er-legend">
+ <div class="er-legend-item"><span class="er-legend-swatch" style="background:rgba(0,120,212,0.08);border-color:#0078d4;"></span> New</div>
+ <div class="er-legend-item"><span class="er-legend-swatch" style="background:rgba(202,80,16,0.08);border-color:#ca5010;"></span> Extended</div>
+ <div class="er-legend-item"><span class="er-legend-swatch" style="background:rgba(16,124,16,0.08);border-color:#107c10;"></span> Reused</div>
+ </div>
+ <button id="erCompactBtn" class="er-toggle">Compact view</button>
+ </div>
+
+ <div id="erContainer"></div>
+ <h3>Tables</h3>
+ <div id="tablesContainer"></div>
+ </div>
+
+ <div class="section" id="tab-capabilities">
+ <h2>Capabilities</h2>
+ <div class="section-desc">
+ What this app can do, and why each capability was chosen. An app can run entirely on
+ connectors with no Dataverse at all.
+ </div>
+
+ <h3>Device capabilities</h3>
+ <div id="deviceCapabilities"></div>
+
+ <h3>Connectors</h3>
+ <div id="connectorList"></div>
+
+ <h3>Offline</h3>
+ <div id="offlineBlock"></div>
+ </div>
+
+ <div class="section" id="tab-screens">
+ <h2>Screens</h2>
+ <div class="section-desc">The screen graph approved at Gate 3 and the per-screen specs from Gate 4.</div>
+ <div id="approval-screens"></div>
+ <div id="screensPlanDoc"></div>
+ <div id="graphContainer"></div>
+ <h3>Screen specs</h3>
+ <div id="screensContainer"></div>
+ </div>
+
+ <div class="section" id="tab-design">
+ <h2>Design</h2>
+ <div class="section-desc">The design direction applied to every generated screen.</div>
+ <div id="approval-design"></div>
+ <div class="facts" id="designFacts"></div>
+ <h3>Palette</h3>
+ <div class="palette-grid" id="paletteContainer"></div>
+ </div>
+
+ <div class="section" id="tab-trust">
+ <h2>Trust report</h2>
+ <div id="approval-trust"></div>
+ <div class="section-desc">
+ What this app can reach on the device, what it keeps, and what it does while you are not
+ looking. Every entry comes from the approved plan and the capabilities actually wired up,
+ not from what the shared template could theoretically do.
+ </div>
+
+ <h3>Permission behavior</h3>
+ <div class="section-desc">
+ How each permission is acquired, and when. The badge names the pattern - a permission asked
+ for beside the feature that needs it reads differently from one taken at launch, even
+ though both end in the same grant.
+ </div>
+ <div id="permissionList"></div>
+
+ <h3>Privacy and data boundaries</h3>
+ <div class="boundary-grid">
+ <div class="boundary" id="handlesCard"></div>
+ <div class="boundary" id="notCollectedCard"></div>
+ </div>
+
+ <h3>Battery-conscious behavior</h3>
+ <div class="section-desc">
+ What this app does while it is not on screen: polling, sensor subscriptions, sync
+ intervals, and any work that outlives a visible screen.
+ </div>
+ <div id="batteryList"></div>
+ </div>
+
+ </div>
+</div>
+
+<aside class="rail">
+ <div class="rail-title" id="railTitle">Your app</div>
+ <div class="device">
+ <div class="device-notch"></div>
+ <div class="device-screen" id="deviceScreen"></div>
+ </div>
+ <div class="rail-caption" id="railCaption"></div>
+ <div class="rail-note" id="railNote" hidden></div>
+ <div id="railPreviewLink"></div>
+</aside>
+</div>
+
+<script id="phasesData" type="application/json">__JSON_PHASES__</script>
+<script id="summaryData" type="application/json">__JSON_SUMMARY__</script>
+<script id="sectionsData" type="application/json">__JSON_SECTIONS__</script>
+<script id="sectionStatesData" type="application/json">__JSON_SECTION_STATES__</script>
+<script id="phoneData" type="application/json">__JSON_PHONE__</script>
+
+<script nonce="__ATTR_CSP_NONCE__">
+(function () {
+ var phases = JSON.parse(document.getElementById('phasesData').textContent);
+ var summary = JSON.parse(document.getElementById('summaryData').textContent);
+ var sections = JSON.parse(document.getElementById('sectionsData').textContent);
+ var sectionStates = JSON.parse(document.getElementById('sectionStatesData').textContent);
+ var phone = JSON.parse(document.getElementById('phoneData').textContent);
+ // Code-owned, substituted at render time; never plan data.
+ var brandIcon = document.getElementById('brandLogo').getAttribute('src') || '';
+ var capabilities = __JSON_CAPABILITIES__;
+
+ var STATUS_CLASS = {
+ done: 'is-done', active: 'is-active', failed: 'is-failed',
+ skipped: 'is-skipped', pending: 'is-pending'
+ };
+ var STATUS_CHIP = {
+ done: 'chip chip-done', active: 'chip chip-active',
+ failed: 'chip chip-failed', skipped: 'chip', pending: 'chip'
+ };
+ var STATUS_LABEL = {
+ done: 'complete', active: 'in progress', failed: 'failed',
+ skipped: 'not needed', pending: 'pending'
+ };
+
+ function el(tag, className, text) {
+ var node = document.createElement(tag);
+ if (className) node.className = className;
+ // textContent everywhere: phase notes are author-written today, but keeping the whole
+ // tree as text means a future free-text note can never become markup.
+ if (text !== undefined) node.textContent = text;
+ return node;
+ }
+
+ /**
+ * Each gated section is written to this page while it is still a *proposal*, so the user can
+ * read the rendered diagram before answering the gate in the terminal. The banner says which
+ * state it is in; without it a proposal and an approved decision look identical.
+ */
+ function approvalBanner(containerId, sectionName, proposedText) {
+ var container = document.getElementById(containerId);
+ if (!container) return;
+ container.textContent = '';
+
+ var state = sectionStates[sectionName];
+ if (!state) return;
+
+ var banner = el('div', 'approval approval-' + state);
+ banner.appendChild(el('span', 'approval-dot'));
+ banner.appendChild(el('span', null, state === 'proposed'
+ ? (proposedText || 'Proposed \u2014 review this, then answer the approval prompt in your terminal')
+ : 'Approved'));
+ container.appendChild(banner);
+ }
+
+ function facts(containerId, rows) {
+ var container = document.getElementById(containerId);
+ container.textContent = '';
+ var present = rows.filter(function (row) {
+ if (Array.isArray(row[1])) return row[1].length > 0;
+ return row[1] !== undefined && row[1] !== null && row[1] !== '';
+ });
+ if (!present.length) {
+ container.appendChild(el('div', 'empty', 'Not captured yet.'));
+ return;
+ }
+ present.forEach(function (row) {
+ var card = el('div', 'fact');
+ card.appendChild(el('div', 'fact-label', row[0]));
+ var value;
+ if (Array.isArray(row[1])) {
+ value = el('div', 'fact-value' + (row[2] ? ' mono' : ''));
+ value.appendChild(bullets(row[1]));
+ } else {
+ value = el('div', 'fact-value' + (row[2] ? ' mono' : ''), String(row[1]));
+ }
+ // row[3] renders the value in the typeface it names, so a font choice is something the
+ // reader can see rather than a string they have to imagine - the same reason the palette
+ // shows swatches instead of hex codes.
+ if (row[3]) applyFontFamily(value, row[3]);
+ card.appendChild(value);
+ container.appendChild(card);
+ });
+ }
+
+ function list(value) {
+ return Array.isArray(value) && value.length ? entryNames(value).join(', ') : '';
+ }
+
+ /**
+ * Render an element in a plan-named typeface.
+ *
+ * The name comes from the plan, so it is not interpolated into CSS unchecked: anything outside
+ * letters, digits, space, hyphen and period is rejected outright rather than escaped, which
+ * keeps a crafted value from closing the quoted family and appending further declarations.
+ * A generic fallback follows the family so an uninstalled font degrades to the system UI face
+ * instead of rendering as the browser default serif.
+ */
+ function applyFontFamily(node, family) {
+ var name = String(family == null ? '' : family).trim();
+ if (!name || !/^[A-Za-z0-9 .-]+$/.test(name)) return;
+ node.style.fontFamily = '"' + name + '", system-ui, sans-serif';
+ }
+
+ /**
+ * Render an array as a bulleted list.
+ *
+ * Several of these fields are genuinely enumerable - a feature list, the distinct rules that
+ * make up an offline decision - and joining them with commas produced a paragraph nobody could
+ * scan. Items go in as textContent, so a free-text feature can never become markup.
+ */
+ function bullets(items, className) {
+ var ul = el('ul', 'bullets' + (className ? ' ' + className : ''));
+ items.forEach(function (item) {
+ ul.appendChild(el('li', null, entryLabel(item)));
+ });
+ return ul;
+ }
+
+ /**
+ * Capabilities and connectors are recorded either as a bare name or as `{ name, reason }`.
+ * `/create-mobile-app` asks for the reason, but an older plan or a partial write can carry
+ * only the name, so every list of them has to accept both shapes. Going through String()
+ * instead is what put "[object Object]" on the overview.
+ */
+ function entryLabel(entry) {
+ if (typeof entry === 'string') return entry;
+ if (entry && typeof entry === 'object' && entry.name) return String(entry.name);
+ return '';
+ }
+
+ function entryNames(entries) {
+ return (entries || []).map(entryLabel).filter(Boolean);
+ }
+
+ /**
+ * Split author-written prose into the paragraphs it was written as.
+ *
+ * The plan records a rationale as one string with blank lines between points. One chunk means
+ * the author wrote a single paragraph, and forcing that into a one-item list reads worse than
+ * leaving it as prose - so the caller decides based on how many chunks come back.
+ */
+ function paragraphs(value) {
+ return String(value == null ? '' : value)
+ .split(/\n\s*\n/)
+ .map(function (part) { return part.replace(/\s+/g, ' ').trim(); })
+ .filter(Boolean);
+ }
+
+ /**
+ * Render a mermaid source into a container, or show its definition if that is impossible.
+ *
+ * Both diagrams go through here. They used to differ - the ER called mermaid.render() while
+ * the screen graph relied on startOnLoad - so turning startOnLoad off to control ER rendering
+ * silently left the screen graph as raw source. One path means one behaviour.
+ */
+ function renderMermaid(containerId, source, emptyText, onRendered) {
+ var container = document.getElementById(containerId);
+ container.textContent = '';
+ if (!source) {
+ container.appendChild(el('div', 'empty', emptyText));
+ return;
+ }
+
+ var panel = el('div', 'diagram');
+ container.appendChild(panel);
+
+ if (typeof mermaid === 'undefined') {
+ showSource(container, panel, source, { message: 'Mermaid could not load' });
+ return;
+ }
+ try {
+ mermaid.render('mmd' + Math.random().toString(36).slice(2), source).then(function (result) {
+ // Mermaid's output is built from plan data (table and screen names), so it goes through
+ // the same cleaning as the mockups rather than straight into the document.
+ // Its own stylesheet is kept: Mermaid scopes every rule to this SVG's id and builds them
+ // from the theme, not from plan data, and without it the diagram renders unstyled.
+ panel.textContent = '';
+ panel.appendChild(sanitizeMockup(result.svg, { keepStyle: true }));
+ if (onRendered) onRendered(panel);
+ }).catch(function (error) {
+ showSource(container, panel, source, error);
+ });
+ } catch (error) {
+ showSource(container, panel, source, error);
+ }
+ }
+
+ function showSource(container, panel, source, error) {
+ panel.textContent = '';
+ panel.appendChild(el('pre', null, source));
+ // Say why. A silent fall back to source reads like an intended view rather than a failure.
+ container.appendChild(el('div', 'diagram-note',
+ 'Diagram could not be drawn, showing its definition instead'
+ + (error && error.message ? ' \u2014 ' + error.message : '') + '.'));
+ }
+
+ /**
+ * Power Apps Mobile Preview - the app that scans the Metro QR and runs the build on a device.
+ * Locale-neutral forms: the plan is a file people share, and a hard-coded storefront would
+ * bounce a reader in another market through a redirect or an unavailable page.
+ */
+ var STORE_LINKS = [
+ {
+ kicker: 'Download on the',
+ name: 'App Store',
+ href: 'https://apps.apple.com/app/id6753083462',
+ // Apple mark, single path, filled with the button's text colour.
+ logo: '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M16.365 1.43c0 1.14-.47 2.2-1.24 2.98-.83.85-2.19 1.5-3.31 1.41-.13-1.1.44-2.26 1.2-3.01.85-.87 2.31-1.5 3.35-1.38zM20.5 17.1c-.5 1.15-.74 1.66-1.38 2.68-.9 1.42-2.16 3.19-3.73 3.2-1.39.01-1.75-.91-3.64-.9-1.89.01-2.28.92-3.67.9-1.57-.01-2.77-1.6-3.67-3.02-2.52-3.98-2.78-8.65-1.23-11.13 1.1-1.76 2.84-2.79 4.47-2.79 1.66 0 2.7.91 4.08.91 1.33 0 2.14-.91 4.06-.91 1.45 0 2.99.79 4.09 2.16-3.6 1.97-3.02 7.11.62 8.9z"/></svg>'
+ },
+ {
+ kicker: 'GET IT ON',
+ name: 'Google Play',
+ href: 'https://play.google.com/store/apps/details?id=com.microsoft.PreviewApp',
+ // Play mark: four faces of the same folded triangle, so the colours are fixed rather
+ // than inherited - it is the mark's identity, not decoration.
+ logo: '<svg viewBox="0 0 24 24" aria-hidden="true">'
+ + '<path fill="#00A0FF" d="M3.06 1.54A1.5 1.5 0 0 0 2.5 2.72v18.12c0 .47.22.89.56 1.18l10.24-10.24L3.06 1.54z"/>'
+ + '<path fill="#00E676" d="M3.06 1.54a1.5 1.5 0 0 1 1.5-.06l12.2 6.9-3.46 3.4L3.06 1.54z"/>'
+ + '<path fill="#FFCE00" d="M16.76 8.38l3.5 1.98c1 .57 1 1.7 0 2.27l-3.5 1.98-3.46-3.11 3.46-3.12z"/>'
+ + '<path fill="#FF3A44" d="M4.56 22.08a1.5 1.5 0 0 1-1.5-.06l10.24-10.24 3.46 3.4-12.2 6.9z"/>'
+ + '</svg>'
+ }
+ ];
+
+ /**
+ * Link out to the full-size mockups instead of opening them in a browser tab mid-run. The
+ * carousel already shows these screens in the phone frame, so a tab that steals focus while
+ * the user is reading the plan is an interruption rather than information.
+ */
+ function railPreviewLink() {
+ // The carousel shows HTML mockups rendered from the screen specs, not the built Tamagui
+ // screens. They are close enough to approve a layout on and not close enough to be held to,
+ // so say which one the user is looking at - but only while they are looking at it.
+ var note = document.getElementById('railNote');
+ if (note) {
+ var showing = phone.stage === 'screens' && phone.screens && phone.screens.length;
+ note.textContent = showing
+ ? 'Plan-time mockups. The built app will differ in places from what is shown here.'
+ : '';
+ note.hidden = !showing;
+ }
+
+ var container = document.getElementById('railPreviewLink');
+ if (!container) return;
+ container.textContent = '';
+
+ function add(href, label) {
+ if (!href) return;
+ var link = el('a', 'rail-link', label);
+ link.setAttribute('href', href);
+ link.setAttribute('target', '_blank');
+ link.setAttribute('rel', 'noopener');
+ container.appendChild(link);
+ }
+
+ add(summary.screenPreviewHref, 'Open screens full size \u2197');
+ // The QR is already drawn in the phone; this is for scanning it larger, and it links the
+ // PNG rather than the inlined data URI because browsers block top-level navigation to a
+ // data: URL. It drops away once `.expo/` is cleaned, leaving the inlined copy.
+ add(phone.qrHref, 'Open QR code full size \u2197');
+
+ // The QR stage is the end of the run, and a code is useless without the app that reads it.
+ // Only shown here: offering a store download while the app is still being generated would
+ // send the user off to install something they cannot use yet.
+ if (phone.stage !== 'qr') return;
+ var stores = el('div', 'store-row');
+ STORE_LINKS.forEach(function (store) {
+ var button = el('a', 'store-btn');
+ button.setAttribute('href', store.href);
+ button.setAttribute('target', '_blank');
+ // noopener/noreferrer: these are the only links in the plan that leave the machine.
+ button.setAttribute('rel', 'noopener noreferrer');
+ var mark = el('span', 'store-logo');
+ // Code-owned constant markup - no plan data reaches it - so it may be set as markup.
+ mark.innerHTML = store.logo;
+ button.appendChild(mark);
+ var text = el('span', 'store-text');
+ text.appendChild(el('span', 'store-kicker', store.kicker));
+ text.appendChild(el('span', 'store-name', store.name));
+ button.appendChild(text);
+ stores.appendChild(button);
+ });
+ container.appendChild(stores);
+ }
+
+ // Elements that execute, navigate, or reach the network. `link`/`meta`/`base` are included
+ // because a mockup is a fragment of a document and must not redefine this one's head.
+ // `STYLE` is here for a different reason from the rest. The others execute or navigate; a
+ // stylesheet cannot, but its selectors are global, so a mockup carrying one could restyle the
+ // approval banner or the trust report - hiding or spoofing the very UI a reviewer is reading.
+ // The CSP cannot refuse it: `style-src 'unsafe-inline'` is required for this page's own
+ // stylesheet and for Mermaid's. Mockups keep their `style=` attributes, which only ever affect
+ // the element carrying them; see `.car-frame` for how those are kept inside the phone.
+ // `ANIMATE` and `SET` are SVG animation elements, which can rewrite another element's `href`
+ // after this pass has checked it.
+ var MOCKUP_BANNED_TAGS = ['SCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'LINK', 'META', 'BASE', 'FORM', 'STYLE',
+ 'ANIMATE', 'SET'];
+ // `javascript:` executes; `data:text/html` navigates to attacker-controlled markup with this
+ // document's privileges. Images as `data:` are fine and are how the QR is drawn.
+ var MOCKUP_BANNED_URL = /^(javascript:|data:text\/html)/i;
+
+ /**
+ * Make generated mockup markup inert before it enters the document.
+ *
+ * The blocks come from `/design-system`, but their text is the user's own requirements, so a
+ * handler or SVG payload that survived into the mockup would run when the plan is opened. The
+ * page's CSP already refuses unnonced scripts and inline handlers; this is the second line, so
+ * a policy that is ever loosened does not immediately become an execution path.
+ *
+ * Parsed into a `<template>`, whose content is an inert fragment: nothing executes and no
+ * resource is fetched while it is being cleaned.
+ */
+ function sanitizeMockup(markup, options) {
+ var keepStyle = !!(options && options.keepStyle);
+ var holder = document.createElement('template');
+ holder.innerHTML = String(markup == null ? '' : markup);
+ var nodes = holder.content.querySelectorAll('*');
+ for (var i = 0; i < nodes.length; i++) {
+ var node = nodes[i];
+ // `tagName` is upper case only for HTML elements. Inside inline SVG an element keeps its
+ // own case, so `<svg><style>` reports "style" and passed an upper-case list untouched.
+ var tag = String(node.tagName || '').toUpperCase();
+ if (MOCKUP_BANNED_TAGS.indexOf(tag) >= 0 && !(keepStyle && tag === 'STYLE')) {
+ if (node.parentNode) node.parentNode.removeChild(node);
+ continue;
+ }
+ var attrs = node.attributes;
+ for (var j = attrs.length - 1; j >= 0; j--) {
+ var name = attrs[j].name;
+ // Test the URL the browser will actually follow. It drops tabs and newlines from
+ // anywhere in a URL and leading control characters and spaces, so `java&#9;script:`
+ // still navigates: https://url.spec.whatwg.org/#concept-basic-url-parser
+ var value = attrs[j].value.replace(/[\u0000-\u0020]/g, '');
+ // Every event handler, however it is spelled.
+ if (/^on/i.test(name)) { node.removeAttribute(name); continue; }
+ if (/^(href|src|xlink:href|action|formaction)$/i.test(name) && MOCKUP_BANNED_URL.test(value)) {
+ node.removeAttribute(name);
+ }
+ }
+ }
+ return holder.content;
+ }
+
+ function renderPhone() {
+ railPreviewLink();
+ var screen = document.getElementById('deviceScreen');
+ var title = document.getElementById('railTitle');
+ var caption = document.getElementById('railCaption');
+ screen.textContent = '';
+ caption.textContent = '';
+
+ if (phone.stage === 'qr' && phone.qrImage) {
+ title.textContent = 'Open it on your phone';
+ var qr = el('div', 'qr');
+ var img = document.createElement('img');
+ img.src = phone.qrImage;
+ img.alt = 'Metro QR code';
+ qr.appendChild(img);
+ qr.appendChild(el('div', 'qr-title', 'Scan to run the app'));
+ qr.appendChild(el('div', 'qr-sub', 'Open the Power Apps Mobile Preview app and scan this code. Your phone and this machine need to be on the same network.'));
+ if (phone.qrUrl) qr.appendChild(el('div', 'qr-url', phone.qrUrl));
+ screen.appendChild(qr);
+ caption.textContent = 'Edits hot-reload straight onto the device.';
+ return;
+ }
+
+ if (phone.stage === 'screens' && phone.screens && phone.screens.length) {
+ title.textContent = 'Your screens';
+ var index = 0;
+ var car = el('div', 'car');
+ var frame = el('div', 'car-frame');
+ var nav = el('div', 'car-nav');
+ var prev = el('button', 'car-btn', '\u2039');
+ prev.setAttribute('aria-label', 'Previous screen');
+ var next = el('button', 'car-btn', '\u203a');
+ next.setAttribute('aria-label', 'Next screen');
+ var dots = el('div', 'car-dots');
+ nav.appendChild(prev); nav.appendChild(dots); nav.appendChild(next);
+ car.appendChild(frame); car.appendChild(nav);
+ screen.appendChild(car);
+
+ var show = function (i) {
+ index = Math.max(0, Math.min(phone.screens.length - 1, i));
+ var current = phone.screens[index] || {};
+ // Replaced wholesale each time, then refilled from the sanitized fragment. Assigning
+ // innerHTML directly would put unexamined markup into the document.
+ frame.textContent = '';
+ frame.appendChild(sanitizeMockup(current.html));
+ caption.textContent = (current.name ? current.name + ' \u00b7 ' : '')
+ + (index + 1) + ' of ' + phone.screens.length;
+ prev.disabled = index === 0;
+ next.disabled = index === phone.screens.length - 1;
+ dots.textContent = '';
+ phone.screens.forEach(function (unused, i2) {
+ dots.appendChild(el('span', 'car-dot' + (i2 === index ? ' on' : '')));
+ });
+ };
+ prev.addEventListener('click', function () { show(index - 1); });
+ next.addEventListener('click', function () { show(index + 1); });
+ show(0);
+ return;
+ }
+
+ title.textContent = 'Building your app';
+ var bld = el('div', 'bld');
+ var orbit = el('div', 'bld-orbit');
+ orbit.appendChild(el('div', 'bld-ring'));
+ orbit.appendChild(el('div', 'bld-ring'));
+ var core = el('div', 'bld-core');
+ var logo = document.createElement('img');
+ logo.src = brandIcon;
+ logo.alt = '';
+ core.appendChild(logo);
+ orbit.appendChild(core);
+ bld.appendChild(orbit);
+
+ bld.appendChild(el('div', 'bld-title', 'Step ' + Math.min(summary.done + 1, summary.total) + ' of ' + summary.total));
+ bld.appendChild(el('div', 'bld-msg', summary.currentTitle));
+ var bar = el('div', 'bld-bar');
+ var fill = el('span');
+ fill.style.width = summary.percent + '%';
+ bar.appendChild(fill);
+ bld.appendChild(bar);
+
+ var caps = el('div', 'bld-caps');
+ capabilities.forEach(function (label, i) {
+ var chip = el('span', 'bld-cap', label);
+ chip.style.animationDelay = (0.25 + i * 0.16) + 's';
+ caps.appendChild(chip);
+ });
+ bld.appendChild(caps);
+ screen.appendChild(bld);
+ caption.textContent = 'Your screens appear here once the design is locked.';
+ }
+
+ /**
+ * Surface a blocked run the way `/create-site` does: a persistent pill, not a toast, because
+ * the answer is wanted in the terminal and the user may be reading another tab when the prompt
+ * appears. Dismissal is keyed to the prompt text, so closing one gate's banner does not
+ * suppress the next gate's, and it is forgotten once nothing is waiting.
+ */
+ // Kept in sessionStorage because the page reloads itself every few seconds; a dismissal held
+ // only in memory came back on the next reload.
+ var STORE_DISMISSED = 'mobile-plan-dismissed-prompt';
+ var dismissedPrompt = null;
+ try { dismissedPrompt = sessionStorage.getItem(STORE_DISMISSED); } catch (e) { /* private mode */ }
+
+ function renderInputBanner() {
+ var banner = document.getElementById('inputBanner');
+ if (!banner) return;
+ var prompt = summary.awaitingInput || '';
+ if (!prompt) {
+ dismissedPrompt = null;
+ try { sessionStorage.removeItem(STORE_DISMISSED); } catch (e) { /* private mode */ }
+ }
+ document.getElementById('inputBannerPrompt').textContent = prompt;
+ banner.hidden = !prompt || dismissedPrompt === prompt;
+ }
+
+ function renderOverview() {
+ approvalBanner('approval-architecture', 'architecture');
+ document.getElementById('summaryBox').textContent = summary.narrative;
+ document.getElementById('progressFill').style.width = summary.percent + '%';
+ document.getElementById('progressCurrent').textContent = summary.currentTitle;
+ document.getElementById('progressCount').textContent =
+ summary.done + ' of ' + summary.total + ' steps done' +
+ (summary.failed ? ' · ' + summary.failed + ' failed' : '');
+ document.getElementById('statDone').textContent = summary.done;
+ document.getElementById('statRemaining').textContent = summary.total - summary.done;
+ document.getElementById('statSkipped').textContent = summary.skipped;
+ document.getElementById('pillProgress').textContent =
+ 'Step ' + Math.min(summary.done + 1, summary.total) + ' of ' + summary.total;
+
+ var env = sections.environment || {};
+ facts('environmentFacts', [
+ ['Environment', env.displayName],
+ ['Environment ID', env.environmentId, true],
+ ['Environment URL', env.environmentUrl, true],
+ ['Tenant', env.tenantId, true],
+ ['Publisher prefix', env.publisherPrefix, true],
+ ['App registration', (sections.auth || {}).status]
+ ]);
+
+ planDocLink('overviewPlanDoc', 'Read the full plan');
+
+ var arch = sections.architecture || {};
+ facts('architectureFacts', [
+ ['Data platform', arch.dataPlatform],
+ ['Device capabilities', entryNames(arch.nativeCapabilities)],
+ ['Connectors', entryNames(arch.connectors)]
+ ]);
+ }
+
+ function renderRequirements() {
+ var req = sections.requirements || {};
+ document.getElementById('briefBox').textContent =
+ req.brief || 'The confirmed feature brief will appear here once requirements are agreed.';
+ facts('requirementsFacts', [
+ ['App name', req.appName],
+ ['Folder', req.slug, true],
+ ['Platforms', list(req.platforms) || req.platforms],
+ ['Aesthetic', req.aesthetic],
+ ['Industry', req.industry],
+ ['Features', req.features]
+ ]);
+ }
+
+ var REASON_LABEL = {
+ new: 'Why create it:', reused: 'Why reuse it:', modified: 'Why extend it:',
+ };
+
+ var STATUS_ALIAS = { create: 'new', created: 'new', extend: 'modified', modify: 'modified', reuse: 'reused', existing: 'reused' };
+
+ function tableStatus(table) {
+ var raw = String(table.status || table.action || 'new').toLowerCase();
+ return STATUS_ALIAS[raw] || (['new', 'modified', 'reused'].indexOf(raw) >= 0 ? raw : 'new');
+ }
+
+ // Mermaid's erDiagram grammar accepts a narrow ATTRIBUTE_WORD. Dataverse type names such as
+ // "Yes/No" contain characters that abort the whole parse, so strip anything outside the
+ // allowed set rather than letting one column blank the diagram.
+ function erWord(value) {
+ return String(value == null ? '' : value).replace(/[^A-Za-z0-9_]/g, '_');
+ }
+
+ function erLabel(value) {
+ // Newlines, quotes and angle brackets all end a mermaid label early. Truncate too: an
+ // over-long label wraps the box and pushes the diagram off screen.
+ return String(value == null ? '' : value)
+ .replace(/[\r\n]+/g, ' ')
+ .replace(/"/g, "'")
+ .replace(/[<>]/g, '')
+ .slice(0, 40);
+ }
+
+ /**
+ * Emit one of exactly three known-good cardinality tokens - never a value from the plan.
+ * `native-app-plan.md` writes human shorthand ("N:1"), and a single unrecognised token aborts
+ * the whole erDiagram parse, which is how a complete model ends up displayed as source. An
+ * allowlist makes an unrenderable diagram impossible rather than merely unlikely.
+ */
+ function erCardinality(value) {
+ var raw = String(value == null ? '' : value).trim().toLowerCase();
+ if (raw === '1:1' || raw === '||--||' || raw === 'one-to-one') return '||--||';
+ if (raw === 'n:n' || raw === 'm:n' || raw === '}o--o{' || raw === 'many-to-many') return '}o--o{';
+ if (raw === 'n:1' || raw === 'm:1' || raw === '}o--||' || raw === 'many-to-one') return '}o--||';
+ // One-to-many is what a lookup column produces, so it is the safe default for anything else.
+ return '||--o{';
+ }
+
+ function buildErDiagram(tables, compact) {
+ var lines = ['erDiagram'];
+ var ids = {};
+ tables.forEach(function (table) {
+ var name = String(table.logicalName || table.name || '');
+ var id = erWord(name).toUpperCase();
+ ids[name] = id;
+ lines.push(' ' + id + '["' + erLabel(name) + (table.displayName ? ' (' + erLabel(table.displayName) + ')' : '') + '"] {');
+ var columns = table.columns || [];
+ if (compact) columns = columns.filter(function (c) { return (c.key || '') === 'PK'; });
+ columns.forEach(function (column) {
+ if (typeof column === 'string') { lines.push(' string ' + erWord(column)); return; }
+ var key = column.key === 'PK' || column.key === 'FK' ? ' ' + column.key : '';
+ lines.push(' ' + (erWord(column.type) || 'string') + ' ' + erWord(column.logicalName || column.name) + key);
+ });
+ lines.push(' }');
+ });
+
+ var seen = {};
+ tables.forEach(function (table) {
+ var from = ids[String(table.logicalName || table.name || '')];
+ (table.relationships || []).forEach(function (rel) {
+ var to = ids[rel.relatedTable];
+ // A relationship whose related table is not in the model has nowhere to point, so it is
+ // skipped. A table relating to itself is not that: parent account, manager, and category
+ // hierarchies are ordinary Dataverse models, and Mermaid draws the same entity on both
+ // ends, so dropping them made the plan misstate the approved model.
+ if (!from || !to) return;
+ // Both tables declare the same relationship from their own side, so the reverse
+ // declaration is a duplicate and is suppressed - but only for that same relationship.
+ // The name is part of the identity, or a second lookup between the same two tables is
+ // lost.
+ var pairKey = [from, to].sort().join('|') + '|' + erLabel(rel.name || 'related');
+ if (seen[pairKey]) return;
+ seen[pairKey] = true;
+ lines.push(' ' + from + ' ' + erCardinality(rel.cardinality) + ' ' + to + ' : "' + erLabel(rel.name || 'related') + '"');
+ });
+ });
+ return lines.join('\n');
+ }
+
+ /**
+ * Derive the screen graph from the approved screen list.
+ *
+ * Deliberately NOT read from a planner-authored mermaid string. The ER diagram used to work
+ * that way and a single bad token rendered the whole model as source; the same field here was
+ * never populated by anything, so the graph silently showed its empty state instead. Route
+ * nesting is already present in `list[]`, so deriving the graph from the same data the cards
+ * render means the two cannot disagree, and there is no token the plan can supply that breaks
+ * the parse.
+ */
+ function buildScreenGraph(items, navigation) {
+ var nodes = items.map(function (screen, index) {
+ var route = String(screen.route || '');
+ return {
+ id: 'S' + index,
+ // Normalize to a trailing slash so prefix tests are unambiguous: without it
+ // "/(app)/sites" would parent "/(app)/sites-admin" as well as "/(app)/sites/[id]".
+ prefix: route.replace(/\/+$/, '') + '/',
+ name: erLabel(screen.name || route || 'Screen'),
+ // Everything under the (app) route group hangs off the signed-in shell; anything else
+ // (login, onboarding) is an entry point that leads into it.
+ inShell: route.indexOf('/(app)') === 0
+ };
+ });
+
+ nodes.forEach(function (node) {
+ var parent = null;
+ nodes.forEach(function (other) {
+ if (other === node || node.prefix === other.prefix) return;
+ if (node.prefix.indexOf(other.prefix) !== 0) return;
+ // The deepest matching route is the real parent: /a/[id]/scan belongs to /a/[id], not /a.
+ if (!parent || other.prefix.length > parent.prefix.length) parent = other;
+ });
+ node.parent = parent;
+ });
+
+ // `navigation` is a full sentence ("Bottom tabs (Today, Schedule...) with a stack pushed
+ // from each tab"). erLabel's hard 40-char cut would slice it mid-word, so take the leading
+ // phrase before the first bracket or full stop, which is the shell's actual name.
+ var shellLabel = erLabel(String(navigation || '').split(/[(.]/)[0].trim()) || 'App shell';
+ var lines = ['flowchart LR'];
+ lines.push(' SHELL{{"' + shellLabel + '"}}');
+ nodes.forEach(function (node) {
+ lines.push(' ' + node.id + '["' + node.name + '"]');
+ });
+ nodes.forEach(function (node) {
+ if (node.parent) lines.push(' ' + node.parent.id + ' --> ' + node.id);
+ else if (node.inShell) lines.push(' SHELL --> ' + node.id);
+ else lines.push(' ' + node.id + ' --> SHELL');
+ });
+ return lines.join('\n');
+ }
+
+ /**
+ * Tint the rendered entity boxes by status so the diagram carries the same new/extended/reused
+ * meaning as the legend and the cards. Mermaid v11 prefixes node ids with the svg element id
+ * (erSvg123-entity-INSPECTION-0), so match on the suffix rather than an exact id.
+ */
+ function colorErDiagram(container, tables) {
+ var svg = container.querySelector('svg');
+ if (!svg) return;
+
+ // Header, both alternating row bands, and the dividers between them. Tinting the header
+ // alone left every table's body the same lavender Mermaid ships, so the status read as a
+ // stripe at the top rather than as a property of the table - which is how a reader loses
+ // track of which table is which once the diagram is more than a screen tall. Matches the
+ // power-pages data-model plan, which these values are taken from.
+ var fills = { new: '#d0e4f5', modified: '#f5dcc8', reused: '#c8e6c9' };
+ var rowOddFills = { new: '#e8f2fc', modified: '#fdf0e6', reused: '#e8f5e9' };
+ var rowEvenFills = { new: '#f0f7fe', modified: '#fef6ee', reused: '#f1f9f1' };
+ var strokes = { new: '#0078d4', modified: '#ca5010', reused: '#107c10' };
+
+ var statusById = {};
+ tables.forEach(function (table) {
+ var id = erWord(table.logicalName || table.name || '').toUpperCase();
+ statusById[id] = tableStatus(table);
+ });
+
+ svg.querySelectorAll('g.node').forEach(function (node) {
+ var match = (node.getAttribute('id') || '').match(/entity-(.+)-\d+$/);
+ if (!match) return;
+ var status = statusById[match[1]];
+ if (!status) return;
+
+ var group = node.querySelector('.outer-path') || node.children[0];
+ if (!group || group.tagName !== 'g') return;
+ var paths = group.querySelectorAll('path');
+ if (paths[0]) paths[0].setAttribute('fill', fills[status]);
+ if (paths[1]) {
+ paths[1].setAttribute('stroke', strokes[status]);
+ paths[1].setAttribute('stroke-width', '2');
+ }
+
+ node.querySelectorAll('.row-rect-odd, .row-rect-even').forEach(function (row) {
+ var fill = row.classList.contains('row-rect-odd') ? rowOddFills : rowEvenFills;
+ var rect = row.querySelector('path');
+ if (rect) rect.setAttribute('fill', fill[status]);
+ });
+
+ node.querySelectorAll('.divider path').forEach(function (line) {
+ // A divider Mermaid drew as `none` is a spacer, not a rule; leaving it alone keeps the
+ // box from gaining lines it was not meant to have.
+ if (line.getAttribute('stroke') !== 'none') line.setAttribute('stroke', strokes[status]);
+ });
+ });
+ }
+
+ function drawEr(source, tables) {
+ renderMermaid('erContainer', source,
+ 'No data model \u2014 this app uses connectors only.',
+ function (panel) { colorErDiagram(panel, tables || []); });
+ }
+
+ function renderDataModel() {
+ approvalBanner('approval-datamodel', 'dataModel');
+ var model = sections.dataModel || {};
+ var tables = model.tables || [];
+
+ var counts = { new: 0, modified: 0, reused: 0 };
+ tables.forEach(function (table) { counts[tableStatus(table)] += 1; });
+ document.getElementById('statNew').textContent = counts.new;
+ document.getElementById('statReused').textContent = counts.reused;
+ document.getElementById('statModified').textContent = counts.modified;
+
+ // Built from the table data so the ER stays in step with what was actually approved. A
+ // hand-written `mermaid` source is drawn only when the plan has no structured tables.
+ var compact = false;
+ function paint() {
+ drawEr(tables.length ? buildErDiagram(tables, compact) : (model.mermaid || ''), tables);
+ }
+ paint();
+
+ var toggle = document.getElementById('erCompactBtn');
+ toggle.addEventListener('click', function () {
+ compact = !compact;
+ toggle.classList.toggle('active', compact);
+ paint();
+ });
+
+ var container = document.getElementById('tablesContainer');
+ container.textContent = '';
+ if (!tables.length) {
+ container.appendChild(el('div', 'empty',
+ model.connectorOnly
+ ? 'This app has no Dataverse tables — it runs on connectors. See the Capabilities tab.'
+ : 'No tables approved yet.'));
+ return;
+ }
+
+ tables.forEach(function (table) {
+ var status = tableStatus(table);
+ var entity = el('div', 'entity ' + status);
+
+ var head = el('div', 'entity-head');
+ head.appendChild(el('span', 'expand-chevron', '\u276f'));
+ head.appendChild(el('span', 'entity-name', table.logicalName || table.name || ''));
+ if (table.displayName) head.appendChild(el('span', 'entity-display', table.displayName));
+ head.appendChild(el('span', 'entity-spacer'));
+ head.appendChild(el('span', 'status-pill status-' + status, status === 'modified' ? 'extended' : status));
+ // A real button, not a clickable div: the row is a disclosure control, and a div cannot
+ // be focused or activated from the keyboard.
+ head.setAttribute('role', 'button');
+ head.setAttribute('tabindex', '0');
+ head.setAttribute('aria-expanded', 'false');
+ var toggle = function () {
+ var open = entity.classList.toggle('open');
+ head.setAttribute('aria-expanded', open ? 'true' : 'false');
+ };
+ head.addEventListener('click', toggle);
+ head.addEventListener('keydown', function (event) {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ // Space scrolls the page by default, which is not what a disclosure control should do.
+ event.preventDefault();
+ toggle();
+ });
+ entity.appendChild(head);
+
+ // Visible without expanding: what the table holds, and why it is being created, reused or
+ // extended. The columns and relationships below are detail; this is the decision.
+ if (table.purpose || table.reason) {
+ var summary = el('div', 'entity-summary');
+ if (table.purpose) summary.appendChild(el('div', 'step-detail', table.purpose));
+ if (table.reason) {
+ var why = el('div', 'cap-why');
+ why.appendChild(el('strong', null, REASON_LABEL[status] + ' '));
+ why.appendChild(document.createTextNode(table.reason));
+ summary.appendChild(why);
+ }
+ entity.appendChild(summary);
+ }
+
+ var body = el('div', 'entity-body');
+
+ var columns = table.columns || [];
+ if (columns.length) {
+ var tableEl = el('table', 'col-table');
+ var thead = el('thead');
+ var headRow = el('tr');
+ ['Column', 'Display', 'Type', 'Key'].forEach(function (label) {
+ headRow.appendChild(el('th', null, label));
+ });
+ thead.appendChild(headRow);
+ tableEl.appendChild(thead);
+
+ var tbody = el('tbody');
+ columns.forEach(function (column) {
+ var normalized = typeof column === 'string' ? { logicalName: column } : column;
+ var row = el('tr');
+ row.appendChild(el('td', 'col-logical', normalized.logicalName || normalized.name || ''));
+ row.appendChild(el('td', null, normalized.displayName || ''));
+ var typeCell = el('td');
+ if (normalized.type) typeCell.appendChild(el('span', 'type-chip', normalized.type));
+ row.appendChild(typeCell);
+ var keyCell = el('td');
+ if (normalized.key === 'PK' || normalized.key === 'FK') {
+ keyCell.appendChild(el('span', 'key-badge key-' + normalized.key, normalized.key));
+ }
+ row.appendChild(keyCell);
+ tbody.appendChild(row);
+ });
+ tableEl.appendChild(tbody);
+ body.appendChild(tableEl);
+ }
+
+ (table.relationships || []).forEach(function (rel) {
+ var line = el('div', 'rel-line');
+ line.appendChild(el('span', 'rel-arrow', '\u2192 '));
+ line.appendChild(document.createTextNode((rel.name || 'related') + ' \u00b7 ' + rel.relatedTable));
+ body.appendChild(line);
+ });
+
+ entity.appendChild(body);
+ container.appendChild(entity);
+ });
+ }
+
+ /**
+ * Capabilities carry a reason, not just a name. "Camera" tells the user nothing; "Camera -
+ * technicians photograph meter damage at the visit" tells them whether the choice was right,
+ * which is the only question an approval gate is really asking.
+ *
+ * Accepts a plain string too, so an older plan that recorded bare names still renders.
+ */
+ function capabilityCards(containerId, entries, kind, emptyText) {
+ var container = document.getElementById(containerId);
+ container.textContent = '';
+ var list = (entries || []).map(function (entry) {
+ return typeof entry === 'string' ? { name: entry } : (entry || {});
+ }).filter(function (entry) { return entryLabel(entry); });
+
+ if (!list.length) {
+ container.appendChild(el('div', 'empty', emptyText));
+ return;
+ }
+
+ list.forEach(function (entry) {
+ var card = el('div', 'cap' + (kind === 'connector' ? ' cap-connector' : ''));
+ var head = el('div', 'cap-head');
+ head.appendChild(permissionIcon(entry.name, kind === 'connector' ? 'plug' : 'device', 'cap-icon'));
+ head.appendChild(el('span', 'cap-name', entry.name));
+ // No "device"/"connector" pill: the section heading above already says which list this is,
+ // and the coloured left border carries it visually. A label that only repeats its heading
+ // is noise on every row. The offline card keeps its pill because the sync *mode* is real
+ // information the heading does not give.
+ card.appendChild(head);
+ card.appendChild(el('div', 'cap-why', entry.reason || 'No rationale recorded.'));
+ container.appendChild(card);
+ });
+ }
+
+ function renderCapabilities() {
+ var arch = sections.architecture || {};
+ capabilityCards('deviceCapabilities', arch.nativeCapabilities, 'device',
+ 'No device capabilities — this app uses data and navigation only.');
+ capabilityCards('connectorList', arch.connectors, 'connector',
+ 'No connectors — this app reads its data from Dataverse directly.');
+
+ var container = document.getElementById('offlineBlock');
+ container.textContent = '';
+ var offline = sections.offline;
+ if (!offline) {
+ container.appendChild(el('div', 'empty', 'Offline has not been decided yet.'));
+ return;
+ }
+
+ var on = offline.enabled === true;
+ var card = el('div', 'cap ' + (on ? 'cap-offline-on' : 'cap-offline-off'));
+ var head = el('div', 'cap-head');
+ head.appendChild(el('span', 'cap-name', on ? 'Offline sync enabled' : 'Online only'));
+ if (offline.mode) head.appendChild(el('span', 'cap-kind', offline.mode));
+ card.appendChild(head);
+ var reasons = paragraphs(offline.rationale);
+ if (reasons.length > 1) {
+ var why = el('div', 'cap-why');
+ why.appendChild(bullets(reasons));
+ card.appendChild(why);
+ } else {
+ card.appendChild(el('div', 'cap-why', reasons[0] || 'No rationale recorded.'));
+ }
+
+ if (on && offline.tables && offline.tables.length) {
+ card.appendChild(el('div', 'step-ref', 'Synced tables: ' + list(offline.tables)));
+ }
+ container.appendChild(card);
+ }
+
+ /**
+ * Link the planner's own markdown. The tabs summarise it; the file has the full per-screen
+ * specs, and it is the artifact `/edit-app` reads on a later run. The href is code-owned
+ * ('../native-app-plan.md'), and the renderer leaves it empty until the file exists.
+ */
+ function planDocLink(containerId, label) {
+ var container = document.getElementById(containerId);
+ if (!container) return;
+ container.textContent = '';
+ if (!summary.planDocHref) return;
+
+ // Markdown is a document, not a web page: a browser either dumps it as plain text or
+ // downloads it. The editor scheme opens it where it is meant to be read. It is offered
+ // first but not alone - a reader without a handler for it would otherwise hit a dead end,
+ // so the plain file link stays beside it.
+ var link = el('a', 'plan-doc');
+ link.setAttribute('href', summary.planDocEditorHref || summary.planDocHref);
+ link.textContent = label;
+ // This page stays open and reloads itself for the whole run, so a link that navigates must
+ // open beside it rather than replace it. The editor link is the exception: a `vscode://`
+ // click hands the file to the editor and leaves this page where it is, and giving it a new
+ // tab would only strand an empty one.
+ if (!summary.planDocEditorHref) {
+ link.setAttribute('target', '_blank');
+ link.setAttribute('rel', 'noopener');
+ }
+
+ var raw = el('a', 'plan-doc-raw', 'native-app-plan.md');
+ raw.setAttribute('href', summary.planDocHref);
+ raw.setAttribute('title', 'Open as plain text in a new tab instead');
+ raw.setAttribute('target', '_blank');
+ raw.setAttribute('rel', 'noopener');
+ container.appendChild(link);
+ container.appendChild(raw);
+ }
+
+ function renderScreens() {
+ approvalBanner('approval-screens', 'screens');
+ planDocLink('screensPlanDoc', 'Full screen specs');
+ var screens = sections.screens || {};
+ var items = screens.list || [];
+ renderMermaid('graphContainer',
+ items.length ? buildScreenGraph(items, screens.navigation) : '',
+ 'The screen graph will appear here after Gate 3.');
+
+ var container = document.getElementById('screensContainer');
+ container.textContent = '';
+ if (!items.length) {
+ container.appendChild(el('div', 'empty', 'No screens planned yet.'));
+ return;
+ }
+ items.forEach(function (screen) {
+ var card = el('div', 'card');
+ card.appendChild(el('div', 'mark'));
+ var body = el('div');
+ body.appendChild(el('div', 'step-title', screen.name));
+ if (screen.purpose) body.appendChild(el('div', 'step-detail', screen.purpose));
+ var meta = [];
+ if (screen.route) meta.push(screen.route);
+ if (screen.data) meta.push(screen.data);
+ if (screen.capabilities && screen.capabilities.length) meta.push(list(screen.capabilities));
+ if (meta.length) body.appendChild(el('div', 'step-ref', meta.join(' \u00b7 ')));
+ card.appendChild(body);
+ if (screen.status) card.appendChild(el('span', 'chip', screen.status));
+ container.appendChild(card);
+ });
+ }
+
+ /**
+ * Outline icons for the trust report, drawn as inline SVG on a 24x24 grid.
+ *
+ * Geometric unicode shapes were tried first and failed the job: at 15px a filled square, a
+ * fisheye and a lozenge are indistinguishable, so the column read as decoration rather than
+ * telling you at a glance which permission a row is about. SVG also renders identically
+ * everywhere, which is the reason the nav icons are pinned to a proven unicode block.
+ *
+ * Every string here is a code-owned constant - no plan data reaches them - which is why they
+ * may be assigned as markup.
+ */
+ var ICON_PATHS = {
+ camera: '<rect x="3.2" y="7" width="17.6" height="12" rx="2.5"/><path d="M9 7l1-2h4l1 2"/><circle cx="12" cy="13" r="3"/>',
+ barcode: '<path d="M4 6v12M7.2 6v12M10.4 6v12M13.6 6v12M16.8 6v12M20 6v12"/>',
+ location: '<path d="M12 21c3.8-4 6-7.2 6-10a6 6 0 1 0-12 0c0 2.8 2.2 6 6 10z"/><circle cx="12" cy="11" r="2.2"/>',
+ gps: '<circle cx="12" cy="12" r="6.6"/><circle cx="12" cy="12" r="2.1"/><path d="M12 2.6v2.8M12 18.6v2.8M2.6 12h2.8M18.6 12h2.8"/>',
+ microphone: '<rect x="9.4" y="3.4" width="5.2" height="10.2" rx="2.6"/><path d="M6.4 11.6a5.6 5.6 0 0 0 11.2 0"/><path d="M12 17.2v3.4"/>',
+ contacts: '<circle cx="12" cy="8.4" r="3.6"/><path d="M5.2 19.8a6.8 6.8 0 0 1 13.6 0"/>',
+ bell: '<path d="M18 16.2v-5.2a6 6 0 1 0-12 0v5.2l-1.6 2.2h15.2z"/><path d="M10 20.2a2 2 0 0 0 4 0"/>',
+ faceid: '<path d="M4 9V6.6A2.6 2.6 0 0 1 6.6 4H9M15 4h2.4A2.6 2.6 0 0 1 20 6.6V9M20 15v2.4a2.6 2.6 0 0 1-2.6 2.6H15M9 20H6.6A2.6 2.6 0 0 1 4 17.4V15"/><path d="M9.6 10.6v1.2M14.4 10.6v1.2"/><path d="M9.6 15a3.6 3.6 0 0 0 4.8 0"/>',
+ photos: '<rect x="3.2" y="7.4" width="13.4" height="11.4" rx="2"/><circle cx="7.4" cy="11.4" r="1.2"/><path d="M3.2 16.2l3.6-3 4.2 3.6"/><path d="M7.4 7.4V6a1.6 1.6 0 0 1 1.6-1.6h10.4A1.6 1.6 0 0 1 21 6v9a1.6 1.6 0 0 1-1.6 1.6h-2.8"/>',
+ cloud: '<path d="M7.2 18.4h10.2a3.6 3.6 0 0 0 .4-7.2 5.6 5.6 0 0 0-10.8-1 4.1 4.1 0 0 0 .2 8.2z"/>',
+ globe: '<circle cx="12" cy="12" r="8"/><path d="M4 12h16"/><ellipse cx="12" cy="12" rx="3.6" ry="8"/>',
+ battery: '<rect x="3" y="8" width="15.4" height="8.8" rx="2.4"/><path d="M21 11.4v2.4"/><rect x="5.4" y="10.4" width="5.2" height="4" rx="1" fill="currentColor" stroke="none"/>',
+ refresh: '<path d="M20 12a8 8 0 1 1-2.4-5.7"/><path d="M20 4.2v4.2h-4.2"/>',
+ shield: '<path d="M12 3.4l7.2 2.8v5.2c0 4.4-3 7.8-7.2 9.2-4.2-1.4-7.2-4.8-7.2-9.2V6.2z"/>',
+ mail: '<rect x="3" y="5.5" width="18" height="13" rx="2.2"/><path d="M3.6 7.2l7.5 5.2a1.6 1.6 0 0 0 1.8 0l7.5-5.2"/>',
+ documents: '<path d="M13.5 3.5H7.6A2.1 2.1 0 0 0 5.5 5.6v12.8a2.1 2.1 0 0 0 2.1 2.1h8.8a2.1 2.1 0 0 0 2.1-2.1V8.5z"/><path d="M13.5 3.5V8.5h5"/><path d="M9 13.2h6M9 16.4h4"/>',
+ database: '<ellipse cx="12" cy="6.4" rx="7" ry="2.8"/><path d="M5 6.4v11.2c0 1.55 3.13 2.8 7 2.8s7-1.25 7-2.8V6.4"/><path d="M5 12c0 1.55 3.13 2.8 7 2.8s7-1.25 7-2.8"/>',
+ chat: '<path d="M20 12.4a7.2 7.2 0 0 1-9.8 6.7L4.6 20.4 6 15A7.2 7.2 0 1 1 20 12.4z"/>',
+ plug: '<path d="M10.2 13.8a3.6 3.6 0 0 0 5.1 0l3-3a3.6 3.6 0 0 0-5.1-5.1l-1.3 1.3"/><path d="M13.8 10.2a3.6 3.6 0 0 0-5.1 0l-3 3a3.6 3.6 0 0 0 5.1 5.1l1.3-1.3"/>',
+ device: '<rect x="6.5" y="2.8" width="11" height="18.4" rx="2.4"/><path d="M10.4 5.6h3.2"/><path d="M11 18.6h2"/>'
+ };
+
+ // Keyed off the capability name because the plan records a human label ("Barcode & QR
+ // scanning"), not an enum. Order matters: "background location" must be tested before the
+ // plain location pattern, or a background-tracking row would claim the on-demand pin icon.
+ var PERMISSION_ICONS = [
+ [/photo librar|gallery|picker/, 'photos'],
+ [/camera|image capture|photo/, 'camera'],
+ [/barcode|scanner|scanning|qr/, 'barcode'],
+ [/background location|continuous gps|\bgps\b/, 'gps'],
+ [/location|geofence|geo/, 'location'],
+ [/microphone|audio|voice/, 'microphone'],
+ [/contact|calendar|address book/, 'contacts'],
+ [/notification|push|alert/, 'bell'],
+ [/biometric|face id|touch id|fingerprint|unlock/, 'faceid'],
+ [/offline|sqlite|sync|upload/, 'cloud'],
+ [/network|connectivity|online|signal/, 'globe'],
+ [/outlook|\bmail\b|email|smtp/, 'mail'],
+ [/sharepoint|document|\blibrary\b|\bfiles?\b/, 'documents'],
+ [/blob|storage account|\bsql\b|dataverse|database|\btables?\b/, 'database'],
+ [/teams|\bchat\b|message/, 'chat'],
+ [/refresh|poll/, 'refresh'],
+ [/battery|power|background/, 'battery']
+ ];
+
+ function permissionIconName(name, fallback) {
+ var value = String(name == null ? '' : name).toLowerCase();
+ for (var i = 0; i < PERMISSION_ICONS.length; i++) {
+ if (PERMISSION_ICONS[i][0].test(value)) return PERMISSION_ICONS[i][1];
+ }
+ // The fallback says what kind of list this is, so an unmatched connector reads as a
+ // connector rather than as a device permission.
+ return ICON_PATHS[fallback] ? fallback : 'shield';
+ }
+
+ function permissionIcon(name, fallback, className) {
+ var span = el('span', 'perm-icon' + (className ? ' ' + className : ''));
+ span.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"'
+ + ' stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
+ + ICON_PATHS[permissionIconName(name, fallback)] + '</svg>';
+ return span;
+ }
+
+ /**
+ * How a permission is acquired, not merely whether it is. These are the seven cross-platform
+ * acquisition patterns plus "never asked for"; which one an app uses is the substance of a
+ * least-privilege claim, because "on demand" and "at startup" grant the same access while
+ * asking for it very differently.
+ *
+ * `tone` drives the badge colour: `good` for patterns that tie access to an explicit user
+ * action or avoid a standing grant entirely, `warn` for ones that take the grant before the
+ * user has context, `info` for the rest.
+ */
+ var PERMISSION_STATUSES = {
+ 'on-demand': { label: 'ON DEMAND', tone: 'good' },
+ 'on-startup': { label: 'AT STARTUP', tone: 'warn' },
+ 'on-first-access': { label: 'ON FIRST ACCESS', tone: 'info' },
+ 'per-operation': { label: 'PER OPERATION', tone: 'good' },
+ 'incremental': { label: 'INCREMENTAL', tone: 'info' },
+ 'system-settings': { label: 'VIA SETTINGS', tone: 'warn' },
+ 'system-mediated': { label: 'SYSTEM-MEDIATED', tone: 'good' },
+ 'not-requested': { label: 'NOT REQUESTED', tone: 'muted' }
+ };
+
+ var STATUS_ALIASES = {
+ ondemand: 'on-demand', requested: 'on-demand', 'on-use': 'on-demand',
+ startup: 'on-startup', 'on-launch': 'on-startup', 'on-load': 'on-startup', onboarding: 'on-startup',
+ 'first-access': 'on-first-access', automatic: 'on-first-access', implicit: 'on-first-access',
+ 'per-use': 'per-operation', 'every-time': 'per-operation', ephemeral: 'per-operation',
+ escalating: 'incremental', 'incremental-escalation': 'incremental',
+ settings: 'system-settings', 'via-settings': 'system-settings',
+ 'system-picker': 'system-mediated', picker: 'system-mediated', mediated: 'system-mediated',
+ 'not-used': 'not-requested', none: 'not-requested', never: 'not-requested'
+ };
+
+ /**
+ * Anything unrecognised resolves to `not-requested` - the claim that promises least - so a
+ * typo or a stale status can never overstate what the app reaches for.
+ */
+ function permissionStatus(raw) {
+ var value = String(raw == null ? '' : raw).toLowerCase().trim().replace(/[\s_]+/g, '-');
+ value = STATUS_ALIASES[value] || value;
+ return PERMISSION_STATUSES[value] ? value : 'not-requested';
+ }
+
+ function boundaryCard(containerId, heading, items) {
+ var container = document.getElementById(containerId);
+ container.textContent = '';
+ container.appendChild(el('h4', null, heading));
+ var entries = (items || []).filter(Boolean);
+ if (!entries.length) {
+ container.appendChild(el('div', 'empty', 'Recorded once the data sources are wired.'));
+ return;
+ }
+ container.appendChild(bullets(entries));
+ }
+
+ function renderTrust() {
+ // The trust report is drafted at Gate 1 and finalised at Step 10, but no gate puts it to the
+ // user, so the default wording would send them to the terminal for a prompt that never comes.
+ approvalBanner('approval-trust', 'trust',
+ 'Draft - written from the approved plan, and finalised once the capabilities are wired');
+ var trust = sections.trust || {};
+
+ var permissions = document.getElementById('permissionList');
+ permissions.textContent = '';
+ var entries = trust.permissions || [];
+ if (!entries.length) {
+ permissions.appendChild(el('div', 'empty',
+ 'Permission behaviour appears here once the capabilities are approved.'));
+ } else {
+ entries.forEach(function (entry) {
+ var name = entryLabel(entry) || 'Capability';
+ var row = el('div', 'perm');
+ row.appendChild(permissionIcon(name));
+ var body = el('div', 'perm-body');
+ var head = el('div', 'perm-head');
+ head.appendChild(el('span', 'perm-name', name));
+ var status = permissionStatus(entry.status);
+ var meta = PERMISSION_STATUSES[status];
+ head.appendChild(el('span', 'perm-badge perm-' + meta.tone, meta.label));
+ body.appendChild(head);
+ body.appendChild(el('div', 'perm-why',
+ entry.detail || entry.reason || 'No access behaviour recorded.'));
+ // Authorization and activation are different events: holding a camera grant is not the
+ // same as the lens being on. Shown separately so a reader can see both.
+ if (entry.activation) {
+ body.appendChild(el('div', 'perm-act', 'Hardware: ' + entry.activation));
+ }
+ row.appendChild(body);
+ permissions.appendChild(row);
+ });
+ }
+
+ boundaryCard('handlesCard', 'What the app handles', trust.handles);
+ boundaryCard('notCollectedCard', 'What the app does not collect', trust.notCollected);
+
+ var battery = document.getElementById('batteryList');
+ battery.textContent = '';
+ var behaviours = trust.battery || [];
+ if (!behaviours.length) {
+ battery.appendChild(el('div', 'empty', 'Background behaviour appears here once the capabilities are approved.'));
+ return;
+ }
+ behaviours.forEach(function (entry) {
+ var name = entryLabel(entry) || 'Behaviour';
+ var row = el('div', 'perm');
+ row.appendChild(permissionIcon(name));
+ var body = el('div', 'perm-body');
+ body.appendChild(el('div', 'perm-name', name));
+ body.appendChild(el('div', 'perm-why', entry.detail || entry.reason || ''));
+ row.appendChild(body);
+ battery.appendChild(row);
+ });
+ }
+
+ function renderDesign() {
+ approvalBanner('approval-design', 'design');
+ var design = sections.design || {};
+ facts('designFacts', [
+ ['Direction', design.direction],
+ ['Heading font', design.headingFont, false, design.headingFont],
+ ['Body font', design.bodyFont, false, design.bodyFont],
+ ['Dark mode', design.darkMode]
+ ]);
+
+ var container = document.getElementById('paletteContainer');
+ container.textContent = '';
+ var palette = design.palette || [];
+ if (!palette.length) {
+ container.appendChild(el('div', 'empty', 'No palette captured yet.'));
+ return;
+ }
+ palette.forEach(function (entry) {
+ var card = el('div', 'swatch-card');
+ var swatch = el('div', 'swatch');
+ // Only accept a literal hex colour; anything else stays unset rather than becoming
+ // an arbitrary CSS value.
+ if (/^#[0-9a-fA-F]{3,8}$/.test(entry.value || '')) swatch.style.backgroundColor = entry.value;
+ card.appendChild(swatch);
+ var meta = el('div', 'swatch-meta');
+ meta.appendChild(el('div', 'swatch-name', entry.name || ''));
+ meta.appendChild(el('div', 'swatch-value', entry.value || ''));
+ card.appendChild(meta);
+ container.appendChild(card);
+ });
+ }
+
+ function renderSteps() {
+ var container = document.getElementById('stepsContainer');
+ container.textContent = '';
+ if (!phases.length) {
+ container.appendChild(el('div', 'empty', 'No steps recorded yet.'));
+ return;
+ }
+ phases.forEach(function (phase) {
+ var card = el('div', 'card ' + (STATUS_CLASS[phase.status] || 'is-pending'));
+ card.appendChild(el('div', 'mark'));
+
+ var body = el('div');
+ body.appendChild(el('div', 'step-title', phase.title));
+ body.appendChild(el('div', 'step-detail', phase.detail));
+ if (phase.note) body.appendChild(el('div', 'step-note', phase.note));
+ if (phase.skillSteps) body.appendChild(el('div', 'step-ref', 'Step ' + phase.skillSteps));
+ card.appendChild(body);
+
+ card.appendChild(el('span', STATUS_CHIP[phase.status] || 'chip', STATUS_LABEL[phase.status] || phase.status));
+ container.appendChild(card);
+ });
+ }
+
+ if (typeof mermaid !== 'undefined') {
+ mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: 'default', er: { fontSize: 16, useMaxWidth: true } });
+ }
+
+ // The renderer stamps UTC. Show the reader's own clock; the UTC text stays if this cannot run.
+ var updatedAt = document.getElementById('updatedAt');
+ var generated = new Date(updatedAt.getAttribute('data-generated') || '');
+ if (!isNaN(generated.getTime())) {
+ updatedAt.textContent = 'Updated ' + generated.toLocaleString(undefined,
+ { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
+ }
+
+ renderPhone();
+ renderOverview();
+ renderRequirements();
+ renderDataModel();
+ renderCapabilities();
+ renderScreens();
+ renderDesign();
+ renderTrust();
+ renderInputBanner();
+
+ document.getElementById('inputBannerClose').addEventListener('click', function () {
+ dismissedPrompt = summary.awaitingInput || '';
+ try { sessionStorage.setItem(STORE_DISMISSED, dismissedPrompt); } catch (e) { /* private mode */ }
+ document.getElementById('inputBanner').hidden = true;
+ });
+ renderSteps();
+
+ /**
+ * The agent rewrites this file in place, and the page is opened over file://, where fetch() is
+ * CORS-blocked - so there is no way to poll for changes and patch the DOM. A reload is the only
+ * mechanism available, which makes *when* it happens the whole design:
+ *
+ * - Restore the open tab and scroll position through sessionStorage, so a reload never throws
+ * the reader back to the top of Overview.
+ * - Pause while the reader is actually using the page. Being yanked mid-sentence is worse than
+ * seeing a slightly stale plan.
+ * - Stop entirely once nothing is in progress.
+ */
+ var STORE_TAB = 'mobile-plan-tab';
+ var STORE_SCROLL = 'mobile-plan-scroll';
+ var RELOAD_MS = 10000;
+ var QUIET_MS = 30000;
+ var lastInteraction = 0;
+
+ function showTab(tab) {
+ var button = document.querySelector('.nav-btn[data-tab="' + tab + '"]');
+ var section = document.getElementById('tab-' + tab);
+ if (!button || !section) return;
+ document.querySelectorAll('.nav-btn').forEach(function (b) { b.classList.remove('active'); });
+ document.querySelectorAll('.section').forEach(function (x) { x.classList.remove('active'); });
+ button.classList.add('active');
+ section.classList.add('active');
+ }
+
+ document.querySelectorAll('.nav-btn').forEach(function (btn) {
+ btn.addEventListener('click', function () {
+ lastInteraction = Date.now();
+ showTab(btn.dataset.tab);
+ try { sessionStorage.setItem(STORE_TAB, btn.dataset.tab); } catch (e) { /* private mode */ }
+ });
+ });
+
+ ['scroll', 'keydown', 'pointerdown'].forEach(function (event) {
+ window.addEventListener(event, function () { lastInteraction = Date.now(); }, { passive: true });
+ });
+
+ window.addEventListener('beforeunload', function () {
+ try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (e) { /* ignore */ }
+ });
+
+ try {
+ var savedTab = sessionStorage.getItem(STORE_TAB);
+ if (savedTab) showTab(savedTab);
+ var savedScroll = Number(sessionStorage.getItem(STORE_SCROLL) || 0);
+ if (savedScroll > 0) window.scrollTo(0, savedScroll);
+ } catch (e) { /* sessionStorage unavailable; first-tab default is fine */ }
+
+ if (!summary.settled) {
+ setInterval(function () {
+ // Never interrupt someone who is reading. The next tick picks it up.
+ if (Date.now() - lastInteraction < QUIET_MS) return;
+ if (document.hidden) return;
+ try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (e) { /* ignore */ }
+ // A plain reload() is not enough. This page is opened over file://, so it carries no
+ // cache headers, and `render-template.js` publishes each rewrite with an atomic rename -
+ // a new inode at the same path. Browsers are free to serve the copy they already have,
+ // which is why the build animation could persist until a hard refresh. Reloading through
+ // a URL that differs every time is the only lever a file:// page has.
+ var fresh = location.href.split('#')[0].split('?')[0] + '?t=' + Date.now();
+ // replace(), not assign(): this fires every few seconds, and each one would otherwise be
+ // a back-button entry the reader has to escape.
+ location.replace(fresh);
+ }, RELOAD_MS);
+ }
+})();
+</script>
+<footer class="ai-footer">AI-generated content may be incorrect</footer>
+</body>
+</html>
diff --git a/plugins/mobile-apps/scripts/app-docs.js b/plugins/mobile-apps/scripts/app-docs.js
new file mode 100644
index 000000000..1408bc676
--- /dev/null
+++ b/plugins/mobile-apps/scripts/app-docs.js
@@ -0,0 +1,537 @@
+#!/usr/bin/env node
+
+/**
+ * app-docs.js — own the generated app's `docs/` folder.
+ *
+ * `/create-mobile-app` runs for 10-20 minutes across ~30 steps, and until now the only
+ * record of what it did was scrollback. This writes a living plan to `<app>/docs/` that the
+ * user can keep open while the run proceeds and come back to afterwards to understand how
+ * their app was put together.
+ *
+ * Modelled on the power-pages `/create-site` HTML plan artifacts (see that plugin's
+ * render scripts and their HTML assets). The template encoder is a physical port
+ * at `lib/render-template.js`; the one behavioural change is that this document is
+ * re-rendered in place on every update rather than written once.
+ *
+ * State lives in `docs/.run-plan.json`; the rendered page is `docs/create-app-plan.html`.
+ * The JSON is the source of truth so a re-render never has to parse HTML back.
+ *
+ * Commands:
+ * init --working-dir <d> --json-file <path> ({"appName", "dataPlatform"}; the skill's route)
+ * init --working-dir <d> --app-name <n> [--data-platform dataverse|connector-only]
+ * step --working-dir <d> --id <phase-id> --status <pending|active|done|skipped|failed> [--note <t>]
+ * set --working-dir <d> --section <name> --json <obj> | --json-file <path> [--state proposed|approved]
+ * phone --working-dir <d> --stage building|screens|qr [--screens-file <path>] [--qr-image <png>] [--qr-url <url>]
+ * show --working-dir <d>
+ */
+
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+
+const { publishAtomic, renderTemplate } = require('./lib/render-template');
+
+/**
+ * The plan's state file is read by one process and rewritten by another as the run advances, so
+ * it is published with a rename: a reader either sees the previous object or the next one, never
+ * a half-written file.
+ */
+function readJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch {
+ // A missing file and a truncated one are the same to a reader: no plan yet. Callers
+ // distinguish the states from which files exist, not from parse failures.
+ return null;
+ }
+}
+
+function writeJsonAtomic(filePath, value) {
+ publishAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`);
+}
+
+const DOCS_DIR = 'docs';
+const STATE_FILE = '.run-plan.json';
+const OUTPUT_FILE = 'create-app-plan.html';
+const TEMPLATE_PATH = path.join(__dirname, '..', 'assets', 'run-plan.html');
+
+const STATUSES = new Set(['pending', 'active', 'done', 'skipped', 'failed']);
+
+/**
+ * Sections the skill records as it learns them. Each is written once by the step that owns
+ * the decision, so the finished document explains not just what was built but what the user
+ * chose and what environment it landed in.
+ *
+ * environment Step 1/4 resolved env, tenant, publisher prefix
+ * requirements Step 2/2b app identity, platforms, aesthetic, confirmed feature brief
+ * architecture Gate 1 data platform, device capabilities, connectors - each with a reason
+ * offline Gate 2 whether offline sync is on, which tables, and why
+ * dataModel Gate 2 tables with reuse/extend/create intent + Mermaid ER source
+ * screens Gates 3-4 navigation pattern, screen graph source, per-screen specs
+ * design Step 6.75 direction, typography, palette
+ * auth Step 7 whether an app registration was supplied or deferred
+ */
+const SECTIONS = new Set([
+ 'environment', 'requirements', 'architecture', 'dataModel', 'screens', 'design', 'auth',
+ 'offline', 'trust',
+]);
+
+/**
+ * User-facing phases, not the skill's ~30 internal step numbers. A plan the user reads should
+ * describe what is happening to their app, so several skill steps collapse into one row here.
+ * `skillSteps` records the mapping so a maintainer can trace a phase back to the SKILL.md.
+ */
+const PHASES = [
+ { id: 'requirements', title: 'Understand what to build', detail: 'Confirm the feature brief', skillSteps: '2, 2b, 2c' },
+ // Planning is approved before anything is scaffolded: the gates decide the data platform,
+ // capabilities and screen set that Steps 5-6 then materialize. This list is the order the
+ // user sees, so it has to match the order the skill runs, or a phase reads as complete
+ // while phases above it are still pending.
+ { id: 'architecture', title: 'Approve the architecture', detail: 'Device capabilities, connectors, and data platform', skillSteps: '3 / Gate 1' },
+ { id: 'data-model', title: 'Design the data model', detail: 'Tables, columns, and relationships', skillSteps: '3 / Gate 2', dataverseOnly: true },
+ { id: 'screen-plan', title: 'Plan the screens', detail: 'Screen graph, navigation, and per-screen specs', skillSteps: '3 / Gates 3-4' },
+ { id: 'scaffold', title: 'Bring the app online', detail: 'Prepare the template and initialize the Power Apps project', skillSteps: '5, 6' },
+ { id: 'design', title: 'Lock the design system', detail: 'Brand tokens, typography, and colour', skillSteps: '6.75, 9b' },
+ { id: 'auth', title: 'Connect sign-in', detail: 'Entra ID app registration and MSAL config', skillSteps: '7' },
+ { id: 'dataverse', title: 'Build the data model', detail: 'Create tables in Dataverse and generate services', skillSteps: '8, 8.5', dataverseOnly: true },
+ { id: 'capabilities', title: 'Wire capabilities', detail: 'Device features and connectors', skillSteps: '9, 10' },
+ { id: 'screens', title: 'Build the screens', detail: 'Navigation, shared code, and each screen', skillSteps: '10b, 10.8, 11' },
+ { id: 'run', title: 'Run it on a device', detail: 'Start Metro and scan the QR code to open the app on your phone', skillSteps: '12, 13' },
+];
+
+function docsDir(projectRoot) {
+ return path.join(path.resolve(projectRoot), DOCS_DIR);
+}
+
+function statePath(projectRoot) {
+ return path.join(docsDir(projectRoot), STATE_FILE);
+}
+
+function outputPath(projectRoot) {
+ return path.join(docsDir(projectRoot), OUTPUT_FILE);
+}
+
+function loadState(projectRoot) {
+ return readJson(statePath(projectRoot));
+}
+
+function initState(projectRoot, { appName, dataPlatform }) {
+ const existing = loadState(projectRoot);
+ // A resumed run must not lose the progress already recorded.
+ if (existing) return existing;
+
+ return {
+ appName: appName || 'Your app',
+ dataPlatform: dataPlatform || 'unknown',
+ startedAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ sections: {},
+ phone: { stage: 'building', screens: [] },
+ phases: PHASES.map((phase) => ({ ...phase, status: 'pending', note: '' })),
+ };
+}
+
+const SECTION_STATES = new Set(['proposed', 'approved']);
+
+const PHONE_STAGES = new Set(['building', 'screens', 'qr']);
+
+/**
+ * The device rail beside the plan. It moves through three stages as the run proceeds:
+ * building an animation, from the first phase until the design is locked
+ * screens a carousel of the plan-time screen previews `/design-system` renders at Step 6.75,
+ * which exist before any TSX is written
+ * qr the Metro QR code, so the last thing the plan shows is how to open the real app
+ */
+function setPhone(state, update) {
+ state.phone = state.phone || { stage: 'building', screens: [] };
+
+ if (update.stage !== undefined) {
+ if (!PHONE_STAGES.has(update.stage)) {
+ throw new Error(`Unknown stage '${update.stage}'. Known: ${[...PHONE_STAGES].join(', ')}`);
+ }
+ state.phone.stage = update.stage;
+ }
+ if (update.screens !== undefined) state.phone.screens = update.screens;
+ if (update.qrImage !== undefined) state.phone.qrImage = update.qrImage;
+ if (update.qrHref !== undefined) state.phone.qrHref = update.qrHref;
+ if (update.qrUrl !== undefined) state.phone.qrUrl = update.qrUrl;
+
+ state.updatedAt = new Date().toISOString();
+ return state;
+}
+
+function setSection(state, name, value, sectionState) {
+ if (!SECTIONS.has(name)) {
+ throw new Error(`Unknown section '${name}'. Known: ${[...SECTIONS].join(', ')}`);
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`Section '${name}' must be a JSON object`);
+ }
+ state.sections = state.sections || {};
+ // Merge so a later step can add to a section without restating what an earlier one wrote
+ // (for example Step 4 confirming the environment Step 1 resolved).
+ state.sections[name] = { ...(state.sections[name] || {}), ...value };
+
+ // A section is written when it is *proposed*, so the user can read the rendered ER or screen
+ // graph while deciding, then flipped to `approved` once they say yes. Kept beside the content
+ // rather than inside it so it cannot collide with a content key.
+ if (sectionState !== undefined) {
+ if (!SECTION_STATES.has(sectionState)) {
+ throw new Error(`Unknown state '${sectionState}'. Known: ${[...SECTION_STATES].join(', ')}`);
+ }
+ state.sectionStates = state.sectionStates || {};
+ state.sectionStates[name] = sectionState;
+ }
+ state.updatedAt = new Date().toISOString();
+ return state;
+}
+
+function applyStep(state, { id, status, note }) {
+ const phase = state.phases.find((entry) => entry.id === id);
+ if (!phase) {
+ throw new Error(`Unknown phase '${id}'. Known: ${PHASES.map((p) => p.id).join(', ')}`);
+ }
+ if (!STATUSES.has(status)) {
+ throw new Error(`Unknown status '${status}'. Known: ${[...STATUSES].join(', ')}`);
+ }
+
+ // A note describes the status it was written with, so it must not outlive it. A gate opens
+ // with "Gate 1 — awaiting your approval" and is later closed by a bare `--status done`;
+ // without this the approved step kept asking for an approval the user had already given.
+ // A repeated status keeps its note, so progress updates like "3 of 12 screens built" survive
+ // an `active` -> `active` refresh.
+ if (note !== undefined) phase.note = String(note);
+ else if (status !== phase.status) phase.note = '';
+ phase.status = status;
+
+ // Only one phase is the live one; marking a new phase active resolves any earlier
+ // still-active phase so a crashed or skipped step cannot leave two spinners running.
+ // The note goes with the status, as above: a gate left open on "awaiting your approval"
+ // would otherwise keep asking for it on a phase the plan now shows as done.
+ if (status === 'active') {
+ for (const other of state.phases) {
+ if (other.id !== id && other.status === 'active') {
+ other.status = 'done';
+ other.note = '';
+ }
+ }
+ }
+ state.updatedAt = new Date().toISOString();
+ return state;
+}
+
+// Sections the user is actually asked to approve. `trust` is deliberately absent: it is written
+// `proposed` at Gate 1 and only finalised at Step 10, but no gate asks the user to answer for it,
+// so including it held the banner up for most of the run with no question to answer.
+const AWAITING_LABEL = {
+ architecture: 'the architecture', dataModel: 'the data model', screens: 'the screen plan',
+ design: 'the design system', offline: 'the offline profile',
+};
+
+// An active phase announces it is blocked through its note. Both spellings are accepted because
+// a gate writes "Gate 2 - awaiting your approval" while an ordinary question reads more naturally
+// as "Waiting for your answers"; matching only the first missed every prompt that is not a gate.
+const AWAITING_NOTE = /\bawaiting\b|\bwaiting for\b/i;
+
+/**
+ * `init` runs at Step 2b, before the data platform is decided, so the top-level value is
+ * "unknown" and nothing updates it. Gate 1 records the real answer on the architecture section,
+ * so read that once it exists and fall back to whatever `init` was given.
+ */
+function dataPlatformLabel(state) {
+ const approved = ((state.sections || {}).architecture || {}).dataPlatform;
+ if (approved) return approved;
+ // The placeholder is internal; the pill is read as a fact about the app.
+ return state.dataPlatform === 'unknown' ? 'not decided yet' : state.dataPlatform;
+}
+
+function failedTitle(state) {
+ const failed = state.phases.find((phase) => phase.status === 'failed');
+ return failed ? failed.title : '';
+}
+
+/**
+ * What the run is blocked on, if anything.
+ *
+ * The active phase's note is the authority, because it is the only signal that distinguishes
+ * "a question is open" from "work is in progress". A `proposed` section does not mean a question
+ * is open: `screens` is proposed at Gate 3 and stays proposed until Step 3.9, so between Gate 3's
+ * approval and Gate 4 the plan showed "Review the screen plan, then answer in your terminal"
+ * while the planner was busy writing specs and nobody had been asked anything.
+ *
+ * A proposed section still raises the banner when the phase says nothing at all, so a gate that
+ * forgets its note is not silent.
+ */
+function awaitingInput(state, active) {
+ const note = (active && active.note) || '';
+ if (AWAITING_NOTE.test(note)) return note;
+ // A note that says something else is a progress report, not a question.
+ if (note.trim()) return '';
+
+ const states = state.sectionStates || {};
+ for (const name of Object.keys(AWAITING_LABEL)) {
+ if (states[name] === 'proposed') return `Review ${AWAITING_LABEL[name]} above, then answer in your terminal`;
+ }
+ return '';
+}
+
+function summarize(state) {
+ const counted = state.phases.filter((phase) => phase.status !== 'skipped');
+ const done = counted.filter((phase) => phase.status === 'done').length;
+ const failed = state.phases.filter((phase) => phase.status === 'failed').length;
+ const skipped = state.phases.filter((phase) => phase.status === 'skipped').length;
+ const active = state.phases.find((phase) => phase.status === 'active');
+ const finished = counted.length > 0 && done === counted.length;
+
+ return {
+ total: counted.length,
+ done,
+ failed,
+ skipped,
+ percent: counted.length === 0 ? 0 : Math.round((done / counted.length) * 100),
+ currentTitle: failed > 0
+ ? `Stopped — ${failedTitle(state) || 'a step failed'}`
+ : (active ? active.title : (finished ? 'Finished' : 'Waiting to start')),
+ // The page reloads itself to pick up each rewrite; `settled` stops that once there is
+ // nothing left to watch, so a finished plan is not reloading forever.
+ settled: finished || failed > 0,
+ // The id, not the title: a resumed run reopens this phase with `step --id`, and that is what
+ // takes the plan out of its stopped state.
+ failedPhase: (state.phases.find((phase) => phase.status === 'failed') || {}).id || '',
+ // What the run is blocked on, if anything. A section held at `proposed` means the plan is
+ // showing the user something to review while the terminal waits on their answer; an active
+ // phase whose note says so covers gates that have no section of their own.
+ awaitingInput: awaitingInput(state, active),
+ narrative: failed > 0
+ ? `${state.appName} stopped during ${failedTitle(state) ? `"${failedTitle(state)}"` : 'a step'}. `
+ + 'The run does not continue past a failed phase; check your terminal for the error.'
+ : (active
+ // Phase titles are imperatives ("Design the data model"), so they follow a label rather
+ // than complete a sentence - "Currently design the data model" is what that produced.
+ ? `In progress: ${active.title}. ${active.detail}.`
+ : (finished
+ ? `${state.appName} is built. Every phase completed.`
+ : `Preparing to build ${state.appName}.`)),
+ };
+}
+
+/**
+ * Short labels for the building animation. Uses the approved architecture once it exists so the
+ * chips describe *this* app, and falls back to the platform's headline capabilities before then.
+ */
+function capabilityLabels(state) {
+ const architecture = (state.sections || {}).architecture || {};
+ const named = [...(architecture.nativeCapabilities || []), ...(architecture.connectors || [])]
+ .map((entry) => (typeof entry === 'string' ? entry : (entry && entry.name)))
+ .filter(Boolean);
+ if (named.length) return named.slice(0, 6);
+ return ['Dataverse', 'Works offline', 'Camera', 'Location', 'Push', 'Biometrics'];
+}
+
+// The full planner output, with the per-screen specs the tabs only summarise. It sits beside
+// the app root and the plan is written into `docs/`, so one level up is the whole path.
+const PLAN_DOC = 'native-app-plan.md';
+
+// The full-size screen mockups `/design-system` renders at the app root. The carousel shows the
+// same blocks in a phone frame; this is the link out to them at full width.
+const SCREEN_PREVIEW = '_plan_preview.html';
+
+// Linked only when really present: each is written partway through the run, so an unconditional
+// link would 404 in the user's browser for the phases before it exists.
+
+/** A file at the app root. The plan is written into `docs/`, so one level up is the whole path. */
+function siblingHref(projectRoot, fileName) {
+ return fs.existsSync(path.join(path.resolve(projectRoot), fileName)) ? `../${fileName}` : '';
+}
+
+/**
+ * An editor deep-link for a local file.
+ *
+ * A page opened over `file://` cannot hand a document to the OS default application - browsers
+ * deliberately refuse, or any site could launch local apps. A registered URL scheme is the one
+ * route that works, and `vscode://file/<path>` is the realistic target here: this plugin is used
+ * from editors that register it. The plain relative link stays beside it for anyone without one.
+ *
+ * Path form per the VS Code URL handler: forward slashes throughout and a leading slash, so a
+ * Windows `C:\app\plan.md` becomes `vscode://file/C:/app/plan.md`.
+ * https://code.visualstudio.com/docs/configure/command-line#_opening-vs-code-with-urls
+ */
+function editorHref(projectRoot, fileName) {
+ const absolute = path.join(path.resolve(projectRoot), fileName);
+ if (!fs.existsSync(absolute)) return '';
+ const forwardSlashed = absolute.replace(/\\/g, '/');
+ const rooted = forwardSlashed.startsWith('/') ? forwardSlashed : `/${forwardSlashed}`;
+ // encodeURI keeps `/` as a separator, which is what this needs, but it also leaves `?` and
+ // `#` alone - and both are legal in a POSIX path. `/tmp/app#1/native-app-plan.md` would parse
+ // as pathname `/tmp/app` with the rest as a fragment, so the editor opens nothing. Escape
+ // those two afterwards; every other character encodeURI already handles. That includes a
+ // literal `%` (`100% Done/` becomes `100%25%20Done/`), and because it is escaped first, the
+ // `%` in the `%3F` and `%23` added here is never escaped a second time.
+ const escaped = encodeURI(rooted).replace(/\?/g, '%3F').replace(/#/g, '%23');
+ return `vscode://file${escaped}`;
+}
+
+function render(projectRoot, state) {
+ const summary = summarize(state);
+ const now = new Date();
+ summary.planDocHref = siblingHref(projectRoot, PLAN_DOC);
+ summary.planDocEditorHref = editorHref(projectRoot, PLAN_DOC);
+ summary.screenPreviewHref = siblingHref(projectRoot, SCREEN_PREVIEW);
+ return renderTemplate({
+ templatePath: TEMPLATE_PATH,
+ outputPath: outputPath(projectRoot),
+ allowOverwrite: true,
+ requiredKeys: ['APP_NAME', 'PHASES', 'SUMMARY', 'SECTIONS', 'SECTION_STATES', 'PHONE'],
+ dataObject: {
+ PLAN_TITLE: 'Mobile app build plan',
+ APP_NAME: state.appName,
+ // Both forms: the page shows the reader's local time and keeps this UTC text as fallback.
+ GENERATED_AT: now.toISOString().replace('T', ' ').slice(0, 16),
+ GENERATED_ISO: now.toISOString(),
+ DATA_PLATFORM: dataPlatformLabel(state),
+ PHASES: state.phases,
+ SUMMARY: summary,
+ SECTIONS: state.sections || {},
+ SECTION_STATES: state.sectionStates || {},
+ PHONE: state.phone || { stage: 'building', screens: [] },
+ CAPABILITIES: capabilityLabels(state),
+ BRAND_ICON: brandIconDataUri(),
+ },
+ });
+}
+
+/**
+ * The brand mark as a `data:` URI.
+ *
+ * Inlined rather than copied beside the page for two reasons. The page is opened over `file://`,
+ * where the origin is opaque, so a CSP `img-src 'self'` would not reliably match a sibling file -
+ * and the plan carries a strict CSP precisely so injected mockup markup cannot fetch or execute
+ * anything. It also makes the plan a single shareable file rather than a folder.
+ */
+function brandIconDataUri() {
+ const source = path.join(__dirname, '..', 'assets', 'power-apps-icon.svg');
+ try {
+ return `data:image/svg+xml;base64,${fs.readFileSync(source).toString('base64')}`;
+ } catch {
+ // A missing mark must not fail a build; the page renders without it.
+ return '';
+ }
+}
+
+function save(projectRoot, state) {
+ fs.mkdirSync(docsDir(projectRoot), { recursive: true });
+ writeJsonAtomic(statePath(projectRoot), state);
+ return render(projectRoot, state);
+}
+
+function parseArgs(argv) {
+ const options = {};
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index];
+ if (argument === '--working-dir') options.workingDir = argv[++index];
+ else if (argument === '--app-name') options.appName = argv[++index];
+ else if (argument === '--data-platform') options.dataPlatform = argv[++index];
+ else if (argument === '--id') options.id = argv[++index];
+ else if (argument === '--status') options.status = argv[++index];
+ else if (argument === '--note') options.note = argv[++index];
+ else if (argument === '--section') options.section = argv[++index];
+ else if (argument === '--json') options.json = argv[++index];
+ else if (argument === '--json-file') options.jsonFile = argv[++index];
+ else if (argument === '--state') options.state = argv[++index];
+ else if (argument === '--stage') options.stage = argv[++index];
+ else if (argument === '--screens-file') options.screensFile = argv[++index];
+ else if (argument === '--qr-image') options.qrImage = argv[++index];
+ else if (argument === '--qr-url') options.qrUrl = argv[++index];
+ else if (!argument.startsWith('--') && !options.command) options.command = argument;
+ else throw new Error(`Unknown argument: ${argument}`);
+ }
+ options.workingDir = options.workingDir || process.cwd();
+ options.command = options.command || 'show';
+ if (!['init', 'step', 'show', 'set', 'phone'].includes(options.command)) {
+ throw new Error(`Unknown command: ${options.command}`);
+ }
+ return options;
+}
+
+if (require.main === module) {
+ try {
+ const options = parseArgs(process.argv.slice(2));
+ const root = path.resolve(options.workingDir);
+
+ if (options.command === 'show') {
+ const state = loadState(root);
+ process.stdout.write(`${JSON.stringify(state ? summarize(state) : { total: 0, done: 0 })}\n`);
+ } else if (options.command === 'init') {
+ // `--app-name` is the display name the user typed, so it may contain a quote, a backtick
+ // or `$(...)`. Passed as a shell argument those break out of the quoting before Node ever
+ // sees them, so the skill hands the name over in a file instead - the same channel every
+ // section write uses. `--app-name`/`--data-platform` stay for callers whose values are
+ // their own, such as tests and tooling.
+ const seed = options.jsonFile
+ ? JSON.parse(fs.readFileSync(options.jsonFile, 'utf8'))
+ : options;
+ const written = save(root, initState(root, seed));
+ process.stdout.write(`${JSON.stringify({ status: 'ok', plan: written })}\n`);
+ } else if (options.command === 'phone') {
+ const state = loadState(root);
+ if (!state) throw new Error('No run plan yet; run `init` first.');
+ const update = { stage: options.stage, qrUrl: options.qrUrl };
+ if (options.screensFile) {
+ update.screens = JSON.parse(fs.readFileSync(options.screensFile, 'utf8'));
+ }
+ if (options.qrImage) {
+ // Inlined as a data URI: the plan is opened over file://, where a relative <img> works
+ // but a moved or deleted PNG leaves a broken image in a document meant to outlive the run.
+ update.qrImage = `data:image/png;base64,${fs.readFileSync(options.qrImage).toString('base64')}`;
+ // A link to the file as well, for opening the code full size in its own tab. A data:
+ // URI cannot be used for that - browsers block top-level navigation to one - so this
+ // has to be a real path. It is relative to `docs/`, and disappears once `.expo/` is
+ // cleaned, at which point the inlined copy above is still there.
+ const qrPath = path.resolve(options.qrImage);
+ const relative = path.relative(docsDir(root), qrPath);
+ // POSIX separators: this becomes an href, not a filesystem path.
+ update.qrHref = relative.split(path.sep).join('/');
+ }
+ const written = save(root, setPhone(state, update));
+ process.stdout.write(`${JSON.stringify({ status: 'ok', stage: state.phone.stage, plan: written })}\n`);
+ } else if (options.command === 'set') {
+ const state = loadState(root);
+ if (!state) throw new Error('No run plan yet; run `init` first.');
+ // A large section (a full screen list, an ER diagram) is awkward and fragile to pass as
+ // one shell argument, so --json-file is the route for anything non-trivial.
+ const raw = options.jsonFile ? fs.readFileSync(options.jsonFile, 'utf8') : options.json;
+ if (!raw) throw new Error('Provide --json <object> or --json-file <path>');
+ const written = save(root, setSection(state, options.section, JSON.parse(raw), options.state));
+ process.stdout.write(`${JSON.stringify({ status: 'ok', section: options.section, plan: written })}\n`);
+ } else {
+ const state = loadState(root);
+ if (!state) throw new Error('No run plan yet; run `init` first.');
+ const written = save(root, applyStep(state, options));
+ process.stdout.write(`${JSON.stringify({ status: 'ok', plan: written, ...summarize(state) })}\n`);
+ }
+ } catch (error) {
+ process.stderr.write(`${error.message}\n`);
+ process.exit(1);
+ }
+}
+
+module.exports = {
+ DOCS_DIR,
+ OUTPUT_FILE,
+ PHASES,
+ STATE_FILE,
+ applyStep,
+ docsDir,
+ initState,
+ loadState,
+ outputPath,
+ render,
+ save,
+ SECTION_STATES,
+ setPhone,
+ setSection,
+ summarize,
+ PHONE_STAGES,
+ SECTIONS,
+};
diff --git a/plugins/mobile-apps/scripts/lib/render-template.js b/plugins/mobile-apps/scripts/lib/render-template.js
new file mode 100644
index 000000000..33e8f6cf5
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/render-template.js
@@ -0,0 +1,161 @@
+'use strict';
+
+/**
+ * render-template.js — render an HTML artifact from a template plus data.
+ *
+ * Ported from the power-pages plugin's `scripts/lib/render-template.js`. Marketplace
+ * installs copy one plugin directory, so cross-plugin `require` is impossible and each
+ * adopting plugin keeps a physical copy - the same rule the shared skills and telemetry
+ * libraries follow. Keep the encoder in step with that sibling.
+ *
+ * **Deliberate deviation from the sibling:** power-pages refuses to overwrite an existing
+ * output file ("the caller must choose a unique name"), because its plans are point-in-time
+ * documents. The mobile run plan is the opposite - one living document re-rendered at every
+ * step boundary so the user can watch progress - so overwrite is opt-in via `allowOverwrite`.
+ * It stays OFF by default so a one-shot artifact cannot silently clobber a previous run.
+ *
+ * Placeholders carry their own encoding context because one source value can legitimately
+ * appear in both HTML and JavaScript:
+ * __NAME__ bare -> HTML text for strings, JSON for structured values
+ * __HTML_NAME__ HTML text
+ * __ATTR_NAME__ HTML attribute
+ * __JSON_NAME__ JSON inside <script> (script-close sequences neutralised)
+ * __RAW_NAME__ trusted, code-owned markup only - never user or CLI data
+ */
+
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const PLACEHOLDER_RE = /__(?:(HTML|ATTR|JSON|RAW)_)?([A-Z][A-Z0-9_]*)__/g;
+
+function escapeHtml(value) {
+ return String(value)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+function escapeHtmlAttribute(value) {
+ return escapeHtml(value)
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;')
+ .replace(/`/g, '&#96;');
+}
+
+function serializeJson(value) {
+ const json = JSON.stringify(value);
+ if (json === undefined) {
+ throw new TypeError('Template values in JSON contexts must be JSON-serializable');
+ }
+ // HTML parses a script end tag before it parses JavaScript or JSON content, so a string
+ // containing "</script>" would end the block early. Neutralise those characters.
+ // U+2028/U+2029 are valid JSON but terminate a JavaScript line, so a JSON blob containing
+ // one would break the <script> it is embedded in. Built via char code because writing the
+ // literal separator into a regex source is itself a syntax hazard.
+ const LINE_SEPARATORS = new RegExp('[\\u2028\\u2029]', 'g');
+ return json
+ .replace(/&/g, '\\u0026')
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(LINE_SEPARATORS, (ch) => (ch === '\u2028' ? '\\u2028' : '\\u2029'));
+}
+
+function renderValue(value, context) {
+ if (context === 'RAW') return String(value);
+ if (context === 'ATTR') return escapeHtmlAttribute(value);
+ if (context === 'JSON') return serializeJson(value);
+ return escapeHtml(value);
+}
+
+function renderTemplate({
+ templatePath,
+ outputPath,
+ dataObject,
+ requiredKeys = [],
+ allowOverwrite = false,
+}) {
+ if (!fs.existsSync(templatePath)) {
+ throw new Error(`Template not found: ${templatePath}`);
+ }
+ if (!dataObject || typeof dataObject !== 'object') {
+ throw new Error('dataObject is required');
+ }
+
+ const missing = requiredKeys.filter((key) => !(key in dataObject));
+ if (missing.length > 0) {
+ throw new Error(`Missing required keys: ${missing.join(', ')}`);
+ }
+
+ const template = fs.readFileSync(templatePath, 'utf8');
+ const data = { ...dataObject, CSP_NONCE: crypto.randomBytes(16).toString('base64') };
+
+ // Collected from the template while it is being filled, never by scanning the output. The
+ // output also holds the substituted data, and plan data can legitimately contain
+ // placeholder-shaped text - React Native's `__DEV__` flag in a note, say. Scanning the output
+ // reported that as an unreplaced placeholder and failed the write, and because the value was
+ // already saved in the plan state, every later write failed with it.
+ const unreplaced = new Set();
+ const result = template.replace(PLACEHOLDER_RE, (placeholder, explicitContext, key) => {
+ if (!(key in data)) {
+ unreplaced.add(placeholder);
+ return placeholder;
+ }
+ const context = explicitContext || (typeof data[key] === 'string' ? 'HTML' : 'JSON');
+ return renderValue(data[key], context);
+ });
+
+ if (unreplaced.size > 0) {
+ throw new Error(`Unreplaced placeholders: ${[...unreplaced].join(', ')}`);
+ }
+
+ if (!allowOverwrite && fs.existsSync(outputPath)) {
+ throw new Error(`Refusing to overwrite ${outputPath}; pass allowOverwrite for living documents.`);
+ }
+
+ return publishAtomic(outputPath, result);
+}
+
+// Windows will not replace a file that another process holds open without delete sharing - a
+// browser reading the plan as it reloads, or an antivirus scanner inspecting the file just
+// written - and reports it as EPERM, EACCES or EBUSY. The hold lasts milliseconds, so retry for
+// up to about a second instead of dropping the update. graceful-fs retries renames on win32 for
+// the same reason: https://github.com/isaacs/node-graceful-fs/blob/main/polyfills.js
+// A POSIX rename replaces an open file atomically and never takes the retry.
+const RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
+const RENAME_ATTEMPTS = 20;
+const RENAME_BACKOFF_MS = 50;
+
+/**
+ * Write a file so a reader never sees it half-written: the content goes to a sibling temporary
+ * file, which is then renamed over the target. A reader opens either the previous file or the
+ * next one.
+ */
+function publishAtomic(filePath, content) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ const temporary = `${filePath}.tmp.${process.pid}`;
+ fs.writeFileSync(temporary, content, 'utf8');
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ fs.renameSync(temporary, filePath);
+ return filePath;
+ } catch (error) {
+ if (!RENAME_RETRY_CODES.has(error.code) || attempt >= RENAME_ATTEMPTS) {
+ fs.rmSync(temporary, { force: true });
+ throw error;
+ }
+ // A synchronous pause: this runs inside a short-lived CLI with nothing else to schedule.
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_BACKOFF_MS);
+ }
+ }
+}
+
+module.exports = {
+ PLACEHOLDER_RE,
+ escapeHtml,
+ escapeHtmlAttribute,
+ publishAtomic,
+ renderTemplate,
+ renderValue,
+ serializeJson,
+};
diff --git a/plugins/mobile-apps/scripts/tests/app-docs.test.js b/plugins/mobile-apps/scripts/tests/app-docs.test.js
new file mode 100644
index 000000000..135a28ad8
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/app-docs.test.js
@@ -0,0 +1,918 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+const {
+ PHASES, PHONE_STAGES, SECTIONS, applyStep, initState, loadState, outputPath, save, setPhone,
+ setSection, summarize,
+} = require('../app-docs');
+
+const scriptPath = path.resolve(__dirname, '..', 'app-docs.js');
+
+function project(name) {
+ return fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));
+}
+
+function seeded(root) {
+ return save(root, initState(root, { appName: 'Field Inspections', dataPlatform: 'dataverse' }));
+}
+
+test('init creates docs/ with a plan that carries its own brand mark', () => {
+ const root = project('docs-init');
+ seeded(root);
+ assert.ok(fs.existsSync(path.join(root, 'docs', 'create-app-plan.html')));
+
+ // The mark is inlined rather than copied beside the page. The plan is opened over file://,
+ // where the origin is opaque, so a CSP `img-src 'self'` would not reliably match a sibling -
+ // and inlining also makes the plan a single shareable file rather than a folder.
+ assert.ok(!fs.existsSync(path.join(root, 'docs', 'power-apps-icon.svg')),
+ 'no sibling asset should be written');
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /<img class="logo" id="brandLogo" src="data:image\/svg\+xml;base64,/);
+});
+
+test('a resumed run keeps the progress already recorded', () => {
+ const root = project('docs-resume');
+ seeded(root);
+ save(root, applyStep(loadState(root), { id: 'requirements', status: 'done' }));
+
+ // init must be safe to call again; it must not reset completed phases.
+ const again = initState(root, { appName: 'Field Inspections' });
+ assert.equal(again.phases.find((p) => p.id === 'requirements').status, 'done');
+});
+
+test('only one phase can be in progress at a time', () => {
+ const root = project('docs-active');
+ const state = initState(root, { appName: 'App' });
+ applyStep(state, { id: 'requirements', status: 'active' });
+ applyStep(state, { id: 'architecture', status: 'active' });
+
+ assert.equal(state.phases.find((p) => p.id === 'requirements').status, 'done');
+ assert.equal(state.phases.filter((p) => p.status === 'active').length, 1);
+});
+
+test('skipped phases leave the percentage honest', () => {
+ const root = project('docs-skip');
+ const state = initState(root, { appName: 'App' });
+ // A connector-only app skips both Dataverse phases; they must not count as outstanding
+ // work or the plan would never reach 100%.
+ applyStep(state, { id: 'data-model', status: 'skipped' });
+ applyStep(state, { id: 'dataverse', status: 'skipped' });
+ for (const phase of state.phases.filter((p) => p.status !== 'skipped')) {
+ applyStep(state, { id: phase.id, status: 'done' });
+ }
+
+ const summary = summarize(state);
+ assert.equal(summary.total, PHASES.length - 2);
+ assert.equal(summary.percent, 100);
+ assert.equal(summary.skipped, 2);
+ assert.equal(summary.settled, true, 'a finished plan must stop reloading itself');
+});
+
+test('a failed phase settles the page and is counted', () => {
+ const root = project('docs-fail');
+ const state = initState(root, { appName: 'App' });
+ applyStep(state, { id: 'scaffold', status: 'failed' });
+ const summary = summarize(state);
+ assert.equal(summary.failed, 1);
+ assert.equal(summary.settled, true);
+});
+
+test('a note does not outlive the status it was written with', () => {
+ const root = project('docs-note');
+ const state = initState(root, { appName: 'App' });
+
+ // How the gate protocol actually runs: open with an "awaiting" note, close with a bare
+ // --status done. The note used to stick, so an approved gate kept asking for approval.
+ applyStep(state, { id: 'architecture', status: 'active', note: 'Gate 1 — awaiting your approval' });
+ applyStep(state, { id: 'architecture', status: 'done' });
+ const architecture = state.phases.find((phase) => phase.id === 'architecture');
+ assert.equal(architecture.status, 'done');
+ assert.equal(architecture.note, '', 'the awaiting-approval note must not survive approval');
+
+ // An explicit note on the closing call is kept.
+ applyStep(state, { id: 'data-model', status: 'active', note: 'Gate 2 — awaiting your approval' });
+ applyStep(state, { id: 'data-model', status: 'done', note: 'Gate 2 — 6 tables approved' });
+ assert.equal(state.phases.find((p) => p.id === 'data-model').note, 'Gate 2 — 6 tables approved');
+
+ // A repeated status keeps its note, so progress updates survive a refresh.
+ applyStep(state, { id: 'screens', status: 'active', note: '3 of 12 screens built' });
+ applyStep(state, { id: 'screens', status: 'active' });
+ assert.equal(state.phases.find((p) => p.id === 'screens').note, '3 of 12 screens built');
+
+ // Opening the next phase auto-closes the live one, and the note goes with that status too.
+ // A gate left open on its awaiting note otherwise kept asking for approval on a phase the plan
+ // already showed as done.
+ applyStep(state, { id: 'screen-plan', status: 'active', note: 'Gate 3 — awaiting your approval' });
+ applyStep(state, { id: 'scaffold', status: 'active' });
+ const screenPlan = state.phases.find((p) => p.id === 'screen-plan');
+ assert.equal(screenPlan.status, 'done');
+ assert.equal(screenPlan.note, '', 'an auto-closed phase must not keep its awaiting note');
+});
+
+test('the skill closes every gate with a fresh note', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const body = skill.slice(skill.indexOf('\n### Step '));
+ // Clearing on status change means a gate closed without a note simply goes blank, which is
+ // correct but less useful than saying it was approved.
+ for (const gate of ['architecture', 'data-model', 'screen-plan']) {
+ const closes = [...body.matchAll(new RegExp(`step --id ${gate} --status done([^\n]*)`, 'g'))];
+ assert.ok(closes.length > 0, `${gate} must be closed somewhere`);
+ for (const [, rest] of closes) {
+ assert.match(rest, /--note /, `${gate} is closed without a note`);
+ }
+ }
+});
+
+test('the trust report is written as soon as the gate it depends on closes', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const body = skill.slice(skill.indexOf('\n### Step '));
+
+ // The tab told the user it would fill after Gate 1 while the skill only wrote it at Step 10,
+ // so it sat empty for most of the run. A proposed pass lands with Gate 1 and Step 10 finalises.
+ const writes = [...body.matchAll(/set --section trust[^\n]*--state (proposed|approved)/g)].map((m) => m[1]);
+ assert.deepEqual(writes, ['proposed', 'approved'],
+ 'trust must be proposed at the gate that settles capabilities, then approved once wired');
+
+ const proposedAt = body.indexOf('set --section trust');
+ const gate1Close = body.indexOf('step --id architecture --status done');
+ assert.ok(gate1Close !== -1 && proposedAt > gate1Close, 'the first pass belongs with the Gate 1 batch');
+});
+
+test('sections merge so a later step can add to an earlier one', () => {
+ const root = project('docs-sections');
+ const state = initState(root, { appName: 'App' });
+ setSection(state, 'environment', { displayName: 'Contoso Dev' });
+ setSection(state, 'environment', { publisherPrefix: 'cr8142a' });
+
+ assert.deepEqual(state.sections.environment, {
+ displayName: 'Contoso Dev', publisherPrefix: 'cr8142a',
+ });
+});
+
+test('unknown phases, statuses and sections are rejected by name', () => {
+ const state = initState(project('docs-reject'), { appName: 'App' });
+ assert.throws(() => applyStep(state, { id: 'nope', status: 'done' }), /Unknown phase 'nope'/);
+ assert.throws(() => applyStep(state, { id: 'requirements', status: 'nope' }), /Unknown status 'nope'/);
+ assert.throws(() => setSection(state, 'nope', {}), /Unknown section 'nope'/);
+ assert.throws(() => setSection(state, 'environment', ['a']), /must be a JSON object/);
+ assert.ok(SECTIONS.has('dataModel'));
+});
+
+test('captured choices reach the rendered page', () => {
+ const root = project('docs-render');
+ const state = initState(root, { appName: 'Field Inspections', dataPlatform: 'dataverse' });
+ setSection(state, 'environment', { displayName: 'Contoso Dev', publisherPrefix: 'cr8142a' });
+ setSection(state, 'dataModel', { mermaid: 'erDiagram\n A ||--o{ B : has', tables: [{ name: 'cr8142a_inspection', action: 'create' }] });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ for (const value of ['Contoso Dev', 'cr8142a_inspection', 'erDiagram', 'tab-datamodel']) {
+ assert.ok(html.includes(value), `missing ${value}`);
+ }
+ assert.doesNotMatch(html, /__[A-Z][A-Z0-9_]*__/, 'no placeholder may survive rendering');
+});
+
+test('a hostile note cannot break out of the JSON script block', () => {
+ const root = project('docs-xss');
+ const state = initState(root, { appName: 'App' });
+ applyStep(state, { id: 'requirements', status: 'done', note: '</script><img src=x onerror=alert(1)>' });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.doesNotMatch(html, /<\/script><img/);
+ assert.match(html, /u003c\/script/);
+});
+
+test('the CLI refuses a step before init and reports the reason', () => {
+ const root = project('docs-cli');
+ const early = spawnSync(process.execPath, [scriptPath, '--working-dir', root, 'step', '--id', 'requirements', '--status', 'done'], { encoding: 'utf8' });
+ assert.equal(early.status, 1);
+ assert.match(early.stderr, /run `init` first/);
+
+ spawnSync(process.execPath, [scriptPath, '--working-dir', root, '--app-name', 'App', 'init'], { encoding: 'utf8' });
+ const set = spawnSync(process.execPath, [scriptPath, '--working-dir', root, 'set', '--section', 'auth', '--json', '{"status":"skipped"}'], { encoding: 'utf8' });
+ assert.equal(set.status, 0, set.stderr);
+ assert.equal(JSON.parse(set.stdout.trim()).section, 'auth');
+});
+
+test('the data model tab carries the power-pages colour vocabulary', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // Same three-state legend power-pages uses, so a reader moving between the two plugins
+ // reads the same colours: new = accent blue, extended = warn orange, reused = pass green.
+ for (const marker of [
+ 'status-new', 'status-modified', 'status-reused',
+ 'key-PK', 'key-FK', 'type-chip', 'col-table',
+ 'er-legend', 'erCompactBtn',
+ ]) {
+ assert.ok(template.includes(marker), `missing ${marker}`);
+ }
+ assert.match(template, /#0078d4/);
+ assert.match(template, /#ca5010/);
+ assert.match(template, /#107c10/);
+});
+
+test('erDiagram source strips characters that would abort the mermaid parse', () => {
+ const root = project('docs-er');
+ const state = initState(root, { appName: 'App' });
+ // "Yes/No" is a real Dataverse type name and its slash is invalid in an ATTRIBUTE_WORD;
+ // one bad column must not blank the whole diagram.
+ setSection(state, 'dataModel', {
+ tables: [{
+ logicalName: 'cr8142a_inspection',
+ status: 'new',
+ columns: [{ logicalName: 'cr8142a_flag', type: 'Yes/No', key: 'PK' }],
+ }],
+ });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ // The raw value still appears in the data block; the sanitiser runs at diagram build time.
+ assert.match(html, /Yes\/No/);
+ assert.match(html, /replace\(\/\[\^A-Za-z0-9_\]\/g, '_'\)/);
+});
+
+test('table action verbs from the plan map onto the three visual states', () => {
+ const root = project('docs-alias');
+ const state = initState(root, { appName: 'App' });
+ setSection(state, 'dataModel', {
+ tables: [
+ { logicalName: 'a', action: 'create' },
+ { logicalName: 'b', action: 'reuse' },
+ { logicalName: 'c', action: 'extend' },
+ ],
+ });
+ save(root, state);
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ // native-app-plan.md says create/reuse/extend; the page says new/reused/modified.
+ assert.match(html, /STATUS_ALIAS/);
+ assert.match(html, /create: 'new'/);
+ assert.match(html, /extend: 'modified'/);
+ assert.match(html, /reuse: 'reused'/);
+});
+
+test('nav icons come from blocks that actually render', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ const icons = [...template.matchAll(/<span class="nav-icon">&#(\d+);<\/span>/g)].map((m) => Number(m[1]));
+ assert.ok(icons.length >= 6, 'every tab needs an icon');
+
+ // U+2610 BALLOT BOX and U+2637 TRIGRAM FOR EARTH shipped once and rendered as a missing
+ // glyph in common Segoe UI stacks. Keep icons inside Geometric Shapes (U+25A0-U+25FF) or
+ // the Dingbats/Misc-Symbols characters already proven in the power-pages plans.
+ const PROVEN = new Set([0x2600, 0x270E]);
+ for (const code of icons) {
+ const geometric = code >= 0x25a0 && code <= 0x25ff;
+ assert.ok(geometric || PROVEN.has(code), `U+${code.toString(16).toUpperCase()} is not a proven glyph`);
+ }
+ assert.equal(icons.includes(0x2610), false, 'BALLOT BOX does not render');
+ assert.equal(icons.includes(0x2637), false, 'TRIGRAM FOR EARTH does not render');
+});
+
+test('an ordinary question raises the banner, not just an approval gate', () => {
+ const root = project('docs-waiting');
+ const state = initState(root, { appName: 'App' });
+
+ // The first real prompt is the Step 2b setup questions, long before any section is proposed.
+ // Matching only /awaiting/ missed it, so the page looked busy while the run was blocked.
+ applyStep(state, { id: 'requirements', status: 'active', note: 'Waiting for your answers to the setup questions' });
+ assert.equal(summarize(state).awaitingInput, 'Waiting for your answers to the setup questions');
+
+ // A gate's own wording still works.
+ applyStep(state, { id: 'architecture', status: 'active', note: 'Gate 1 — awaiting your approval' });
+ assert.match(summarize(state).awaitingInput, /awaiting your approval/);
+
+ // Answering clears it, because the note does not outlive its status.
+ applyStep(state, { id: 'architecture', status: 'done' });
+ assert.equal(summarize(state).awaitingInput, '');
+
+ // An active phase that is merely working must not raise it.
+ applyStep(state, { id: 'screens', status: 'active', note: '3 of 12 screens built' });
+ assert.equal(summarize(state).awaitingInput, '');
+});
+
+test('the skill flags the run as blocked before its first question', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const open = skill.match(/step --id requirements --status active([^\n]*)/);
+ assert.ok(open, 'the requirements phase must be opened');
+ assert.match(open[1], /--note "Waiting for your answers/,
+ 'the first prompt must raise the waiting banner');
+});
+
+test('a failed run says so, because that is the last thing the page will ever show', () => {
+ const root = project('docs-failed');
+ const state = initState(root, { appName: 'Field App' });
+ applyStep(state, { id: 'scaffold', status: 'failed' });
+
+ // A failure sets `settled`, which stops the self-refresh - so whatever the page says at that
+ // moment is what the user is left looking at. It used to read "Waiting to start" and
+ // "Preparing to build", hiding the failure exactly when refreshes stopped.
+ const summary = summarize(state);
+ assert.equal(summary.failed, 1);
+ assert.equal(summary.settled, true);
+ assert.match(summary.currentTitle, /^Stopped — /);
+ assert.match(summary.currentTitle, /Bring the app online/);
+ assert.match(summary.narrative, /stopped during "Bring the app online"\./);
+ assert.doesNotMatch(summary.narrative, /Preparing to build/);
+});
+
+test('the narrative names the live phase without bending its title into a sentence', () => {
+ const root = project('docs-narrative');
+ const state = applyStep(initState(root, { appName: 'App' }), { id: 'data-model', status: 'active' });
+ assert.equal(summarize(state).narrative, 'In progress: Design the data model. Tables, columns, and relationships.');
+});
+
+test('the topbar shows the approved data platform, not the placeholder init was given', () => {
+ const root = project('docs-platform');
+ let state = initState(root, { appName: 'App', dataPlatform: 'unknown' });
+ // `init` runs at Step 2b, before the platform is chosen, and nothing updates the top-level
+ // value - so the pill read "Data: unknown" for the whole run. Before Gate 1 it says so in words.
+ save(root, state);
+ let html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /Data: not decided yet/);
+
+ state = setSection(state, 'architecture', { dataPlatform: 'Dataverse + connectors' }, 'approved');
+ save(root, state);
+ html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /Data: Dataverse \+ connectors/);
+ assert.doesNotMatch(html, /Data: unknown/);
+});
+
+test('a section nobody is asked to approve does not raise the waiting banner', () => {
+ const root = project('docs-trust-banner');
+ let state = initState(root, { appName: 'App' });
+ // `trust` is written `proposed` at Gate 1 and only finalised at Step 10, but no gate asks the
+ // user to answer for it. Treating it as a gate held the banner up for most of the run.
+ state = setSection(state, 'trust', { permissions: [] }, 'proposed');
+ assert.equal(summarize(state).awaitingInput, '');
+
+ // A section that really is a gate still raises it.
+ state = setSection(state, 'dataModel', { tables: [] }, 'proposed');
+ assert.match(summarize(state).awaitingInput, /Review the data model/);
+});
+
+test('the skill marks a phase failed before it stops', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+
+ // `failed` settles the page, which stops the self-refresh. Listing the value without ever
+ // issuing it left the last phase `active`, so a terminal STOP produced a plan that reloaded
+ // forever reporting work in progress on a run that had ended.
+ assert.match(skill, /step --id <phase> --status failed/);
+ assert.match(skill, /Mark the phase `failed` before you stop/);
+
+ // And nothing may switch the protocol off: the plan is how an abandoned run explains itself.
+ assert.doesNotMatch(skill, /Skip the protocol entirely when/);
+ assert.match(skill, /No argument switches this protocol off/);
+});
+
+test('an editor link survives a path containing ?, # or %', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'docs-url-#1 100% Done-'));
+ fs.writeFileSync(path.join(root, 'native-app-plan.md'), '# plan\n');
+ save(root, initState(root, { appName: 'App' }));
+
+ const summary = JSON.parse(
+ fs.readFileSync(outputPath(root), 'utf8')
+ .match(/<script id="summaryData" type="application\/json">([\s\S]*?)<\/script>/)[1],
+ );
+
+ // encodeURI keeps `/` as a separator but leaves `?` and `#` alone, and both are legal in a
+ // POSIX path. Unescaped, `/tmp/app#1/plan.md` parses as pathname `/tmp/app` with the rest a
+ // fragment, so the editor opens nothing.
+ assert.doesNotMatch(summary.planDocEditorHref, /#(?!23)/, 'a # must be percent-encoded');
+ const pathname = new URL(summary.planDocEditorHref).pathname;
+ assert.match(pathname, /native-app-plan\.md$/, 'the whole path must survive into the URL');
+
+ // A literal `%` starts an escape, so `100% Done` would be an invalid sequence if it were left
+ // alone. Decoding must give back exactly the path on disk, in the forward-slashed, rooted form
+ // the VS Code URL handler expects.
+ assert.match(summary.planDocEditorHref, /100%25%20Done/, 'a literal % must be percent-encoded');
+ const onDisk = path.join(root, 'native-app-plan.md').replace(/\\/g, '/');
+ assert.equal(decodeURIComponent(pathname), onDisk.startsWith('/') ? onDisk : `/${onDisk}`);
+});
+
+test('the skill records a skipped design step instead of leaving it open', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const design = skill.slice(skill.indexOf('### Step 6.75'), skill.indexOf('### Step 7 '));
+
+ // `--no-design` returns before the `done` call. Opening the phase on that branch left it
+ // active through auth and most of Step 8, until opening the next phase auto-closed it as
+ // done - reporting a design system that was never built.
+ const skipAt = design.indexOf('step --id design --status skipped');
+ const openAt = design.indexOf('step --id design --status active');
+ assert.ok(skipAt !== -1, 'the skip branch must record itself');
+ assert.ok(openAt !== -1, 'the real path must open the phase');
+ assert.ok(skipAt < openAt, 'the skip branch comes first, so the phase is only opened when used');
+});
+
+test('nested skills are handed the orchestration flag, not just told about it', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ // `/design-system` and its style picker gate every browser opener on this variable. Asserting
+ // it was set without passing it made those guards dead code: the nested skill saw a standalone
+ // run and opened tabs over the build plan anyway.
+ const invocation = skill.slice(skill.indexOf('Invoke skill: /design-system'));
+ const block = invocation.slice(0, invocation.indexOf('```'));
+ assert.match(block, /Environment:\s*\n\s*CODE_APPS_NATIVE_ORCHESTRATING=1/,
+ 'the invocation must pass the flag the guards read');
+});
+
+test('a section still proposed between two gates does not read as a question', () => {
+ const root = project('docs-between-gates');
+ const state = initState(root, { appName: 'Field Readings' });
+
+ // `screens` is proposed at Gate 3 and stays proposed until Step 3.9, because one section
+ // covers both gates. Between Gate 3's approval and Gate 4 the plan therefore showed "Review
+ // the screen plan, then answer in your terminal" while the planner was busy writing specs and
+ // nobody had been asked anything.
+ setSection(state, 'screens', { list: [] }, 'proposed');
+
+ applyStep(state, { id: 'screen-plan', status: 'active', note: 'Gate 3 — awaiting your approval' });
+ assert.match(summarize(state).awaitingInput, /awaiting your approval/);
+
+ applyStep(state, { id: 'screen-plan', status: 'active', note: 'Gate 3 approved — writing per-screen specs' });
+ assert.equal(summarize(state).awaitingInput, '', 'a progress note means the run is working, not waiting');
+
+ applyStep(state, { id: 'screen-plan', status: 'active', note: 'Gate 4 — awaiting your approval of the screen specs' });
+ assert.match(summarize(state).awaitingInput, /Gate 4/);
+});
+
+test('a gate that forgets its note is still not silent', () => {
+ const root = project('docs-gate-no-note');
+ const state = initState(root, { appName: 'App' });
+ // The note is the authority, but a proposed section with nothing said about it is the safety
+ // net - otherwise a skill that proposes a section and omits the note blocks in silence.
+ setSection(state, 'dataModel', { tables: [] }, 'proposed');
+ applyStep(state, { id: 'data-model', status: 'active' });
+ assert.match(summarize(state).awaitingInput, /Review the data model/);
+});
+
+test('every step that blocks on the user says so in the plan', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const lines = skill.split('\n');
+
+ const headings = [];
+ lines.forEach((line, i) => {
+ const m = /^### Step ([0-9a-z.]+) /.exec(line);
+ if (m) headings.push([i, m[1]]);
+ });
+ const stepAt = (i) => {
+ let name = '(preamble)';
+ for (const [pos, id] of headings) {
+ if (pos <= i) name = id; else break;
+ }
+ return name;
+ };
+
+ // Derived from the skill, not listed here. A hard-coded list is what let Step 7 ship asking
+ // for an app registration with no phase open at all - the plan showed nothing in progress
+ // while the run was blocked, and the test passed because 7 was not on the list.
+ const asks = new Set();
+ const raises = new Set();
+ lines.forEach((line, i) => {
+ if (line.includes('AskUserQuestion')) asks.add(stepAt(i));
+ if (/--status active[^\n]*--note "[^"]*(?:[Ww]aiting for|awaiting)/.test(line)) raises.add(stepAt(i));
+ });
+ asks.delete('(preamble)');
+
+ // Step 2 asks before `init` runs at Step 2b, so there is no plan to raise a banner on.
+ const EXEMPT = new Set(['2']);
+ const silent = [...asks].filter((step) => !raises.has(step) && !EXEMPT.has(step)).sort();
+ assert.deepEqual(silent, [], 'these steps ask the user but never raise the waiting banner');
+
+ // The exemption must stay true: the plan is created at 2b.
+ assert.match(skill, /### Step 2b[\s\S]{0,1200}init --json-file/, 'the plan is created at Step 2b');
+
+ // Step 3 counts as raising through one generic call, so every gate must be in the table that
+ // call is applied to. Step 3 opened on "Planning — approval gates ahead" with no gate ever
+ // raising its own note, which also suppressed the proposed-section fallback for all four.
+ for (const [gate, id] of [['1', 'architecture'], ['2', 'data-model'], ['3', 'screen-plan'], ['4', 'screen-plan']]) {
+ assert.match(skill, new RegExp(`^\\| ${gate} - [^|]+\\| \`${id}\` \\|`, 'm'), `Gate ${gate} has no row in the gate table`);
+ }
+
+ // Step 13's menu is not a gate. The build has finished and the plan has settled, so
+ // re-opening a phase there would restart the reload loop.
+ assert.ok(!raises.has('13'), 'the closing menu must not re-open a phase');
+ assert.match(skill, /Do \*\*not\*\* re-open the `run` phase/);
+});
+
+test('each phase opens before its first step does any work', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const lines = skill.split('\n');
+
+ // With no phase open the plan reads "Waiting to start". Step 8 opened `dataverse` only after
+ // its tables were created, and `screens` opened at the end of the first wave in Step 11 - so
+ // the two longest stretches of the run showed nothing in progress.
+ // Step 2 runs before the plan exists, so requirements opens at 2b. The gate phases are opened
+ // by Step 3's gate table, which the blocking-step test checks.
+ const OPENED_AT = { requirements: '2b' };
+ for (const phase of PHASES) {
+ if (/Gate/.test(phase.skillSteps)) continue;
+ const step = OPENED_AT[phase.id] || phase.skillSteps.split(/[,\s]+/)[0];
+ const start = lines.findIndex((line) => line.startsWith(`### Step ${step} `));
+ assert.ok(start >= 0, `no heading for Step ${step}`);
+ const next = lines.findIndex((line, i) => i > start && line.startsWith('### '));
+ const opens = lines.findIndex((line, i) => i > start && i < next
+ && line.includes(`step --id ${phase.id} --status active`));
+ assert.ok(opens > 0, `'${phase.id}' is not opened in Step ${step}, where its work starts`);
+
+ // Nothing runs before it: every code block above the call is the plan's own, or the JSON it
+ // is given.
+ let fence = null;
+ for (let i = start; i < opens; i += 1) {
+ const marker = /^\s*```(\w*)/.exec(lines[i]);
+ if (marker) { fence = fence === null ? marker[1] : null; continue; }
+ if (fence === null || fence === 'json' || !lines[i].trim()) continue;
+ assert.match(lines[i], /app-docs\.js|^\s*#/,
+ `Step ${step} runs \`${lines[i].trim().slice(0, 60)}\` before opening '${phase.id}'`);
+ }
+ }
+});
+
+test('a stopped plan names the failed phase by id, and a resume reopens it', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'app-docs-resume-'));
+ let state = initState(root, { appName: 'Resume', dataPlatform: 'dataverse' });
+ state = applyStep(state, { id: 'scaffold', status: 'failed', note: 'npm install failed' });
+ assert.equal(summarize(state).failedPhase, 'scaffold');
+ assert.equal(summarize(state).settled, true);
+
+ // Reopening is what takes the plan out of its stopped state, so it reloads again.
+ state = applyStep(state, { id: 'scaffold', status: 'active' });
+ assert.equal(summarize(state).failedPhase, '');
+ assert.equal(summarize(state).settled, false);
+
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const resume = skill.slice(skill.indexOf('### Step 0 '), skill.indexOf('### Step 1 '));
+ assert.match(resume, /step --id <failedPhase> --status active/);
+ assert.match(resume, /docs\/create-app-plan\.html/, 'a resume skips 2b, so it must reopen the plan');
+});
+
+test('every waiting note is taken down by the step that set it', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const calls = [...skill.matchAll(/step --id ([a-z-]+) --status ([a-z]+)([^\n]*)/g)].map((m) => ({
+ phase: m[1],
+ status: m[2],
+ waiting: /--note "[^"]*(?:[Ww]aiting for|awaiting)/.test(m[3]),
+ }));
+
+ // A note does not outlive its status, so any later call on the same phase clears it. What
+ // must not happen is a phase left waiting with nothing after it.
+ for (let i = 0; i < calls.length; i += 1) {
+ if (!calls[i].waiting) continue;
+ const cleared = calls.slice(i + 1).some((c) => c.phase === calls[i].phase);
+ assert.ok(cleared, `'${calls[i].phase}' is left waiting with no later call to take it down`);
+ }
+});
+
+test('phase order matches the order the skill actually runs them', () => {
+ const order = PHASES.map((phase) => phase.id);
+ const at = (id) => order.indexOf(id);
+
+ // The gates run at Step 3 and the scaffold group at Steps 5-6. These two lists drifted
+ // apart once before, and because the test agreed with the stale list it stayed green while
+ // a completed "Bring the app online" rendered above three still-pending gates.
+ assert.ok(at('architecture') < at('scaffold'), 'the gates are answered before anything is built');
+ assert.ok(at('data-model') < at('scaffold'));
+ assert.ok(at('screen-plan') < at('scaffold'));
+
+ assert.ok(at('requirements') < at('scaffold'), 'dependencies must land before the app can run');
+ assert.ok(at('scaffold') < at('design'), 'the project exists before a design system is written into it');
+ assert.ok(at('screen-plan') < at('design'), 'design is locked after the screens are planned');
+ assert.ok(at('design') < at('screens'), 'screens are built against a settled design');
+ assert.ok(at('dataverse') < at('screens'), 'generated services exist before screens use them');
+ assert.equal(order[order.length - 1], 'run', 'running on a device is the last thing that happens');
+});
+
+test('phase order is derived from where the skill actually runs each step', () => {
+ // The pairwise assertions above encode intent, but they were written by hand and once
+ // agreed with a stale PHASES list while contradicting the skill. This check takes the
+ // order from SKILL.md itself, using the `step --id` transition calls rather than the
+ // `skillSteps` metadata: the metadata records which steps a phase spans, and those spans
+ // legitimately interleave (setup's background install is collected long after discovery
+ // starts), whereas the transition calls are the moments the plan actually advances.
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+
+ // The "Build documentation protocol" preamble shows a worked example of the gate calls.
+ // It is documentation, not execution, so start scanning at the first real step heading.
+ const firstStep = skill.indexOf('\n### Step ');
+ assert.ok(firstStep > 0, 'SKILL.md must have step headings');
+ const body = skill.slice(firstStep);
+
+ // e.g. `node "$DOCS" --working-dir "<working_dir>" step --id data-model --status done`
+ // `skipped` is excluded: the connector-only branch at Step 3.9 marks both Dataverse
+ // phases skipped up front, which is a statement about applicability rather than a point
+ // in the execution order.
+ const calls = [...body.matchAll(/step --id ([a-z-]+) --status (active|done)\b/g)];
+ assert.ok(calls.length > 0, 'the skill must drive the plan with `step --id` calls');
+
+ const firstTransition = new Map();
+ for (const call of calls) {
+ if (!firstTransition.has(call[1])) firstTransition.set(call[1], call.index);
+ }
+
+ let previous = -1;
+ let previousPhase = null;
+ for (const phase of PHASES) {
+ const at = firstTransition.get(phase.id);
+ assert.ok(
+ at !== undefined,
+ `phase '${phase.id}' is never opened or closed by the skill, so it would sit pending ` +
+ 'in the plan while later phases complete',
+ );
+ assert.ok(
+ at >= previous,
+ `phase '${phase.id}' first transitions before phase '${previousPhase}' — PHASES and ` +
+ 'the skill have drifted apart',
+ );
+ previous = at;
+ previousPhase = phase.id;
+ }
+});
+
+test('every phase the skill opens is also closed', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const body = skill.slice(skill.indexOf('\n### Step '));
+ const calls = [...body.matchAll(/step --id ([a-z-]+) --status (active|done|skipped)/g)];
+
+ for (const phase of PHASES) {
+ const statuses = calls.filter((c) => c[1] === phase.id).map((c) => c[2]);
+ // `active` auto-closes the previous phase, so a phase that is only ever opened still
+ // resolves - but only if a later phase opens. `run` is last, so it must close itself.
+ assert.ok(
+ statuses.includes('done') || statuses.includes('skipped'),
+ `phase '${phase.id}' is never marked done or skipped`,
+ );
+ }
+});
+
+test('each phase points at skill steps that still exist', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ const headings = new Set(
+ [...skill.matchAll(/^### Step ([0-9a-z.]+)/gm)].map((m) => m[1].replace(/\.$/, '')),
+ );
+
+ for (const phase of PHASES) {
+ // "2e-2h" is a range and "3 / Gate 1" names a gate; take the leading step of each token.
+ const referenced = phase.skillSteps
+ .split(/[,/]/)
+ .map((part) => part.trim().split(/[-\s]/)[0])
+ .filter((part) => /^[0-9]/.test(part));
+ for (const step of referenced) {
+ assert.ok(headings.has(step), `phase '${phase.id}' cites Step ${step}, which no longer exists`);
+ }
+ }
+});
+
+test('no relationship value can produce an unrenderable diagram', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // Power Pages guarantees its ER always draws by emitting one of a few hardcoded tokens and
+ // never a value from the plan. A single unrecognised token aborts the parse, so passthrough
+ // of any kind reintroduces "renders as source".
+ assert.doesNotMatch(template, /MERMAID_CARDINALITY/, 'no regex passthrough of plan values');
+ assert.doesNotMatch(template, /return raw;/, 'no plan value may reach the mermaid source');
+ for (const token of ["'\\|\\|--\\|\\|'", "'\\}o--o\\{'", "'\\}o--\\|\\|'", "'\\|\\|--o\\{'"]) {
+ assert.match(template, new RegExp(`return ${token};`), `missing literal ${token}`);
+ }
+ // Labels end early on a newline, quote or angle bracket, and wrap the box when over-long.
+ assert.match(template, /\.replace\(\/\[\\r\\n\]\+\/g, ' '\)/);
+ assert.match(template, /\.slice\(0, 40\)/);
+ // Both directions of a relationship are one edge.
+ assert.match(template, /\[from, to\]\.sort\(\)\.join\('\|'\)/);
+ // The diagram itself carries the status colours, not just the legend.
+ assert.match(template, /function colorErDiagram/);
+ assert.match(template, /#0078d4/);
+});
+
+test('build steps sits second, and nav order matches document order', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ const nav = [...template.matchAll(/<button class="nav-btn[^"]*" data-tab="([a-z]+)"/g)].map((m) => m[1]);
+ const sections = [...template.matchAll(/<div class="section[^"]*" id="tab-([a-z]+)"/g)].map((m) => m[1]);
+
+ // Progress is what a user watching a running build wants first, so it leads after Overview.
+ assert.deepEqual(nav.slice(0, 2), ['overview', 'steps']);
+ // A tab whose section sits elsewhere in the document still works, but reading the file then
+ // no longer matches reading the page.
+ assert.deepEqual(nav, sections, 'nav order must match section order');
+ assert.equal(nav.length, 8,
+ 'overview, steps, requirements, data model, capabilities, screens, design, trust');
+});
+
+test('capabilities, connectors and offline each carry a rationale', () => {
+ const root = project('docs-caps');
+ const state = initState(root, { appName: 'App', dataPlatform: 'Connectors only' });
+ setSection(state, 'architecture', {
+ dataPlatform: 'Connectors only',
+ nativeCapabilities: [{ name: 'Camera', reason: 'Photograph meter damage on site' }],
+ connectors: [{ name: 'SharePoint', reason: 'Site documents already live there' }],
+ });
+ setSection(state, 'offline', {
+ enabled: true, mode: 'related rows', tables: ['Site visit'],
+ rationale: 'Readings are taken where there is no signal',
+ });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ // A bare capability name cannot be approved or rejected; the reason is the decision.
+ for (const value of ['Photograph meter damage on site', 'Site documents already live there',
+ 'Readings are taken where there is no signal', 'tab-capabilities']) {
+ assert.ok(html.includes(value), `missing ${value}`);
+ }
+ // The kind is already the section heading and the border colour; repeating it per row is noise.
+ assert.doesNotMatch(html, /cap-kind-connector', ?\n? *kind === 'connector'/);
+ assert.match(html, /already says which list this is/);
+ // The offline pill stays: sync mode is information the heading does not carry.
+ assert.match(html, /offline\.mode\) head\.appendChild/);
+});
+
+test('a connector-only app is a first-class shape, not an empty data model', () => {
+ const root = project('docs-connector-only');
+ const state = initState(root, { appName: 'App', dataPlatform: 'Connectors only' });
+ setSection(state, 'dataModel', { connectorOnly: true, tables: [] });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /runs on connectors/);
+ // Offline is still a decision worth recording even with no tables to sync.
+ assert.match(html, /Offline has not been decided yet/);
+});
+
+test('a plan that recorded bare capability names still renders', () => {
+ const root = project('docs-caps-legacy');
+ const state = initState(root, { appName: 'App' });
+ setSection(state, 'architecture', { nativeCapabilities: ['Camera'], connectors: ['SharePoint'] });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /typeof entry === 'string'/, 'string entries must be tolerated');
+ assert.match(html, /No rationale recorded/);
+});
+
+test('every table shows why it is created, reused or extended, without expanding', () => {
+ const root = project('docs-table-why');
+ const state = initState(root, { appName: 'App', dataPlatform: 'Dataverse' });
+ setSection(state, 'dataModel', {
+ tables: [
+ { logicalName: 'new_sitevisit', status: 'new', reason: 'Nothing models a timed visit' },
+ { logicalName: 'account', status: 'reused', reason: 'Sites are maintained there already' },
+ { logicalName: 'contact', status: 'extend', reason: 'Only one column is missing' },
+ ],
+ });
+ save(root, state);
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ // Each sourcing decision is labelled by its own verb, so the reason reads as an answer.
+ assert.match(html, /new: 'Why create it:'/);
+ assert.match(html, /reused: 'Why reuse it:'/);
+ assert.match(html, /modified: 'Why extend it:'/);
+ // The reason sits in entity-summary, outside entity-body, which is display:none until opened.
+ // Rationale behind a click is rationale nobody reads before approving.
+ assert.match(html, /el\('div', 'entity-summary'\)/);
+ assert.match(html, /entity-summary\{[^}]*display:grid/);
+ assert.match(html, /\.entity-body\{display:none/);
+ const summaryIndex = html.indexOf("summary.appendChild(why)");
+ const bodyIndex = html.indexOf("var body = el('div', 'entity-body')");
+ assert.ok(summaryIndex > 0 && summaryIndex < bodyIndex, 'the reason must render before the collapsed body');
+});
+
+test('the plan never reloads over a reader, and never resets their place', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // It reloaded unconditionally every 5s, which flickered and threw the reader back to Overview.
+ assert.doesNotMatch(template, /\}, 5000\);/, 'no blind 5s reload');
+ assert.doesNotMatch(template, /location\.hash = active/, 'hash juggling lost scroll position');
+
+ // Open tab and scroll survive the reload.
+ assert.match(template, /sessionStorage\.setItem\(STORE_TAB/);
+ assert.match(template, /sessionStorage\.setItem\(STORE_SCROLL/);
+ assert.match(template, /window\.scrollTo\(0, savedScroll\)/);
+
+ // Reading, typing, scrolling or clicking defers the reload; a hidden tab never reloads.
+ assert.match(template, /Date\.now\(\) - lastInteraction < QUIET_MS/);
+ assert.match(template, /if \(document\.hidden\) return;/);
+ // And it stops altogether once the build is finished.
+ assert.match(template, /if \(!summary\.settled\)/);
+
+ // A bare reload() may serve the cached copy: a file:// page has no cache headers, and each
+ // rewrite lands as a new inode at the same path via an atomic rename. The animation could
+ // therefore persist until a hard refresh, so the refresh goes through a changing URL.
+ assert.doesNotMatch(template, /(?<!\/\/.*)\blocation\.reload\(\)/,
+ 'a plain reload can be served from the file:// cache');
+ assert.match(template, /location\.replace\(fresh\)/);
+ assert.match(template, /\?t=' \+ Date\.now\(\)/, 'the reload URL must differ every time');
+ // replace(), not assign(): this fires every few seconds and must not fill the back button.
+ assert.doesNotMatch(template, /location\.assign\(/);
+
+ // sessionStorage throws in some privacy modes; the page must still render.
+ const guarded = template.match(/sessionStorage\.(get|set)Item/g) || [];
+ const tries = template.match(/try \{/g) || [];
+ assert.ok(tries.length >= 4, `every sessionStorage access needs a guard (${guarded.length} accesses)`);
+});
+
+test('every renderer the page defines is also invoked', () => {
+ // A refactor once sliced out the invocation block, leaving the page defining seven renderers
+ // and calling none. Grepping the source still passed, because the functions and their data
+ // were all present - the page just rendered nothing.
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // Only zero-argument definitions are top-level renderers; helpers like renderMermaid(id, src)
+ // are called with arguments from inside them.
+ const defined = [...template.matchAll(/function (render[A-Za-z]+)\(([^)]*)\)/g)]
+ .filter((m) => m[2].trim() === '')
+ .map((m) => m[1]);
+ const called = [...template.matchAll(/^ {2}(render[A-Za-z]+)\(\);/gm)].map((m) => m[1]);
+
+ assert.ok(defined.length >= 8, `expected the full renderer set, found ${defined.length}`);
+ for (const fn of defined) {
+ assert.ok(called.includes(fn), `${fn} is defined but never called`);
+ }
+ for (const fn of called) {
+ assert.ok(defined.includes(fn), `${fn} is called but never defined`);
+ }
+});
+
+test('the device rail moves through building, screens and QR', () => {
+ const root = project('docs-rail');
+ const state = initState(root, { appName: 'App' });
+ assert.equal(state.phone.stage, 'building', 'a new plan starts on the animation');
+
+ setPhone(state, { stage: 'screens', screens: [{ name: 'Home', html: '<div>Home</div>' }] });
+ assert.equal(state.phone.stage, 'screens');
+
+ setPhone(state, { stage: 'qr', qrUrl: 'exp://192.168.1.4:8081' });
+ assert.equal(state.phone.qrUrl, 'exp://192.168.1.4:8081');
+ // Screens survive the move to QR, so the stage is a view choice rather than a data reset.
+ assert.equal(state.phone.screens.length, 1);
+
+ assert.throws(() => setPhone(state, { stage: 'nope' }), /Unknown stage 'nope'/);
+ assert.ok(PHONE_STAGES.has('building') && PHONE_STAGES.has('screens') && PHONE_STAGES.has('qr'));
+});
+
+test('progress is reported as steps, never as a percentage', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // Phases differ wildly in duration, so a percentage reads as a time estimate the plan cannot
+ // make. The bar still fills proportionally - that is a count of steps, not a claim about time.
+ // Only style.width may use percent - that is a fill ratio, not a statement to the reader.
+ const textUses = [...template.matchAll(/textContent = [^;]*percent[^;]*;/g)].map((m) => m[0]);
+ assert.deepEqual(textUses, [], 'no visible label may be a percentage');
+ assert.doesNotMatch(template, /percent \+ '% complete'/);
+ assert.match(template, /summary\.done \+ ' of ' \+ summary\.total/);
+ assert.match(template, /'Step ' \+ Math\.min\(summary\.done \+ 1, summary\.total\)/);
+});
+
+test('both diagrams render through the same path', () => {
+ const template = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
+ );
+ // The ER called mermaid.render() while the screen graph relied on startOnLoad. Turning
+ // startOnLoad off to control the ER silently left the screen graph as raw source.
+ assert.match(template, /function renderMermaid\(/);
+ assert.doesNotMatch(template, /function diagram\(/, 'the startOnLoad-dependent helper is gone');
+ assert.match(template, /renderMermaid\('erContainer'/);
+ assert.match(template, /renderMermaid\('graphContainer'/);
+ assert.match(template, /startOnLoad: false/);
+ // Exactly one place calls mermaid.render, so the two can never diverge again.
+ // One call site, so the two diagrams cannot drift apart again. Strip comments first: the
+ // explanation above names mermaid.render(), and matching prose would count it twice.
+ const code = template.split('\n').filter((line) => !/^\s*(\*|\/\/)/.test(line)).join('\n');
+ assert.equal((code.match(/mermaid\.render\(/g) || []).length, 1);
+});
diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js
index 3d0461394..445b4e9a3 100644
--- a/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js
+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-planning-order.test.js
@@ -187,7 +187,10 @@ test('preview preferences keep deferred Gate 4 markdown-only', () => {
assert.match(brandedPreview, /\/design-system` owns rendering of `_plan_preview\.html`/);
const skippedDesign = section(design, '#### Branch B', '**Preview timing:**');
assert.match(skippedDesign, /\*\*Render `_plan_preview\.html`\*\*/);
- assert.match(skippedDesign, /Print the preview path; open in browser only if `<visual_companion> = yes`/);
+ // The build plan shows these screens in its phone frame and links out to the file, so the
+ // create run no longer opens a browser tab for them.
+ assert.match(skippedDesign, /Do not open it in a browser/);
+ assert.doesNotMatch(skippedDesign, /xdg-open|Start-Process/);
});
test('offline completion summary reflects the bundled native host runtime', () => {
@@ -367,3 +370,55 @@ test('offline profile opt-in runs after Dataverse materialization and before nat
/missing, malformed, or contains no Dataverse[\s\S]*BLOCKED: Dataverse materialization/i,
);
});
+
+test('the screen preview has exactly one filename, everywhere it is named', () => {
+ const designSystem = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'design-system', 'SKILL.md'), 'utf8',
+ );
+
+ // `/create-mobile-app` extracts its carousel from this file and the build plan links it, so a
+ // path that only some branches write leaves both empty. The default no-brand path wrote
+ // `_design_preview.html`, and when that was corrected the message it prints was missed - the
+ // user was handed a link to a file the run no longer creates.
+ assert.doesNotMatch(designSystem, /_design_preview/,
+ 'the screen preview is _plan_preview.html on every path');
+
+ // The path written and the path printed must be the same one.
+ const written = [...designSystem.matchAll(/Write to `<working_dir>\/([a-z_.]+)`/g)].map((m) => m[1]);
+ const printed = [...designSystem.matchAll(/preview ready at file:\/\/<working_dir>\/([a-z_.]+)/g)].map((m) => m[1]);
+ assert.ok(written.length > 0 && printed.length > 0, 'the preview must be written and announced');
+ assert.deepEqual([...new Set(written.concat(printed))], ['_plan_preview.html']);
+});
+
+test('no instruction promises a browser window during an orchestrated run', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ // Step 6.75 guarantees no window opens, but the Step 2b preference definition still told the
+ // agent that `visual_companion = yes` opens one - a directive it could legitimately follow.
+ const preference = skill.split('\n').find((l) => l.startsWith('- `<visual_companion> = yes`'));
+ assert.ok(preference, 'the preference must be defined');
+ assert.doesNotMatch(preference, /automatically open/);
+ assert.match(preference, /Nothing is opened in a browser during a create run/);
+
+ // The guarantee is about windows that appear on their own. Step 11.4 offers a preview the
+ // user picks, defaulting to skip, and `/preview-screens` honours this same flag - so the
+ // definition must not claim the flag is irrelevant inside a create run.
+ assert.doesNotMatch(preference, /governs only a later standalone/);
+ assert.match(preference, /Step 11\.4 offer/);
+
+ // And every opener in the nested skill says which runs it applies to - including the style
+ // picker's refinement loops, which "re-open" the preview after each hybrid, mix or reject.
+ // These are instructions an agent follows, not a runtime branch, so one unqualified "open
+ // browser" is enough to put a tab over the build plan. Lines about the plan page itself
+ // ("its build plan open in the browser") describe it rather than open anything.
+ const OPENER = /\bre-?open\b|\bopens? (the )?browser\b|\bopen (it )?in (the )?browser\b|\bopen the browser\b/i;
+ for (const file of ['SKILL.md', path.join('references', 'vibe', 'style-picker.md')]) {
+ const text = fs.readFileSync(path.resolve(__dirname, '..', '..', 'skills', 'design-system', file), 'utf8');
+ const openers = text.split('\n').filter((l) => OPENER.test(l) && !/build plan open/.test(l));
+ assert.ok(openers.length > 0, `${file}: the opener pattern no longer finds anything`);
+ for (const line of openers) {
+ assert.match(line, /standalone runs only/, `${file}: ungated opener: ${line.trim().slice(0, 70)}`);
+ }
+ }
+});
diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
index 0eac2c57f..cd2e47e08 100644
--- a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
@@ -241,6 +241,39 @@ test('scaffold changed-file validation separates preparation and generator owner
assert.match(shared, /Do not suppress a protected-path finding/);
});
+test('no user-authored value reaches the shell as a command argument', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+
+ // A `'` ends a single-quoted argument; a `"`, a backtick or `$(...)` breaks out of a
+ // double-quoted one and runs before Node sees it. Both forms have shipped here: first the
+ // inline `--json` writes, then `init --app-name "<displayName>"`. Checking only one quoting
+ // style is what let the second through, so this checks the values instead.
+ const USER_AUTHORED = [
+ '<displayName>', '<confirmed brief>', '<aesthetic>', '<industry>',
+ '<feature>', '<direction>', '<slug>',
+ ];
+
+ const offenders = [];
+ for (const [line] of skill.matchAll(/^node "\$\{PLUGIN_ROOT\}\/scripts\/app-docs\.js"[^\n]*/gm)) {
+ for (const token of USER_AUTHORED) {
+ if (line.includes(token)) offenders.push(`${token} in: ${line.slice(60, 140)}`);
+ }
+ }
+ assert.deepEqual(offenders, [], 'these values are the user\'s own and must travel in a file');
+
+ // Every section that carries user text goes through --json-file, including the plan's own
+ // creation, which takes the display name.
+ for (const section of ['requirements', 'design', 'architecture', 'dataModel', 'screens', 'trust', 'offline', 'auth']) {
+ assert.doesNotMatch(skill, new RegExp(`set --section ${section} --json '`), `${section} must use --json-file`);
+ }
+ assert.match(skill, /init --json-file/);
+
+ // And the rule is stated, so the next value added follows it.
+ assert.match(skill, /Use `--json-file` for anything the user wrote/);
+});
+
test('authentication discovers and checks registrations before writing a client ID', () => {
const auth = skill.slice(
skill.indexOf('### Step 7 — Auth config'),
diff --git a/plugins/mobile-apps/scripts/tests/render-template.test.js b/plugins/mobile-apps/scripts/tests/render-template.test.js
new file mode 100644
index 000000000..922d06dad
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/render-template.test.js
@@ -0,0 +1,97 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+const { applyStep, initState, outputPath, save, setSection } = require('../app-docs');
+const { publishAtomic, renderTemplate } = require('../lib/render-template');
+
+function tempDir(prefix) {
+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+}
+
+test('plan text shaped like a placeholder is rendered, not rejected', () => {
+ // `__DEV__` is React Native's development flag, so a note or a trust entry can name it. The
+ // renderer used to scan its own output, find it, and fail the write - and because the value
+ // was already saved, every later write failed with it.
+ const root = tempDir('render-dev-');
+ let state = initState(root, { appName: 'Placeholder', dataPlatform: 'dataverse' });
+ state = applyStep(state, { id: 'requirements', status: 'active', note: 'Debug logging only under __DEV__' });
+ state = setSection(state, 'trust', {
+ battery: [{ name: 'Verbose logging', detail: 'Enabled only when __DEV__ is true.' }],
+ });
+
+ assert.doesNotThrow(() => save(root, state));
+ // And the next write, with the value still in the state, succeeds too.
+ state = applyStep(state, { id: 'requirements', status: 'done' });
+ assert.doesNotThrow(() => save(root, state));
+
+ const html = fs.readFileSync(outputPath(root), 'utf8');
+ assert.match(html, /Enabled only when __DEV__ is true\./);
+});
+
+test('a placeholder the template names but the data lacks still fails the render', () => {
+ const dir = tempDir('render-missing-');
+ const templatePath = path.join(dir, 'template.html');
+ fs.writeFileSync(templatePath, '<p>__HTML_PRESENT__ __HTML_ABSENT__</p>');
+
+ assert.throws(
+ () => renderTemplate({
+ templatePath, outputPath: path.join(dir, 'out.html'), dataObject: { PRESENT: 'yes' },
+ }),
+ /Unreplaced placeholders: __HTML_ABSENT__/,
+ );
+ assert.ok(!fs.existsSync(path.join(dir, 'out.html')), 'nothing is published on failure');
+});
+
+/** Replace `fs.renameSync` for one test, failing the first `failures` calls with `code`. */
+function failingRename(t, code, failures) {
+ const real = fs.renameSync;
+ let calls = 0;
+ t.mock.method(fs, 'renameSync', (from, to) => {
+ calls += 1;
+ if (calls <= failures) {
+ const error = new Error(`${code}: simulated`);
+ error.code = code;
+ throw error;
+ }
+ return real(from, to);
+ });
+ return () => calls;
+}
+
+test('a rename refused by a momentary Windows lock is retried, not dropped', (t) => {
+ const dir = tempDir('render-lock-');
+ const target = path.join(dir, 'plan.html');
+ fs.writeFileSync(target, 'previous');
+ const calls = failingRename(t, 'EPERM', 2);
+
+ publishAtomic(target, 'next');
+
+ assert.equal(fs.readFileSync(target, 'utf8'), 'next');
+ assert.equal(calls(), 3);
+ assert.deepEqual(fs.readdirSync(dir), ['plan.html'], 'no temporary file is left behind');
+});
+
+test('a rename that keeps failing gives up, leaving the previous file and no temporary', (t) => {
+ const dir = tempDir('render-held-');
+ const target = path.join(dir, 'plan.html');
+ fs.writeFileSync(target, 'previous');
+ failingRename(t, 'EBUSY', Infinity);
+
+ assert.throws(() => publishAtomic(target, 'next'), /EBUSY/);
+ assert.equal(fs.readFileSync(target, 'utf8'), 'previous');
+ assert.deepEqual(fs.readdirSync(dir), ['plan.html']);
+});
+
+test('a rename error that is not a lock is not retried', (t) => {
+ const dir = tempDir('render-other-');
+ const calls = failingRename(t, 'EXDEV', 1);
+
+ assert.throws(() => publishAtomic(path.join(dir, 'plan.html'), 'next'), /EXDEV/);
+ assert.equal(calls(), 1);
+ assert.deepEqual(fs.readdirSync(dir), []);
+});
diff --git a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js b/plugins/mobile-apps/scripts/tests/run-plan-page.test.js
new file mode 100644
index 000000000..2f65fa5c3
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/run-plan-page.test.js
@@ -0,0 +1,1159 @@
+'use strict';
+
+/**
+ * Executes the generated run-plan page's script against a real plan, in a minimal DOM stub.
+ *
+ * The other run-plan tests read `assets/run-plan.html` as text and assert on its source. That
+ * catches a missing function but not a page that throws halfway through rendering, and it cannot
+ * tell the difference between a renderer that draws a diagram and one that reads a field nothing
+ * ever writes. Both of those shipped: `renderScreens` read a `screens.mermaid` string that no
+ * producer set, so the screen graph silently showed its empty state, and `showSource` was defined
+ * twice with the second copy silently overriding the first.
+ *
+ * Running the script is the only check that distinguishes those from a working page.
+ */
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+const { applyStep, initState, outputPath, save, setPhone, setSection } = require('../app-docs');
+
+/** Mermaid's crow's-foot tokens. Anything else aborts the parse and blanks the diagram. */
+const ER_CARDINALITY_TOKENS = ['||--||', '}o--o{', '}o--||', '||--o{'];
+
+function node(id, attributes = {}) {
+ return {
+ id,
+ tagName: 'DIV',
+ children: [],
+ style: {},
+ dataset: {},
+ classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } },
+ _text: '',
+ _html: '',
+ get textContent() { return this._text; },
+ set textContent(value) { this._text = String(value); },
+ get innerHTML() { return this._html; },
+ set innerHTML(value) { this._html = String(value); },
+ appendChild(child) { this.children.push(child); return child; },
+ append(...kids) { this.children.push(...kids); },
+ setAttribute() {},
+ getAttribute(name) { return Object.hasOwn(attributes, name) ? attributes[name] : null; },
+ removeAttribute() {},
+ addEventListener() {}, removeEventListener() {}, remove() {},
+ querySelector() { return null; }, querySelectorAll() { return []; },
+ closest() { return null; }, focus() {}, scrollIntoView() {},
+ getBoundingClientRect() { return { top: 0, left: 0, width: 0, height: 0 }; },
+ };
+}
+
+/**
+ * Run every executable `<script>` in the page and report what it did.
+ *
+ * `<script type="application/json" id="...">` blocks are the page's own state, read back with
+ * `JSON.parse(getElementById(id).textContent)`. They are data, so they are registered as element
+ * content rather than executed - running them as JavaScript is a syntax error on the first colon.
+ *
+ * `session` seeds sessionStorage, which is what survives the page's own reloads.
+ */
+async function runPage(htmlPath, { session = {} } = {}) {
+ const html = fs.readFileSync(htmlPath, 'utf8');
+
+ // The attributes of every element the static markup gives an id, so a script reading one back
+ // (`getAttribute('data-generated')`) sees what the renderer wrote. Values are attribute-encoded
+ // by the renderer and none of the ones read here contain an entity, so no decoding is needed.
+ const staticAttributes = new Map();
+ for (const [, tag] of html.matchAll(/<[a-z][a-z0-9]*\s([^>]*\bid="[^"]+"[^>]*)>/g)) {
+ const attributes = Object.fromEntries(
+ [...tag.matchAll(/([a-zA-Z-]+)="([^"]*)"/g)].map(([, name, value]) => [name, value]),
+ );
+ staticAttributes.set(attributes.id, attributes);
+ }
+
+ const data = new Map();
+ const scripts = [];
+ for (const [, attributes, body] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)) {
+ const id = (attributes.match(/id\s*=\s*["']([^"']+)["']/) || [])[1];
+ if (/type\s*=\s*["']application\/json["']/.test(attributes) && id) data.set(id, body);
+ else if (body.trim()) scripts.push(body);
+ }
+
+ const elements = new Map();
+ const document = {
+ getElementById(id) {
+ if (!elements.has(id)) {
+ const created = node(id, staticAttributes.get(id));
+ if (data.has(id)) created.textContent = data.get(id);
+ elements.set(id, created);
+ }
+ return elements.get(id);
+ },
+ createElement(tag) {
+ const created = node(`<${tag}>`);
+ created.tagName = tag.toUpperCase();
+ if (created.tagName === 'TEMPLATE') {
+ // Enough of a <template> for the sanitizer to run end to end. The stub cannot parse
+ // HTML, so `content` is an empty inert fragment: this proves the page drives the
+ // sanitizer without throwing. What the sanitizer strips is asserted against the
+ // source separately, in the cleaning test below.
+ created.content = { ...node('#fragment'), querySelectorAll: () => [] };
+ }
+ return created;
+ },
+ createTextNode(text) { const created = node('#text'); created.textContent = String(text); return created; },
+ querySelector() { return null; },
+ querySelectorAll() { return []; },
+ addEventListener() {}, removeEventListener() {},
+ body: node('body'), documentElement: node('html'),
+ hidden: false, readyState: 'complete',
+ };
+
+ const diagrams = [];
+ const renders = [];
+ const errors = [];
+ const sandbox = {
+ document,
+ window: {
+ document,
+ addEventListener() {}, removeEventListener() {},
+ location: { hash: '', reload() {} },
+ matchMedia() { return { matches: false, addEventListener() {} }; },
+ setTimeout() { return 0; }, setInterval() { return 0; }, scrollTo() {}, scrollY: 0,
+ },
+ location: { hash: '', reload() {} },
+ sessionStorage: {
+ store: new Map(Object.entries(session)),
+ getItem(key) { return this.store.has(key) ? this.store.get(key) : null; },
+ setItem(key, value) { this.store.set(key, String(value)); },
+ removeItem(key) { this.store.delete(key); },
+ },
+ localStorage: { getItem() { return null; }, setItem() {}, removeItem() {} },
+ // Stand in for the real Mermaid: record what the page asked it to draw. Rendering is
+ // Mermaid's job; what this test owns is that the page asks, and asks with valid source.
+ mermaid: {
+ initialize() {},
+ render(id, source) {
+ diagrams.push({ id, source });
+ const drawn = Promise.resolve({ svg: '<svg/>' });
+ renders.push(drawn);
+ return drawn;
+ },
+ },
+ navigator: { userAgent: 'node' },
+ console: { log() {}, warn() {}, error(message) { errors.push(String(message)); } },
+ setTimeout() { return 0; }, clearTimeout() {},
+ setInterval() { return 0; }, clearInterval() {},
+ requestAnimationFrame() { return 0; },
+ };
+ sandbox.globalThis = sandbox;
+ vm.createContext(sandbox);
+
+ const thrown = [];
+ for (const source of scripts) {
+ try {
+ vm.runInContext(source, sandbox, { timeout: 10000 });
+ } catch (error) {
+ thrown.push(error);
+ }
+ }
+
+ // The page inserts each diagram in a `.then` and falls back to its source in a `.catch`, so
+ // neither has run when the scripts return. Waiting for the renders and then one macrotask
+ // drains both callbacks; without it, a diagram that throws while being inserted fails after
+ // the test has already passed.
+ await Promise.allSettled(renders);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ // `showSource` adds a `.diagram-note` when a diagram could not be drawn. Its text says why.
+ const diagramNotes = [];
+ function collectNotes(target) {
+ if (target.className === 'diagram-note') diagramNotes.push(target.textContent);
+ target.children.forEach(collectNotes);
+ }
+ ['erContainer', 'graphContainer'].forEach((id) => collectNotes(document.getElementById(id)));
+
+ function textOf(target) {
+ if (!target.children.length) return target.textContent;
+ return target.children.map(textOf).join('\n');
+ }
+ const rendered = (id) => textOf(document.getElementById(id));
+
+ return {
+ diagrams, diagramNotes, errors, thrown, elements, rendered, scriptCount: scripts.length,
+ session: sandbox.sessionStorage.store,
+ };
+}
+
+/** A plan far enough along to exercise every renderer: all sections set, mid-build. */
+function fullPlan() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-page-'));
+ let state = initState(root, { appName: 'Field Service', dataPlatform: 'Dataverse + connectors' });
+
+ state = setSection(state, 'environment', {
+ displayName: 'Contoso (Dev)',
+ environmentUrl: 'https://contoso.crm.dynamics.com',
+ publisherPrefix: 'contoso',
+ });
+ state = setSection(state, 'requirements', {
+ appName: 'Field Service', industry: 'Field service', brief: 'Technicians close jobs offline.',
+ features: ['Job list', 'Photo capture'],
+ });
+ state = setSection(state, 'architecture', {
+ dataPlatform: 'Dataverse + connectors',
+ nativeCapabilities: [{ name: 'Camera', reason: 'Photos are the completion evidence.' }],
+ connectors: [{ name: 'SharePoint', reason: 'Manuals are already maintained there.' }],
+ }, 'approved');
+ state = setSection(state, 'dataModel', {
+ tables: [
+ {
+ logicalName: 'contoso_workorder', displayName: 'Work order', status: 'new',
+ purpose: 'One dispatched visit.', reason: 'A case spans weeks; a visit does not.',
+ columns: [
+ { logicalName: 'contoso_workorderid', type: 'Unique identifier', key: 'PK' },
+ // "Yes/No" is a real Dataverse type whose slash is outside Mermaid's ATTRIBUTE_WORD.
+ { logicalName: 'contoso_urgent', type: 'Yes/No' },
+ { logicalName: 'contoso_siteid', type: 'Lookup', key: 'FK' },
+ ],
+ // Human shorthand from native-app-plan.md, not a Mermaid token.
+ relationships: [{ relatedTable: 'contoso_site', name: 'at site', cardinality: 'N:1' }],
+ },
+ {
+ logicalName: 'contoso_site', displayName: 'Site', status: 'reused',
+ purpose: 'Where the asset lives.', reason: 'Sites are already maintained by the service desk.',
+ columns: [{ logicalName: 'contoso_siteid', type: 'Unique identifier', key: 'PK' }],
+ relationships: [],
+ },
+ ],
+ }, 'approved');
+ state = setSection(state, 'offline', {
+ enabled: true, mode: 'Selective sync', tables: ['contoso_workorder'],
+ rationale: 'Plant rooms have no signal.',
+ }, 'approved');
+ state = setSection(state, 'screens', {
+ navigation: 'Bottom tabs (Today, Sites) with a stack pushed from each tab.',
+ list: [
+ { name: 'Sign in', route: '/login', purpose: 'Tenant sign-in.', capabilities: ['Biometrics'] },
+ { name: 'Today', route: '/(app)/today', purpose: "Today's jobs.", capabilities: ['Offline'] },
+ { name: 'Work order', route: '/(app)/work-order/[id]', purpose: 'The visit.', capabilities: [] },
+ { name: 'Capture', route: '/(app)/work-order/[id]/photos', purpose: 'Photos.', capabilities: ['Camera'] },
+ ],
+ }, 'approved');
+ state = setSection(state, 'design', {
+ direction: 'High-contrast utility.', headingFont: 'Segoe UI', bodyFont: 'Segoe UI',
+ darkMode: 'enabled', palette: [{ name: 'Primary', value: '#742774' }],
+ }, 'approved');
+ state = setSection(state, 'auth', { status: 'Configured' });
+ state = setSection(state, 'trust', {
+ permissions: [
+ { name: 'Camera', status: 'on-demand', detail: 'Requested when photo capture starts.', activation: 'Lens runs only while the capture sheet is open.' },
+ { name: 'Photo library', status: 'system-mediated', detail: 'The OS picker returns one image; no library grant is taken.' },
+ { name: 'Biometric unlock', status: 'per-operation', detail: 'Authenticated at each unlock; no standing grant.' },
+ { name: 'Notifications', status: 'on-startup', detail: 'Asked for during onboarding.' },
+ { name: 'Microphone', status: 'not-requested', detail: 'No audio workflow exists in the app.' },
+ // An unrecognised status must not be able to overstate what the app reaches for.
+ { name: 'Location', status: 'whatever-this-is', detail: 'Site coordinates come from Dataverse.' },
+ ],
+ handles: ['Work order records.', 'Work or school account sign-in.'],
+ notCollected: ['No contact list or calendar.', 'No advertising identifier.'],
+ battery: [{ name: 'No continuous GPS', detail: 'No background location updates or geofences.' }],
+ }, 'approved');
+
+ setPhone(state, { stage: 'building' });
+ save(root, state);
+ return { root, htmlPath: outputPath(root) };
+}
+
+test('the generated page runs to completion without throwing', async () => {
+ const { htmlPath } = fullPlan();
+ const result = await runPage(htmlPath);
+
+ assert.ok(result.scriptCount > 0, 'the page must ship an executable script');
+ assert.deepEqual(
+ result.thrown.map((error) => `${error.message}\n${(error.stack || '').split('\n')[1] || ''}`),
+ [],
+ 'the page script threw while rendering a complete plan',
+ );
+ assert.deepEqual(result.errors, [], 'the page logged an error while rendering');
+ assert.equal(result.diagrams.length, 2, 'both diagrams must be handed to mermaid');
+ assert.deepEqual(result.diagramNotes, [], 'a diagram failed after mermaid drew it');
+});
+
+test('both diagrams are drawn, from the structured plan rather than a supplied string', async () => {
+ const { htmlPath } = fullPlan();
+ const { diagrams } = await runPage(htmlPath);
+
+ const er = diagrams.find((d) => d.source.startsWith('erDiagram'));
+ const graph = diagrams.find((d) => d.source.startsWith('flowchart'));
+
+ assert.ok(er, 'the ER diagram was never handed to mermaid');
+ assert.ok(graph, 'the screen graph was never handed to mermaid');
+
+ // Derived from `tables[]`: the slash in "Yes/No" is sanitized and "N:1" became a real token.
+ assert.match(er.source, /contoso_workorder/);
+ assert.doesNotMatch(er.source, /Yes\/No/, 'an unsanitized type would abort the parse');
+ const cardinalities = [...er.source.matchAll(/^ {4}\S+ (\S+) \S+ : /gm)].map((m) => m[1]);
+ assert.ok(cardinalities.length > 0, 'the ER diagram has no relationships');
+ for (const token of cardinalities) {
+ assert.ok(ER_CARDINALITY_TOKENS.includes(token), `'${token}' is not a mermaid cardinality token`);
+ }
+
+ // Derived from `list[]` route nesting: a child route hangs off its parent, not off the shell.
+ assert.match(graph.source, /SHELL\{\{"Bottom tabs"\}\}/, 'the shell label should be the leading phrase');
+ const edges = [...graph.source.matchAll(/^ {4}(\S+) --> (\S+)$/gm)].map((m) => [m[1], m[2]]);
+ const idOf = (name) => (graph.source.match(new RegExp(`^ {4}(S\\d+)\\["${name}"\\]$`, 'm')) || [])[1];
+
+ const today = idOf('Today');
+ const workOrder = idOf('Work order');
+ const capture = idOf('Capture');
+ const signIn = idOf('Sign in');
+ assert.ok(today && workOrder && capture && signIn, 'every screen should appear as a node');
+
+ const has = (from, to) => edges.some(([a, b]) => a === from && b === to);
+ assert.ok(has(signIn, 'SHELL'), 'a screen outside (app) leads into the shell');
+ assert.ok(has('SHELL', today), 'a top-level (app) screen hangs off the shell');
+ assert.ok(has(workOrder, capture), 'a nested route hangs off its parent screen');
+ assert.ok(!has('SHELL', capture), 'a nested route must not also hang off the shell');
+});
+
+test('object-shaped plan entries render as their names, never as [object Object]', async () => {
+ const { htmlPath } = fullPlan();
+ const { elements, rendered } = await runPage(htmlPath);
+
+ // Capabilities and connectors are `{ name, reason }`. The overview listed them through a
+ // plain join, so every entry rendered as "[object Object]" while the Capabilities tab - which
+ // normalized the same data - looked fine.
+ for (const [id, element] of elements) {
+ const text = (function collect(node) {
+ return node.children.length ? node.children.map(collect).join(' ') : node.textContent;
+ })(element);
+ assert.ok(
+ !text.includes('[object Object]'),
+ `#${id} stringified an object instead of reading its name`,
+ );
+ }
+
+ const architecture = rendered('architectureFacts');
+ assert.match(architecture, /Camera/, 'the capability name should reach the overview');
+ assert.match(architecture, /SharePoint/, 'the connector name should reach the overview');
+});
+
+test('enumerable fields render as a list rather than a run-on sentence', async () => {
+ const { htmlPath } = fullPlan();
+ const { elements } = await runPage(htmlPath);
+
+ const listItems = (id) => {
+ const found = [];
+ (function walk(node) {
+ if (node.tagName === 'LI') found.push(node.textContent);
+ node.children.forEach(walk);
+ })(elements.get(id));
+ return found;
+ };
+
+ // Features are separate things; joined with commas they read as one unparseable sentence.
+ const features = listItems('requirementsFacts');
+ assert.deepEqual(features, ['Job list', 'Photo capture']);
+
+ // The offline rationale is authored as paragraphs, one per decision.
+ const offline = listItems('offlineBlock');
+ assert.equal(offline.length, 0, 'a single-paragraph rationale stays prose');
+});
+
+test('a plan with no screens yet shows the empty state instead of drawing an empty graph', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-empty-'));
+ save(root, initState(root, { appName: 'Early', dataPlatform: 'unknown' }));
+
+ const { diagrams, thrown, errors } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), [], 'an empty plan must still render');
+ assert.deepEqual(errors, []);
+ assert.equal(
+ diagrams.filter((d) => d.source.startsWith('flowchart')).length, 0,
+ 'with no screens there is nothing to draw',
+ );
+});
+
+test('a multi-paragraph rationale becomes one bullet per point', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-offline-'));
+ let state = initState(root, { appName: 'Offline', dataPlatform: 'dataverse' });
+ state = setSection(state, 'offline', {
+ enabled: true,
+ mode: 'Selective sync',
+ tables: ['contoso_workorder'],
+ // Authored as blank-line-separated points, which is how the plan records a rationale.
+ rationale: 'Plant rooms have no signal.\n\nOnly the next two days are cached.\n\nWrites replay in order.',
+ }, 'approved');
+ save(root, state);
+
+ const { elements, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const items = [];
+ (function walk(node) {
+ if (node.tagName === 'LI') items.push(node.textContent);
+ node.children.forEach(walk);
+ })(elements.get('offlineBlock'));
+
+ assert.deepEqual(items, [
+ 'Plant rooms have no signal.',
+ 'Only the next two days are cached.',
+ 'Writes replay in order.',
+ ]);
+});
+
+test('a named font is applied to the card that names it, and only if it is a safe name', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-font-'));
+ let state = initState(root, { appName: 'Fonts', dataPlatform: 'dataverse' });
+ state = setSection(state, 'design', {
+ direction: 'Utility.',
+ headingFont: 'Segoe UI Variable Display',
+ // A name that would close the quoted family and append a declaration must be refused
+ // outright rather than escaped, so nothing from the plan can reach the stylesheet.
+ bodyFont: 'Evil", x:expression(alert(1)), "',
+ darkMode: 'enabled',
+ palette: [{ name: 'Primary', value: '#742774' }],
+ }, 'approved');
+ save(root, state);
+
+ const { elements, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const styled = [];
+ (function walk(node) {
+ if (node.style && node.style.fontFamily) styled.push(node.style.fontFamily);
+ node.children.forEach(walk);
+ })(elements.get('designFacts'));
+
+ assert.deepEqual(styled, ['"Segoe UI Variable Display", system-ui, sans-serif'],
+ 'the safe name is applied with a fallback; the crafted one is dropped');
+});
+
+test('the screens stage with nothing to show falls back to the building animation', async () => {
+ // The skill is told to skip the stage switch when --no-design or "Skip preview" means no
+ // _plan_preview.html was written. If it switches anyway, the phone must keep animating rather
+ // than render an empty carousel with dead prev/next controls.
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-nocarousel-'));
+ const state = initState(root, { appName: 'No design', dataPlatform: 'dataverse' });
+ setPhone(state, { stage: 'screens', screens: [] });
+ save(root, state);
+
+ const { elements, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const classes = [];
+ (function walk(node) {
+ if (node.className) classes.push(node.className);
+ node.children.forEach(walk);
+ })(elements.get('deviceScreen'));
+
+ assert.ok(classes.some((c) => String(c).split(' ').includes('bld')), 'expected the build animation');
+ assert.ok(!classes.some((c) => String(c).split(' ').includes('car')), 'expected no carousel');
+ assert.equal(elements.get('railTitle').textContent, 'Building your app');
+});
+
+test('the trust report states when each permission is used, and downgrades an unknown status', async () => {
+ const { htmlPath } = fullPlan();
+ const { elements, thrown } = await runPage(htmlPath);
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const rows = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('perm')) rows.push(node);
+ node.children.forEach(walk);
+ })(elements.get('permissionList'));
+ assert.equal(rows.length, 6, 'every recorded permission gets a row');
+
+ const flat = (node) => (node.children.length ? node.children.map(flat).join(' ') : node.textContent);
+ const text = rows.map(flat).join(' | ');
+
+ // A capability the app never asks for is the entry a reviewer actually needs, so it must be
+ // listed rather than omitted.
+ assert.match(text, /Microphone[\s\S]*NOT REQUESTED/);
+ // The badge names the acquisition pattern, not just whether access exists: "at startup" and
+ // "on demand" end with the same grant but differ entirely in how it was obtained.
+ assert.match(text, /Camera[\s\S]*ON DEMAND/);
+ assert.match(text, /Photo library[\s\S]*SYSTEM-MEDIATED/);
+ assert.match(text, /Biometric unlock[\s\S]*PER OPERATION/);
+ assert.match(text, /Notifications[\s\S]*AT STARTUP/);
+
+ // Authorization and activation are separate events and are reported separately.
+ assert.match(text, /Hardware: Lens runs only while the capture sheet is open\./);
+
+ // An unrecognised status resolves to the weakest claim, never to "on demand".
+ const location = rows.find((row) => flat(row).includes('Location'));
+ assert.match(flat(location), /NOT REQUESTED/, 'an unknown status must not overstate access');
+
+ // Each row carries when-and-why, not just a name and a badge.
+ assert.match(text, /Requested when photo capture starts\./);
+
+ // Each row leads with an inline SVG, not a unicode glyph: geometric shapes were unreadable
+ // at this size. Distinctness is the point - if two permission types share an icon the column
+ // is decoration.
+ const icons = rows.map((row) => row.children[0].innerHTML);
+ for (const icon of icons) {
+ assert.match(icon, /^<svg viewBox="0 0 24 24"/, 'every row needs a drawn icon');
+ assert.ok(icon.includes('stroke="currentColor"'), 'icons must inherit the row colour');
+ }
+ assert.equal(new Set(icons).size, icons.length, 'no two permission types may share an icon');
+});
+
+test('the trust report separates what is handled from what is not collected', async () => {
+ const { htmlPath } = fullPlan();
+ const { elements } = await runPage(htmlPath);
+ const flat = (node) => (node.children.length ? node.children.map(flat).join(' ') : node.textContent);
+
+ const handles = flat(elements.get('handlesCard'));
+ const notCollected = flat(elements.get('notCollectedCard'));
+ assert.match(handles, /What the app handles/);
+ assert.match(handles, /Work order records\./);
+ assert.match(notCollected, /What the app does not collect/);
+ assert.match(notCollected, /No contact list or calendar\./);
+ assert.ok(!handles.includes('No contact list'), 'the two lists must not bleed together');
+
+ assert.match(flat(elements.get('batteryList')), /No continuous GPS[\s\S]*geofences/);
+});
+
+test('every icon a capability name can select is actually drawn', () => {
+ // permissionIconName returns a key into ICON_PATHS. A typo on either side yields
+ // "undefined" inside the <svg>, which renders as an empty box rather than failing.
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ const defined = new Set(
+ [...template.matchAll(/^ ([a-z]+): '<(?:rect|path|circle|ellipse)/gm)].map((m) => m[1]),
+ );
+ assert.ok(defined.size >= 10, `expected the full icon set, found ${defined.size}`);
+
+ const selected = [...template.matchAll(/^ \[\/[^\]]*\/, '([a-z]+)'\]/gm)].map((m) => m[1]);
+ assert.ok(selected.length > 0, 'the keyword map must select icons');
+ for (const key of selected) {
+ assert.ok(defined.has(key), `keyword map selects '${key}', which ICON_PATHS does not define`);
+ }
+
+ // Callers pass a fallback naming their list ('device', 'plug'); anything unrecognised drops
+ // to the hard-coded last resort. All three must be real icons.
+ const fallbacks = [
+ ...[...template.matchAll(/permissionIcon\([^)]*?'([a-z]+)'\s*:\s*'([a-z]+)'/g)].flatMap((m) => [m[1], m[2]]),
+ (template.match(/return ICON_PATHS\[fallback\] \? fallback : '([a-z]+)';/) || [])[1],
+ ].filter(Boolean);
+ assert.ok(fallbacks.length >= 3, `expected caller and last-resort fallbacks, got ${fallbacks}`);
+ for (const key of fallbacks) {
+ assert.ok(defined.has(key), `fallback '${key}' is not a defined icon`);
+ }
+});
+
+test('a background-tracking capability does not borrow the on-demand location pin', async () => {
+ // "Background location" contains "location", so keyword order is what keeps the two apart.
+ // Getting this wrong would show a never-requested capability with the icon of one the app
+ // actively asks for - the exact claim this report exists to make precisely.
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-icons-'));
+ let state = initState(root, { appName: 'Icons', dataPlatform: 'dataverse' });
+ state = setSection(state, 'trust', {
+ permissions: [
+ { name: 'Location', status: 'on-demand', detail: 'Read on arrival.' },
+ { name: 'Background location', status: 'not-requested', detail: 'No geofences.' },
+ ],
+ }, 'approved');
+ save(root, state);
+
+ const { elements, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const rows = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('perm')) rows.push(node);
+ node.children.forEach(walk);
+ })(elements.get('permissionList'));
+ assert.equal(rows.length, 2);
+ assert.notEqual(rows[0].children[0].innerHTML, rows[1].children[0].innerHTML);
+});
+
+test('a blocked run shows a waiting-for-input banner, and clears it when unblocked', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-await-'));
+ let state = initState(root, { appName: 'Waiting', dataPlatform: 'dataverse' });
+ // A section held at `proposed` is the plan showing something for review while the terminal
+ // waits on the answer.
+ state = setSection(state, 'dataModel', { tables: [] }, 'proposed');
+ save(root, state);
+
+ let page = await runPage(outputPath(root));
+ assert.deepEqual(page.thrown.map((e) => e.message), []);
+ assert.equal(page.elements.get('inputBanner').hidden, false, 'a proposed section must raise the banner');
+ assert.match(page.elements.get('inputBannerPrompt').textContent, /Review the data model/);
+
+ // Approving it is what takes the banner down - nothing else has to remember to.
+ state = setSection(state, 'dataModel', { tables: [] }, 'approved');
+ save(root, state);
+ page = await runPage(outputPath(root));
+ assert.equal(page.elements.get('inputBanner').hidden, true, 'approval must clear the banner');
+});
+
+test('a dismissed banner stays dismissed across reloads, for that prompt only', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-dismiss-'));
+ let state = initState(root, { appName: 'Dismiss', dataPlatform: 'dataverse' });
+ state = applyStep(state, { id: 'data-model', status: 'active', note: 'Gate 2 — awaiting your approval' });
+ save(root, state);
+ const KEY = 'mobile-plan-dismissed-prompt';
+
+ // The page reloads itself every few seconds, so a dismissal held only in memory came back on
+ // the next reload. What the user closed is carried in sessionStorage instead.
+ let page = await runPage(outputPath(root), { session: { [KEY]: 'Gate 2 — awaiting your approval' } });
+ assert.equal(page.elements.get('inputBanner').hidden, true, 'the dismissed prompt stays hidden');
+
+ // Keyed to the prompt text, so closing one gate's banner does not silence the next gate's.
+ page = await runPage(outputPath(root), { session: { [KEY]: 'Gate 1 — awaiting your approval' } });
+ assert.equal(page.elements.get('inputBanner').hidden, false, 'a different prompt is shown');
+
+ // And forgotten once nothing is waiting, so the same words asked again are shown again.
+ state = applyStep(state, { id: 'data-model', status: 'done' });
+ save(root, state);
+ page = await runPage(outputPath(root), { session: { [KEY]: 'Gate 2 — awaiting your approval' } });
+ assert.equal(page.session.has(KEY), false);
+
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ assert.match(template, /sessionStorage\.setItem\(STORE_DISMISSED, dismissedPrompt\)/,
+ 'closing the banner records what was closed');
+});
+
+test('the trust report is labelled a draft, not sent to a terminal prompt that never comes', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-trust-draft-'));
+ let state = initState(root, { appName: 'Draft', dataPlatform: 'dataverse' });
+ state = setSection(state, 'trust', { permissions: [{ name: 'Camera', status: 'on-demand' }] }, 'proposed');
+ state = setSection(state, 'design', { direction: 'Calm' }, 'proposed');
+ save(root, state);
+
+ const { rendered } = await runPage(outputPath(root));
+ // No gate asks the user about the trust report; it is finalised at Step 10.
+ assert.match(rendered('approval-trust'), /^\s*Draft - written from the approved plan/);
+ assert.doesNotMatch(rendered('approval-trust'), /terminal/);
+ // A section that is put to a gate keeps the instruction.
+ assert.match(rendered('approval-design'), /answer the approval prompt in your terminal/);
+});
+
+test('the topbar shows when the plan was updated in the reader\'s own time', async () => {
+ const { htmlPath } = fullPlan();
+ const html = fs.readFileSync(htmlPath, 'utf8');
+ // The renderer runs in UTC, so the static text says so - that is what shows if the script
+ // cannot run.
+ assert.match(html, /Updated \d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC</);
+
+ const { elements } = await runPage(htmlPath);
+ const shown = elements.get('updatedAt').textContent;
+ assert.match(shown, /^Updated /);
+ assert.doesNotMatch(shown, /UTC$/, 'the script replaces it with local time');
+});
+
+test('a screen whose capabilities are objects lists their names', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-screen-caps-'));
+ let state = initState(root, { appName: 'Caps', dataPlatform: 'dataverse' });
+ state = setSection(state, 'screens', {
+ navigation: 'Stack',
+ list: [{ name: 'Capture', route: '/(app)/capture', capabilities: [{ name: 'Camera', reason: 'Meter photos' }, 'Location'] }],
+ });
+ save(root, state);
+
+ const { rendered } = await runPage(outputPath(root));
+ assert.match(rendered('screensContainer'), /Camera, Location/);
+ assert.doesNotMatch(rendered('screensContainer'), /object Object/);
+});
+
+/**
+ * Run the page's own sanitizer against hand-built nodes.
+ *
+ * The page harness has no HTML parser, so the sanitizer is lifted out of the template and given
+ * a `<template>` whose content is exactly these nodes. That exercises its real decisions -
+ * which tags go, which attributes go - rather than matching its source text.
+ */
+function sanitize(nodes, options) {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ const source = template.slice(template.indexOf(' var MOCKUP_BANNED_TAGS'), template.indexOf('\n function renderPhone('));
+ const parent = { removeChild(child) { child.removed = true; } };
+ nodes.forEach((n) => { n.parentNode = parent; });
+ const context = vm.createContext({
+ document: { createElement: () => ({ innerHTML: '', content: { querySelectorAll: () => nodes } }) },
+ options,
+ });
+ vm.runInContext(`${source}\nsanitizeMockup('', options);`, context);
+}
+
+function element(tagName, attributes = {}) {
+ const attrs = { ...attributes };
+ return {
+ tagName,
+ removed: false,
+ attrs,
+ get attributes() { return Object.entries(attrs).map(([name, value]) => ({ name, value })); },
+ removeAttribute(name) { delete attrs[name]; },
+ };
+}
+
+test('the sanitizer removes SVG-cased elements and disguised script URLs', () => {
+ // Inside inline SVG `tagName` keeps its own case, so an upper-case list missed these.
+ const svgStyle = element('style');
+ const svgScript = element('script');
+ const animate = element('animate', { attributeName: 'href' });
+ const tabbed = element('a', { href: 'java\tscript:void(0)' });
+ const controlled = element('a', { href: ' \u0001javascript:void(0)' });
+ const htmlDoc = element('a', { href: 'DATA:text/html,<b>x</b>' });
+ const safe = element('a', { href: 'https://contoso.com/' });
+ const image = element('img', { src: 'data:image/png;base64,AAAA', onerror: 'void(0)', ONLOAD: 'void(0)' });
+
+ sanitize([svgStyle, svgScript, animate, tabbed, controlled, htmlDoc, safe, image]);
+
+ assert.equal(svgStyle.removed, true, 'an SVG <style> could restyle the approval banners');
+ assert.equal(svgScript.removed, true);
+ assert.equal(animate.removed, true, 'animation can rewrite an href after it was checked');
+ assert.equal(tabbed.attrs.href, undefined, 'browsers drop the tab, so this is javascript:');
+ assert.equal(controlled.attrs.href, undefined);
+ assert.equal(htmlDoc.attrs.href, undefined);
+ assert.equal(safe.attrs.href, 'https://contoso.com/');
+ assert.deepEqual(image.attrs, { src: 'data:image/png;base64,AAAA' }, 'images stay; handlers go');
+});
+
+test('Mermaid output keeps its own stylesheet, and nothing else does', () => {
+ // Mermaid scopes its rules to the SVG's id, and the diagram is unstyled without them.
+ const kept = element('style');
+ const script = element('script');
+ sanitize([kept, script], { keepStyle: true });
+ assert.equal(kept.removed, false);
+ assert.equal(script.removed, true);
+
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ const calls = [...template.matchAll(/sanitizeMockup\(([^)]*)\)/g)].map((m) => m[1]);
+ assert.deepEqual(calls.filter((c) => /keepStyle/.test(c)), ['result.svg, { keepStyle: true }'],
+ 'only the Mermaid render may keep a stylesheet; mockups must not');
+});
+
+test('the topbar pills say what their numbers mean', async () => {
+ const { htmlPath } = fullPlan();
+ const { elements } = await runPage(htmlPath);
+ // "4 of 11" and "unknown" on their own read as unlabelled noise.
+ assert.match(elements.get('pillProgress').textContent, /^Step \d+ of \d+$/);
+
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ assert.match(template, /pill-platform">Data: __HTML_DATA_PLATFORM__/);
+});
+
+test('the planner markdown is linked only once it exists on disk', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-doc-'));
+ const state = initState(root, { appName: 'Linked', dataPlatform: 'dataverse' });
+ save(root, state);
+
+ const links = (page) => {
+ const found = [];
+ for (const [, element] of page.elements) {
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('plan-doc')) found.push(node);
+ node.children.forEach(walk);
+ })(element);
+ }
+ return found;
+ };
+
+ // The planner writes native-app-plan.md at Step 3. Before that a link would 404 in the
+ // user's browser, so it is not emitted at all.
+ assert.deepEqual(links(await runPage(outputPath(root))), [], 'no link before the file exists');
+
+ // The plan is written into docs/, so the file sits one level up.
+ fs.writeFileSync(path.join(root, 'native-app-plan.md'), '# Plan\n');
+ save(root, state);
+ const shown = links(await runPage(outputPath(root)));
+ assert.ok(shown.length >= 1, 'the link appears once the planner has written its output');
+ assert.match(shown[0].textContent, /Full screen specs|Read the full plan/);
+
+ // Markdown belongs in an editor, and a browser cannot invoke the OS default app for a link -
+ // an editor URL scheme is the only route that works from a file:// page.
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ assert.match(template, /summary\.planDocEditorHref \|\| summary\.planDocHref/,
+ 'prefer the editor link, but never leave a reader without one stranded');
+ assert.match(template, /plan-doc-raw/, 'the plain file link must remain available');
+
+ // The plan reloads itself for the whole run, so a link that navigates away from it must open
+ // beside it. The editor link only hands off to the editor, so it is given a new tab only when
+ // it has fallen back to the plain file.
+ const planDoc = template.slice(template.indexOf('function planDocLink('), template.indexOf('function renderScreens('));
+ assert.match(planDoc, /if \(!summary\.planDocEditorHref\) \{\s*link\.setAttribute\('target', '_blank'\);\s*link\.setAttribute\('rel', 'noopener'\);/,
+ 'a link falling back to the plain file must not replace the live plan');
+ assert.match(planDoc, /raw\.setAttribute\('target', '_blank'\);\s*raw\.setAttribute\('rel', 'noopener'\);/,
+ 'the plain file link must not replace the live plan');
+});
+
+test('the full-size screens are linked under the phone, once they exist', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-preview-'));
+ const state = initState(root, { appName: 'Preview', dataPlatform: 'dataverse' });
+ save(root, state);
+
+ const railLink = (page) => {
+ const found = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('rail-link')) found.push(node);
+ node.children.forEach(walk);
+ })(page.elements.get('railPreviewLink'));
+ return found;
+ };
+
+ // `/design-system` writes it at Step 6.75; before that the link would 404.
+ assert.deepEqual(railLink(await runPage(outputPath(root))), [], 'no link before the file exists');
+
+ // Written into docs/, beside the plan, where every reviewable artifact is collected.
+ fs.writeFileSync(path.join(root, '_plan_preview.html'), '<html></html>');
+ save(root, state);
+ const shown = railLink(await runPage(outputPath(root)));
+ assert.equal(shown.length, 1, 'the link appears once the preview is rendered');
+ assert.match(shown[0].textContent, /full size/i);
+});
+
+test('the create skill renders the screen preview but never opens it', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+
+ // The plan shows these screens in its phone frame and links out to the file, so a browser tab
+ // opening mid-run interrupts a user who is already watching the plan.
+ for (const block of skill.matchAll(/```(?:bash|sh)\n([\s\S]*?)```/g)) {
+ assert.ok(
+ !/_plan_preview\.html/.test(block[1]),
+ `a runnable command still touches the screen preview: ${block[1].trim().slice(0, 80)}`,
+ );
+ }
+ // It must still be rendered - the carousel takes its markup from those blocks - and it is
+ // written into docs/ with every other artifact the user is asked to look at.
+ assert.match(skill, /Render `_plan_preview\.html`/);
+});
+
+test('the QR is drawn in the phone and linked for scanning full size', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-qr-'));
+ const state = initState(root, { appName: 'QR', dataPlatform: 'dataverse' });
+ // What the `phone --stage qr --qr-image` CLI path produces: the code inlined for the phone,
+ // plus a relative path for opening the file itself.
+ setPhone(state, {
+ stage: 'qr',
+ qrImage: 'data:image/png;base64,iVBORw0KGgo=',
+ qrHref: '../.expo/metro-qr.png',
+ qrUrl: 'exp://192.168.1.4:8081',
+ });
+ save(root, state);
+
+ const { elements, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+
+ const links = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('rail-link')) links.push(node);
+ node.children.forEach(walk);
+ })(elements.get('railPreviewLink'));
+ assert.equal(links.length, 1, 'the QR gets a link under the phone');
+ assert.match(links[0].textContent, /QR code full size/);
+
+ // The link must be the file, not the inlined copy: browsers block top-level navigation to a
+ // data: URL, so linking the data URI would silently do nothing.
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ assert.match(template, /add\(phone\.qrHref,/);
+ assert.doesNotMatch(template, /add\(phone\.qrImage,/);
+
+ // And it is still drawn inside the phone, which is what survives `.expo/` being cleaned.
+ const screen = elements.get('deviceScreen');
+ const imgs = [];
+ (function walk(node) {
+ if (node.tagName === 'IMG') imgs.push(node);
+ node.children.forEach(walk);
+ })(screen);
+ assert.equal(imgs.length, 1, 'the QR image stays in the phone frame');
+
+ // A QR is useless without the app that reads it, and this is the end of the run.
+ const stores = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('store-btn')) stores.push(node);
+ node.children.forEach(walk);
+ })(elements.get('railPreviewLink'));
+ assert.equal(stores.length, 2, 'both stores are offered at the QR stage');
+
+ const flatten = (node) => (node.children.length ? node.children.map(flatten).join(' ') : node.textContent);
+ assert.match(stores.map(flatten).join(' | '), /App Store[\s\S]*Google Play/);
+
+ // Each badge leads with its store's mark - a text-only pill does not read as a store button.
+ const marks = stores.map((button) => {
+ const found = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('store-logo')) found.push(node.innerHTML);
+ node.children.forEach(walk);
+ })(button);
+ return found[0] || '';
+ });
+ assert.equal(marks.filter((m) => m.startsWith('<svg viewBox="0 0 24 24"')).length, 2,
+ 'both badges need a drawn mark');
+ assert.notEqual(marks[0], marks[1], 'the two stores must not share a mark');
+ // The Play mark's colours are its identity, so they are fixed rather than inherited.
+ assert.match(marks[1], /fill="#/);
+ assert.match(marks[0], /fill="currentColor"/);
+});
+
+test('the store links are only offered once the app can actually be used', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-store-'));
+ const state = initState(root, { appName: 'Early', dataPlatform: 'dataverse' });
+ save(root, state);
+
+ const stores = [];
+ (function walk(node) {
+ if (String(node.className).split(' ').includes('store-btn')) stores.push(node);
+ node.children.forEach(walk);
+ })((await await runPage(outputPath(root))).elements.get('railPreviewLink'));
+ // Sending someone to install a player while their app is still being generated hands them
+ // something they cannot use yet.
+ assert.deepEqual(stores, [], 'no store links during the build');
+
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ // These are the only links in the plan that leave the machine.
+ assert.match(template, /rel', 'noopener noreferrer'/);
+ // Locale-neutral: the plan is a file people share across markets.
+ assert.doesNotMatch(template, /apps\.apple\.com\/[a-z]{2}\//);
+});
+
+test('the skill points at the plan instead of opening the QR in a window', () => {
+ const skill = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', 'skills', 'create-mobile-app', 'SKILL.md'), 'utf8',
+ );
+ // The plan draws the QR and links it, so a window opening over a run the user is watching
+ // adds nothing. Asserted on runnable commands, not prose - the prose states the rule and
+ // would trip a naive whole-file match.
+ for (const block of skill.matchAll(/```(?:bash|sh)\n([\s\S]*?)```/g)) {
+ assert.ok(
+ !/(open|xdg-open|Start-Process|start "")\s+"?\$METRO_QR/.test(block[1]),
+ `a runnable command still opens the QR: ${block[1].trim().slice(0, 70)}`,
+ );
+ }
+ assert.match(skill, /do \*\*not\*\* open the PNG/);
+});
+
+test('the plan carries the same AI disclaimer as every other plan page', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ // Worded exactly as the power-pages artifacts word it, so a reader meets one sentence across
+ // the plugins rather than a different hedge in each.
+ assert.match(template, /<footer class="ai-footer">AI-generated content may be incorrect<\/footer>/);
+
+ // It is fixed to the viewport, so the page and the sticky device rail must both stop short of
+ // it; otherwise their last line sits underneath it.
+ assert.match(template, /body\{[^}]*padding-bottom:var\(--footer-h\)/);
+ assert.match(template, /\.rail\{[^}]*calc\(100vh - 65px - var\(--footer-h\)\)/);
+});
+
+test('the carousel says the mockups are not the built app, and only while they are shown', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-note-'));
+ const state = initState(root, { appName: 'Note', dataPlatform: 'dataverse' });
+
+ // Building: nothing to caveat yet.
+ save(root, state);
+ assert.equal((await await runPage(outputPath(root))).elements.get('railNote').hidden, true);
+
+ // Screens: the user is looking at approximations rendered from the specs.
+ setPhone(state, { stage: 'screens', screens: [{ name: 'Today', html: '<div>Today</div>' }] });
+ save(root, state);
+ const shown = (await await runPage(outputPath(root))).elements.get('railNote');
+ assert.equal(shown.hidden, false);
+ assert.match(shown.textContent, /mockups[\s\S]*differ/i);
+
+ // QR: the phone now shows a real code, so the caveat would be wrong.
+ setPhone(state, { stage: 'qr', qrImage: 'data:image/png;base64,iVBORw0KGgo=' });
+ save(root, state);
+ assert.equal((await await runPage(outputPath(root))).elements.get('railNote').hidden, true);
+});
+
+test('the page carries a policy that makes injected mockup markup inert', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ const csp = template.match(/<meta http-equiv="Content-Security-Policy" content="([^"]+)"/);
+ assert.ok(csp, 'the plan must ship a CSP');
+ const policy = csp[1];
+
+ // Nothing loads unless this policy names it.
+ assert.match(policy, /default-src 'none'/);
+ // A script injected through a mockup carries no nonce, and inline handlers need
+ // 'unsafe-inline', which is deliberately absent from script-src.
+ // The nonce alone. A host source would admit every script on that CDN, not just Mermaid.
+ assert.match(policy, /script-src 'nonce-__ATTR_CSP_NONCE__';/);
+ assert.doesNotMatch(policy.match(/script-src[^;]*/)[0], /https?:|\*/);
+ assert.doesNotMatch(policy.match(/script-src[^;]*/)[0], /unsafe-inline|unsafe-eval/);
+ // Every image the plan shows is inlined, so an injected <img src> cannot call out.
+ assert.match(policy, /img-src data:/);
+ assert.doesNotMatch(policy, /connect-src|frame-src/);
+
+ // The nonce the policy names must be the one the page's own scripts carry.
+ assert.ok(template.includes('<script nonce="__ATTR_CSP_NONCE__"'), 'page scripts need the nonce');
+});
+
+test('generated markup is cleaned before it reaches the document', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ // Parsed into a <template>, whose content is inert: nothing runs and no resource is fetched
+ // while it is being cleaned.
+ assert.match(template, /holder\.content\.querySelectorAll\('\*'\)/);
+ for (const tag of ['SCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'FORM']) {
+ assert.ok(template.includes(`'${tag}'`), `${tag} must be stripped from mockups`);
+ }
+ assert.match(template, /\/\^on\/i\.test\(name\)/, 'every on* handler must be removed');
+ assert.match(template, /javascript:\|data:text\\\/html/, 'executing and navigating URLs must be refused');
+
+ // The two places that take generated markup both go through it.
+ const sanitized = [...template.matchAll(/appendChild\(sanitizeMockup\(/g)];
+ assert.equal(sanitized.length, 2, 'mockups and mermaid output both need cleaning');
+ // And neither assigns it straight in.
+ assert.doesNotMatch(template, /frame\.innerHTML/);
+ assert.doesNotMatch(template, /panel\.innerHTML = result\.svg/);
+});
+
+test('the third-party script is pinned by version and by content', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ const tag = template.match(/<script[^>]*cdn\.jsdelivr\.net[^>]*>/s);
+ assert.ok(tag, 'the page loads one script from the CDN');
+ const attrs = tag[0];
+
+ // A floating major resolves to whatever is latest when the plan is opened, so the code running
+ // inside a page holding the environment URL, tenant id and the whole plan could change with
+ // nothing changing here.
+ assert.doesNotMatch(attrs, /mermaid@\d+\//, 'the version must be exact, not a floating major');
+ assert.match(attrs, /mermaid@\d+\.\d+\.\d+\//);
+
+ // The CSP pins where a script may come from; only integrity pins what it is.
+ assert.match(attrs, /integrity="sha(256|384|512)-[A-Za-z0-9+/]+={0,2}"/);
+ // Integrity is not enforced on a cross-origin script without this.
+ assert.match(attrs, /crossorigin="anonymous"/);
+ // And it still carries the nonce the CSP names.
+ assert.match(attrs, /nonce="__ATTR_CSP_NONCE__"/);
+
+ // A refusal must degrade, not break: the page falls back to the diagram source.
+ assert.match(template, /typeof mermaid === 'undefined'/);
+ assert.match(template, /Mermaid could not load/);
+});
+
+test('two relationships between the same tables both survive into the diagram', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-rels-'));
+ let state = initState(root, { appName: 'Rels', dataPlatform: 'dataverse' });
+ state = setSection(state, 'dataModel', {
+ tables: [
+ {
+ logicalName: 'contoso_request', displayName: 'Request', status: 'new',
+ columns: [{ logicalName: 'contoso_requestid', type: 'Unique identifier', key: 'PK' }],
+ // A requester and an approver lookup to the same table. Keying the dedup on the table
+ // pair alone drew the first and silently dropped the second.
+ relationships: [
+ { relatedTable: 'systemuser', name: 'requested by', cardinality: 'N:1' },
+ { relatedTable: 'systemuser', name: 'approved by', cardinality: 'N:1' },
+ ],
+ },
+ {
+ logicalName: 'systemuser', displayName: 'User', status: 'reused',
+ columns: [{ logicalName: 'systemuserid', type: 'Unique identifier', key: 'PK' }],
+ relationships: [],
+ },
+ ],
+ }, 'approved');
+ save(root, state);
+
+ const { diagrams, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+ const er = diagrams.find((d) => d.source.startsWith('erDiagram'));
+ assert.ok(er, 'the ER diagram must render');
+ assert.match(er.source, /"requested by"/);
+ assert.match(er.source, /"approved by"/);
+
+ // The reverse declaration of the same relationship is still suppressed.
+ const edges = [...er.source.matchAll(/^ {4}\S+ \S+ \S+ : "([^"]+)"$/gm)].map((m) => m[1]);
+ assert.equal(edges.length, new Set(edges).size, 'no relationship may be drawn twice');
+});
+
+test('a table that relates to itself is drawn, not dropped', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-self-'));
+ let state = initState(root, { appName: 'Self', dataPlatform: 'dataverse' });
+ state = setSection(state, 'dataModel', {
+ tables: [
+ {
+ logicalName: 'account', displayName: 'Account', status: 'reused',
+ columns: [{ logicalName: 'accountid', type: 'Unique identifier', key: 'PK' }],
+ // Parent account is a standard Dataverse hierarchy, so the approved model has it.
+ relationships: [{ relatedTable: 'account', name: 'parent account', cardinality: 'N:1' }],
+ },
+ {
+ logicalName: 'contoso_site', displayName: 'Site', status: 'new',
+ columns: [{ logicalName: 'contoso_siteid', type: 'Unique identifier', key: 'PK' }],
+ // A related table outside the model still has nothing to point at.
+ relationships: [{ relatedTable: 'contoso_missing', name: 'orphan', cardinality: 'N:1' }],
+ },
+ ],
+ }, 'approved');
+ save(root, state);
+
+ const { diagrams, diagramNotes, thrown } = await runPage(outputPath(root));
+ assert.deepEqual(thrown.map((e) => e.message), []);
+ assert.deepEqual(diagramNotes, []);
+ const er = diagrams.find((d) => d.source.startsWith('erDiagram'));
+ assert.ok(er, 'the ER diagram must render');
+ assert.match(er.source, /^ {4}ACCOUNT \S+ ACCOUNT : "parent account"$/m);
+ assert.doesNotMatch(er.source, /"orphan"/);
+});
+
+test('the two plan-document links are siblings, not one inside the other', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ // An <a> inside an <a> is invalid and leaves keyboard and screen-reader users with an
+ // ambiguous control.
+ assert.doesNotMatch(template, /link\.appendChild\(raw\)/);
+ assert.match(template, /container\.appendChild\(link\);\s*\n\s*container\.appendChild\(raw\);/);
+});
+
+test('mockup CSS cannot reach past the phone frame', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+
+ // CSS is the one vector the CSP cannot close: `style-src 'unsafe-inline'` is required for this
+ // page's own stylesheet and for Mermaid's, so an injected stylesheet would be permitted.
+ // A `<style>` element's selectors are global and could restyle the approval banner or the
+ // trust report - hiding or spoofing the UI a reviewer is reading.
+ assert.match(template, /MOCKUP_BANNED_TAGS = \[[^\]]*'STYLE'/);
+
+ // `style=` attributes survive, because they are what makes a mockup look like the screen. They
+ // only affect their own element - except `position: fixed`, which would otherwise lay out
+ // against the viewport. `contain: paint` makes the frame a containing block for fixed and
+ // absolute descendants, so an injected overlay stays inside the phone.
+ assert.match(template, /\.car-frame\{[^}]*contain:layout paint/);
+});
+
+test('a table status tints the whole entity box, not just its header', () => {
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ const fn = template.slice(template.indexOf('function colorErDiagram'));
+ const body = fn.slice(0, fn.indexOf('\n function '));
+
+ // Header fill plus both alternating row bands. Tinting only the header left every table's
+ // body the same lavender Mermaid ships, so status read as a stripe at the top rather than as
+ // a property of the table.
+ for (const map of ['fills', 'rowOddFills', 'rowEvenFills', 'strokes']) {
+ assert.match(body, new RegExp(`var ${map} = \\{ new: '#`), `${map} must be defined`);
+ }
+ assert.match(body, /\.row-rect-odd, \.row-rect-even/);
+ assert.match(body, /rowOddFills : rowEvenFills/, 'both bands must be selected per row');
+ assert.match(body, /setAttribute\('fill', fill\[status\]\)/, 'the band is filled by status');
+
+ // Dividers take the status stroke, but only where Mermaid drew a real rule - a `none` stroke
+ // is a spacer, and overwriting it adds lines the box was not meant to have.
+ assert.match(body, /\.divider path/);
+ assert.match(body, /getAttribute\('stroke'\) !== 'none'/);
+
+ // The three palettes must agree with the legend's three swatches.
+ const legend = [...template.matchAll(/er-legend-swatch" style="background:[^;]+;border-color:(#[0-9a-f]{6})/g)]
+ .map((m) => m[1]);
+ assert.deepEqual(legend, ['#0078d4', '#ca5010', '#107c10'],
+ 'the legend swatches must be the same three strokes the diagram uses');
+});
+
+test('every function the page defines is defined exactly once', () => {
+ // `showSource` was defined twice, the second copy silently replacing the first. Duplicates are
+ // invisible at runtime, so the only way to see one is to count the definitions.
+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
+ const counts = new Map();
+ for (const [, name] of template.matchAll(/^ {2}function ([A-Za-z0-9_]+)\(/gm)) {
+ counts.set(name, (counts.get(name) || 0) + 1);
+ }
+ const duplicates = [...counts].filter(([, count]) => count > 1).map(([name]) => name);
+ assert.deepEqual(duplicates, [], 'these functions are defined more than once');
+});
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 7e436cdd2..c5abed217 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -75,6 +75,108 @@ This gate is intentionally simple: `/create-mobile-app` creates a new app from a
---
+## Build documentation protocol
+
+The run also writes a plan the user can read while it happens and keep afterwards:
+`<working_dir>/docs/create-app-plan.html`, rendered by
+[`scripts/app-docs.js`](${PLUGIN_ROOT}/scripts/app-docs.js) in the same Fluent format the
+Power Pages `/create-site` plan uses. It is the record of *why* the app looks the way it does,
+so a teammate opening the repo months later can see the environment, the approved data model,
+and the screen plan without re-reading a transcript.
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" <command>
+```
+
+| Command | Use |
+|---|---|
+| `init --json-file <path>` | Once, at Step 2b, with `{"appName","dataPlatform"}`. Safe to re-run: a resume keeps recorded progress. The display name is user text, so it travels in the file, never as an argument. |
+| `step --id <phase> --status <pending\|active\|done\|skipped\|failed> [--note "<text>"]` | At every phase boundary. Marking a phase `active` closes any previous one. |
+| `set --section <name> --json '<object>'` or `--json-file <path>` | When a decision is made. Merges, so a later step can add to a section. |
+| `step --id <phase> --status failed --note "<what stopped it>"` | Before surfacing any unrecoverable STOP. Best-effort like the rest: if it fails, still stop. |
+| `phone --stage building\|screens\|qr` | Moves the plan's phone through its three stages: the building animation, the screen carousel at Step 6.75, and the Metro QR at Step 12. |
+
+**Open the plan in the user's browser as soon as `init` creates it**, with the host's file opener
+or `open` / `xdg-open` / `cmd /c start ""` on the quoted path. A plan the user never sees is a plan
+that only ever existed as terminal text, and terminal text scrolls away during a long run. Opening
+it once is enough: the page reloads itself as each phase lands.
+
+**Phases** (`--id`): `requirements`, `architecture`, `data-model`, `screen-plan`, `scaffold`,
+`design`, `auth`, `dataverse`, `capabilities`, `screens`, `run`. Any other id is rejected by name.
+
+**Write each gated section into the plan *before* asking for approval**, with `--state proposed`,
+then flip it to `--state approved` once the user says yes. The plan is already open in their
+browser, so a rendered ER diagram or screen graph is what they answer the gate against. Recording
+the decision afterwards means approving from terminal text and seeing the picture only once it is
+too late to change it.
+
+Step 3's Architecture gate lists every gate with its phase and section. The Gate 2 calls below are
+the pattern each one follows:
+
+```bash
+DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
+# 1. propose - the tab shows "Proposed - review this, then answer the prompt in your terminal"
+node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state proposed
+node "$DOCS" --working-dir "<working_dir>" step --id data-model --status active --note "Gate 2 — awaiting your approval"
+# 2. point the user at that tab, then ask the gate question
+# 3. on approval
+node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state approved
+node "$DOCS" --working-dir "<working_dir>" step --id data-model --status done --note "Gate 2 — approved"
+```
+
+Pass a fresh `--note` when you close a gate. A note belongs to the status it was written with, so
+changing status without one clears it rather than leaving "awaiting your approval" under a step the
+user has already approved.
+
+If the user asks for changes, rewrite the section with `--state proposed` again and re-ask. The
+page reloads itself, so they see the revision without touching anything.
+
+**Record each other section as soon as it is known** — not in a batch at the end, or an abort
+leaves a plan that explains nothing:
+
+| Section | Written at | Contents |
+|---|---|---|
+| `environment` | Step 1, confirmed Step 4 | `displayName`, `environmentId`, `environmentUrl`, `tenantId`, `publisherPrefix` |
+| `requirements` | Steps 2 and 2b | `appName`, `slug`, `platforms`, `aesthetic`, `industry`, `brief`, `features[]` |
+| `architecture` | Gate 1 | `dataPlatform`, `nativeCapabilities[]` and `connectors[]` as `{ name, reason }` — a bare name cannot be approved or rejected, the reason is the decision |
+| `dataModel` | Gate 2 | `connectorOnly` when there are no tables; otherwise `tables[]` with `logicalName`, `displayName`, `status` (`new`/`reused`/`modified`, or the plan's `create`/`reuse`/`extend`), `purpose` (what it holds), **`reason` (why it is created, reused or extended)**, `columns[]` (`logicalName`, `displayName`, `type`, `key: PK\|FK`), `relationships[]` (`relatedTable`, `name`, `cardinality`) |
+| `offline` | Gate 2 | `enabled`, `mode`, `tables[]`, `rationale` |
+| `screens` | Gates 3 and 4 | `navigation`, `list[]` with `name`, `route`, `purpose`, `data`, `capabilities[]` |
+| `design` | Step 6.75 | `direction`, `headingFont`, `bodyFont`, `darkMode`, `palette[]` (`name`, `value` as `#rrggbb`). Use the real family names from [`typography-and-tone.md`](${PLUGIN_ROOT}/shared/references/typography-and-tone.md) (`Inter`, `JetBrains Mono`, …) — the plan renders each name in the typeface it names, so a label that is not a real family shows as the fallback. |
+| `auth` | Step 7 | `status` |
+| `trust` | Step 10, after capabilities and connectors are wired | `permissions[]` (`name`, `status` as one of the acquisition patterns below, **`detail`: when access is requested and why**), `handles[]`, `notCollected[]`, `battery[]` (`name`, `detail`) |
+
+The ER diagram is **built from `dataModel.tables`**, so populate the structured fields rather
+than only a Mermaid string — that is what makes the diagram, the column tables, and the
+new/reused/extended colouring agree with each other.
+
+**Every reuse, create and extend decision needs a `reason`.** "Reusing `account`" is not
+reviewable; "Reusing `account` — sites are already maintained there by the service desk, and a
+second Site table would drift" is. Write the reason the architect actually used, including what
+was rejected, since that is what the user is being asked to approve at Gate 2.
+
+**Use `--json-file` for anything the user wrote.** Size is not the test — an app called
+`Dave's Rounds` is enough. A value interpolated into a single-quoted shell argument ends that
+quoting at the first apostrophe, which at best corrupts the JSON and at worst leaves whatever
+follows to the shell. App names, briefs, feature lists, table reasons and design directions are
+all user-authored, so they are written to a file with the `Write` tool and passed by path.
+
+`--json` inline is for values this skill controls end to end, such as a fixed status string.
+
+**Every one of these calls is best-effort.** If `app-docs.js` fails, say nothing and carry on:
+the documentation must never gate, retry, or fail a build.
+
+**Mark the phase `failed` before you stop.** Every STOP in this skill is a terminal state the
+user has to act on, and the plan is probably still open in their browser. Without this the last
+phase stays `active`, so the page keeps reloading and keeps reporting work in progress on a run
+that ended. A failed phase settles the page, so the final thing it shows names what stopped.
+
+**No argument switches this protocol off.** `--no-design` suppresses design previews and
+`--no-preview` does not exist (Step 2c). The plan is how an abandoned or failed run explains
+itself, so it is written on every path.
+
+---
+
### Step 0 — Resume check + fresh-template gate
**Telemetry checkpoint: `validate_fresh_template`**
@@ -84,6 +186,15 @@ If `$ARGUMENTS` includes a `--working-dir` (or the user names an existing direct
- **Bank present** → read it. Identify the highest-numbered completed step. Inform the user:
> "Found existing project '<name>' at `<dir>`. Steps 1–<N> already completed (last update <date>). Resume from Step <N+1>?"
Wait for confirmation. If the user says yes, jump to that step. Skip the wizard (Step 2) and re-use the values stored in the bank.
+
+ **Reopen the build plan on resume.** A resume skips Step 2b, where the plan is created and
+ opened, so open `<working_dir>/docs/create-app-plan.html` in the browser yourself when it exists.
+ If the earlier run stopped on a failure, the plan still says so and has stopped reloading. Run
+ `node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" show`, and if it reports a `failedPhase`, reopen that phase before continuing:
+
+ ```bash
+ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id <failedPhase> --status active
+ ```
- **Bank absent** → fresh project. Continue to Step 1.
- **Bank present but corrupted** (missing required headings) → surface the parse error, ask the user whether to overwrite (lose history) or fix manually before proceeding.
@@ -256,13 +367,32 @@ Don't enter plan mode here — that's the planner agent's job in Step 3.
### Step 2b — Requirements discovery
+Create the plan now that the display name is known, and open the first phase. Write
+`<tmp>/plan-init.json` with the `Write` tool first — the display name is the user's own text, and
+a `"`, a backtick or `$(…)` in it would break out of a shell argument before Node saw it:
+
+```json
+{"appName":"<displayName>","dataPlatform":"unknown"}
+```
+
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" init --json-file <tmp>/plan-init.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Waiting for your answers to the setup questions"
+```
+
+The note is what raises the waiting-for-input banner on the plan, so the user can tell from the page
+that the run is blocked on them rather than still working. **Set one whenever you are about to ask a
+question and the answer gates the run.** It clears itself on the next status change, so there is
+nothing to remember to take down.
+
> **Goal:** Turn the user's thin prompt into a confirmed feature brief before the planner runs. The planner agent receives this brief verbatim — richer input means better data model inference, accurate connector detection, and correct screen specs.
#### Step 2b.0 — Prompt richness scoring (decides which path to take)
Before asking anything, score the description on four signals. The score decides whether we ask a multi-select feature picker, a single confirmation, or skip the discovery question entirely.
-Run this scorer mentally on `<description>` (the prompt the user gave with `/create-mobile-app`, plus any clarifying text from Step 2a). Count how many of the four trip:
+Run this scorer mentally on `<description>` (the prompt the user gave with `/create-mobile-app`, plus any clarifying text from Step 2). Count how many of the four trip:
| Signal | Trips when |
|---|---|
@@ -314,7 +444,7 @@ Skip the multi-select question. Extract a 6–10 bullet brief directly from `<de
- `yes` → store as `<requirements_brief>`, fall through to Step 2c.
- `adjust` → drop to Step 2b.1 (walk-through) so the user can edit via the multi-select.
-- `start over` → return to Step 2a and re-prompt for the description.
+- `start over` → return to Step 2 and re-prompt for the description.
#### Step 2b.3 — Auto-plan path (tier = `auto-plan`)
@@ -360,14 +490,29 @@ planning degradation; it never relaxes `/add-dataverse` reconciliation.
Set tentative defaults (the preview preference applies at Step 6.75):
-- `<visual_companion> = yes` — automatically open `_plan_preview.html` in the browser at Step 6.75, after the design choice. Gate 4 remains markdown-only regardless of this preference. `/design-system` may change it to `no`; persist the final value to memory-bank for future runs.
+- `<visual_companion> = yes` — render `_plan_preview.html` at Step 6.75, after the design choice. **Nothing is opened in a browser during a create run**, whatever this is set to: the build plan shows the same screens in its phone frame and links out to the file, and every opener in `/design-system` and its style picker is gated on `CODE_APPS_NATIVE_ORCHESTRATING=1`, which this skill passes. The flag governs `/preview-screens` wherever it runs — including the Step 11.4 offer, which is a browser window the user asked for by picking (a) or (b), not one that appears on its own — and a later `/edit-app` re-plan. Gate 4 remains markdown-only regardless. `/design-system` may change it to `no`; persist the final value to memory-bank for future runs.
- `<design_vibe_opt_in> = deferred` — Step 6.75 sets the real value. While `deferred`, the planner does NOT prompt for a direction; it writes a placeholder `## Design Direction: <deferred — set by /design-system>` block so screen-planner can still run.
**`--no-design` escape hatch.** For headless / token-constrained runs, set `--no-design` in `$ARGUMENTS`. It forces `<visual_companion> = no`, skips the style-picker handoff at Step 3a entirely, and short-circuits Step 6.75 to a no-op (placeholder block stays in `native-app-plan.md`; screen-builders fall back to industry-inferred defaults).
+**Record the confirmed brief.** The phase stays open: Step 2c still asks the user to approve the
+plan preview, and a closed phase cannot report that the run is waiting on them.
+
+Write `<tmp>/requirements.json` with the `Write` tool first — every value here came from the user,
+and none of it may go through the shell:
+
+```json
+{"appName":"<displayName>","slug":"<slug>","platforms":"iOS and Android","aesthetic":"<aesthetic>","industry":"<industry>","brief":"<confirmed brief>","features":["<feature>"]}
+```
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section requirements --json-file <tmp>/requirements.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Brief confirmed"
+```
+
### Step 2c — Plan preview (rough, always shown)
-> **Goal:** Give the user a cheap exit before any mutation happens. This is the **last point** in the flow with zero side effects — no `git clone`, no `npm install`, no `npx power-apps init`, no agent tokens spent on planning. After Step 3 starts, every abort gets more expensive (half-written `native-app-plan.md`, partial `_screens_section.md`, architect tokens already burnt).
+> **Goal:** Give the user a cheap exit before any mutation happens. This is the **last point** before the run touches the app itself — no `npx power-apps init`, no Dataverse writes, no agent tokens spent on planning. The one thing already written is the build plan under `docs/`, which Step 2b created so the user has something to read while answering; an abort here leaves that folder and nothing else. After Step 3 starts, every abort gets more expensive (half-written `native-app-plan.md`, partial `_screens_section.md`, architect tokens already burnt).
**Always runs. There is no `--no-preview` flag in v0** — we need calibration data (~10+ runs with recorded estimate-vs-actual) before we can trust the rough estimates enough to let users skip them. Once the data shows estimates are reliably within ±50%, evaluate adding a skip flag for repeat-user workflows.
@@ -428,6 +573,14 @@ Proceed, edit brief, or abort? [proceed/edit/abort]
- Forced calibration: every run produces the `<estimate, actual>` data we need for v0.x model routing decisions. Skipping drops calibration data.
**Set expectations before handing off to the planner:**
+Raise the wait before showing the estimate, and close the phase once the user approves:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status active --note "Waiting for you to approve the plan preview"
+# ... after they approve ...
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id requirements --status done
+```
+
> "Brief locked in. Planning surfaces up to 4 approval prompts (data platform + native capabilities + connectors → data model when Dataverse is selected → screen graph → screen specs). Data-model readiness is quality-first, with a 10–15 minute target:
> • Gate 1 (architecture) — confirm Dataverse choice, native capabilities, and connectors before schema work
> • Gate 2 (data model, Dataverse only) — budget 10–15 min for verified reuse/extend/create decisions, ER columns, relationships, tiers, and risks; auto-skipped for no-Dataverse apps
@@ -457,8 +610,44 @@ First, create the working and planning-artifact directories:
mkdir -p <working_dir> <working_dir>/.tmp
```
+
### Architecture gate
+Planning is now the live phase. Open it with what the run is doing rather than with a question:
+between gates the agents work for minutes, and the plan must not tell the user the run is waiting
+on them while it is not.
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id architecture --status active --note "Planning the architecture"
+```
+
+**Raise every gate in the plan as you present it, and take it down as soon as it is answered** -
+here, in the inline fallback below, and in every revision loop. The plan is open in the user's
+browser, and its banner is how they can tell the run is waiting on them rather than still working.
+
+| Gate | `--id` | Section written first, `--state proposed` | Once approved, open next |
+|---|---|---|---|
+| 1 - architecture | `architecture` | `architecture` | `data-model`, note "Designing the data model" (`connector-only`: `screen-plan`, note "Planning the screens") |
+| 2 - data model, `required` only | `data-model` | `dataModel`, and `offline` when the plan has one | `screen-plan`, note "Planning the screens" |
+| 3 - screen graph | `screen-plan` | `screens` | `screen-plan`, note "Writing the screen specs" |
+| 4 - screen specs | `screen-plan` | `screens` | nothing - Step 3.9 closes the phase |
+
+```bash
+DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
+# Just before presenting gate <N>:
+node "$DOCS" --working-dir "<working_dir>" set --section <section> --json-file <tmp>/<section>.json --state proposed
+node "$DOCS" --working-dir "<working_dir>" step --id <id> --status active --note "Gate <N> — awaiting your approval"
+# As soon as the user approves it:
+node "$DOCS" --working-dir "<working_dir>" set --section <section> --json-file <tmp>/<section>.json --state approved
+node "$DOCS" --working-dir "<working_dir>" step --id <next id> --status active --note "<note from the table>"
+```
+
+Flip each section to `approved` when its gate is answered, not later in the Step 3.9 batch. A
+section left `proposed` while the next phase works reads as a question nobody is asking. The
+architecture-only planner pass does nothing but present Gate 1, so raise Gate 1 before dispatching
+it. When the planner's completion pass presents Gates 2-4 itself, the plan cannot see inside it and
+keeps its progress note until the result comes back.
+
Run the planner once in architecture-only mode before any Dataverse discovery:
```
@@ -1167,6 +1356,44 @@ Adapt from `core` or missing detail, or Create/Adapt names without
checked-missing collision evidence. Do not fall back to parsing the Markdown
ER diagram when a sidecar is missing or malformed.
+### Step 3.9 — Confirm the approved plan
+
+Each gated section was written `proposed` before its gate and flipped to `approved` when the user
+answered it (the gate table under the Architecture gate). Restate them here, before any mutation
+starts, so a call missed at a gate cannot leave a proposal on record and an abort still leaves a
+document explaining what was agreed:
+
+```bash
+DOCS="${PLUGIN_ROOT}/scripts/app-docs.js"
+node "$DOCS" --working-dir "<working_dir>" set --section architecture --json-file <tmp>/architecture.json --state approved
+node "$DOCS" --working-dir "<working_dir>" step --id architecture --status done --note "Gate 1 — approved"
+node "$DOCS" --working-dir "<working_dir>" set --section trust --json-file <tmp>/trust.json --state proposed
+node "$DOCS" --working-dir "<working_dir>" set --section dataModel --json-file <tmp>/data-model.json --state approved
+node "$DOCS" --working-dir "<working_dir>" step --id data-model --status done --note "Gate 2 — <n> tables approved"
+node "$DOCS" --working-dir "<working_dir>" set --section screens --json-file <tmp>/screens.json --state approved
+node "$DOCS" --working-dir "<working_dir>" step --id screen-plan --status done --note "Gates 3-4 — <n> screens approved"
+```
+
+**Write a first-pass trust report here.** Gate 1 settles the device capabilities and connectors,
+which is everything the `permissions[]` and `battery[]` lists are derived from, so the Trust report
+tab fills as soon as the user approves rather than staying empty for most of the run. Mark it
+`proposed`: it states what the approved plan intends, and Step 10 rewrites it as `approved` once
+the capabilities are actually wired. Leave `handles[]` and `notCollected[]` out for now — those
+depend on the data model and offline profile, which are not settled yet.
+
+Build each JSON from the approved `native-app-plan.md` using the shapes in the
+[Build documentation protocol](#build-documentation-protocol). Populate `dataModel.tables[]`
+structurally — `logicalName`, `status`, `columns[]` with `key: PK|FK`, `relationships[]` — because
+the ER diagram, the column tables, and the new/reused/extended colours are all derived from it.
+
+**Connector-only apps:** mark both Dataverse phases as not applicable rather than leaving them
+pending, or the plan never reaches 100%:
+
+```bash
+node "$DOCS" --working-dir "<working_dir>" step --id data-model --status skipped
+node "$DOCS" --working-dir "<working_dir>" step --id dataverse --status skipped
+```
+
### Step 4 — Auth & environment selection
**Telemetry checkpoint: `select_app_environment`**
@@ -1181,6 +1408,12 @@ If the resolved environment doesn't match what the planner used in Step 3, ask t
**Telemetry checkpoint: `prepare_template_files`**
+Open the scaffold phase:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id scaffold --status active
+```
+
This step is template-only and foreground-only. Do not clone/copy templates, do not run background scaffold jobs, and do not use any legacy fallback path.
**Print before starting:**
@@ -1420,6 +1653,12 @@ npx tsc --noEmit
This is the **Scaffold gate** from the TypeScript Gate Policy. If it fails, capture the full error list once, batch-fix scaffold/template causes, and rerun this gate. Do not continue to Step 6.7 or any app-specific mutation until this gate is clean. If the only failure is a missing generated schema import, preserve the template `@ts-ignore` boundary rather than generating an empty schema artifact.
+A clean scaffold gate is what completes the scaffold phase:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id scaffold --status done
+```
+
### Step 6.7 — Seed the memory bank
```bash
@@ -1449,19 +1688,48 @@ visual_companion: <yes|no> # default from Step 2b; applied at Step 6.75 and la
**Print before starting:**
> "→ [Step 6.75/13] Locking your design system — source of truth for every screen built next. Takes 5 sec to 3 min depending on path."
-**Skip this step if `--no-design` is in `$ARGUMENTS`** — placeholder `## Design Direction: <deferred>` block stays in the plan, screen-builders fall back to industry-inferred defaults from `universal-patterns.md`.
+**Skip this step if `--no-design` is in `$ARGUMENTS`** — record it as skipped rather than leaving
+it open, because this branch never reaches the `done` call below:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status skipped
+```
+
+Marking it `active` here instead would leave it active through auth and most of Step 8, until
+opening the next phase auto-closed it as `done` — reporting a design system that was never built.
-**Otherwise**, invoke `/design-system` (ships with this plugin):
+**On the skip branch** — placeholder `## Design Direction: <deferred>` block stays in the plan, screen-builders fall back to industry-inferred defaults from `universal-patterns.md`.
+
+**Otherwise**, open the phase and invoke `/design-system` (ships with this plugin). `/design-system`
+asks for brand inputs, a cost choice and a style pick, so the phase opens as waiting:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status active --note "Waiting for your brand and design choices"
+```
```
Invoke skill: /design-system
+Environment:
+ CODE_APPS_NATIVE_ORCHESTRATING=1
+
Arguments:
--working-dir <working_dir>
```
+The `Environment` block is load-bearing, and follows the nested-skill handoff `/edit-app` already
+uses. `/design-system` and its style picker gate every browser opener on that variable; without it
+they detect a standalone run and open tabs over the build plan.
+
The skill detects orchestrator mode (`CODE_APPS_NATIVE_ORCHESTRATING=1`), collects brand inputs, presents the cost picker (a/b/c/d), runs the internal style picker, writes `brand/design-system.md` + `brand/tokens.ts`, renders `brand/design-system.html`, and returns with status.
+As soon as `/design-system` returns, replace the note — the user has answered and the run is
+working again:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status active --note "Applying your design system"
+```
+
Handle the return per the status protocol (AGENTS.md rule #10):
- `DONE` → finish the applicable preview branch below, then continue to Step 7. Record `brand_path`, `tokens_path`, `direction` in memory-bank.
- `DONE_WITH_CONCERNS` → surface concerns, ask user, continue.
@@ -1474,7 +1742,7 @@ If the user picked path (c) Skip in the cost picker, the skill returns immediate
#### Branch A — `brand/` files exist (user picked path a, b, or d)
-This is the **FIRST and ONLY HTML preview** the user sees in the new flow — Gate 4 was a structural-only review (markdown screen-graph, no HTML). `/design-system` owns rendering of `_plan_preview.html` at its Sub-step 6.5 using the locked brand tokens. No re-spawn from the orchestrator is needed; the preview is fresh when the skill returns.
+`/design-system` owns rendering of `_plan_preview.html` at its Sub-step 6.5 using the locked brand tokens — no re-spawn from the orchestrator is needed, the file is fresh when the skill returns. Gate 4 was a structural-only review (markdown screen-graph, no HTML), so this is where screens first become visual. The user sees them in the build plan's phone carousel, and the rendered file is linked underneath it. Nothing opens a browser window: `/create-mobile-app` sets `CODE_APPS_NATIVE_ORCHESTRATING=1`, and every opener in `/design-system` and its style picker is gated on that, so the plan stays the single surface the user is watching.
#### Branch B — Skip path preview (user picked path c — no `brand/` files)
@@ -1485,13 +1753,11 @@ The user skipped the design system but still deserves to see their screens befor
2. **Render `_plan_preview.html`** — read the screen specs from `native-app-plan.md` `## Screens` section and render key screens (one List + one Form + one Detail, first match per archetype) using the `tamagui-html-mapping.md` reference and industry-inferred defaults from `## Design Direction`. Write to `<working_dir>/_plan_preview.html`.
-3. **Print the preview path; open in browser only if `<visual_companion> = yes`:**
- ```bash
- open "<working_dir>/_plan_preview.html" 2>/dev/null \
- || xdg-open "<working_dir>/_plan_preview.html" 2>/dev/null \
- || powershell.exe -NoProfile -Command "Start-Process '<working_dir>\_plan_preview.html'" 2>/dev/null \
- || true
- ```
+3. **Do not open it in a browser.** The build plan already shows these screens in its phone
+ frame and links out to the full-size file underneath, so a second tab opening mid-run
+ interrupts the user rather than telling them anything new. Print the path and continue:
+
+ > `→ Full-size screens at <working_dir>/_plan_preview.html (also linked under the phone in the build plan).`
4. **Auto-continue — no prompt.** The user already approved the applicable planning gates; the preview does not introduce another approval gate. Print one line and proceed:
@@ -1506,10 +1772,63 @@ Offline profile setup is intentionally deferred until after the approved
Dataverse model has been materialized. Follow the shared connectivity-intent
ownership contract during this phase.
+**Switch the plan's phone to the screen carousel.** `/design-system` has just rendered
+`_plan_preview.html` — plan-time mockups built from the locked brand tokens, before a single line
+of TSX exists. Those same per-screen blocks become the carousel:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" phone --stage screens --screens-file <tmp>/screens-preview.json
+```
+
+`screens-preview.json` is `[{ "name": "Today's route", "html": "<the screen's markup>" }, …]`, in
+navigation order.
+
+**Carry over exactly the screens `_plan_preview.html` contains — no more, no fewer.** How many
+that is depends on what the user chose at `/design-system` Sub-step 6.5: option (a) renders every
+screen, and the default (b) renders only the List, Form and Detail archetypes. Take the markup
+from those blocks rather than re-authoring any of it: a hand-written block would drift from
+`_plan_preview.html` and from the screen the builder later generates, which is the one thing the
+carousel exists to rule out. A three-screen carousel is the expected shape, not a failure.
+
+**When there is no preview to carry over, leave the phone on the building animation.** That is
+`--no-design`, or Sub-step 6.5 option (c) "Skip preview" — in both cases `_plan_preview.html` was
+never written, so there is nothing to show and nothing to invent. Skip the `phone --stage screens`
+call entirely; the plan keeps animating until the Step 12 QR replaces it.
+
+**This is the moment the plan stops being abstract** — the user sees real screens, in their real
+brand, while the data model is still being built. Do not skip it because they are "only mockups":
+they are the same mockups `/preview-screens` would produce, and they are the first concrete thing
+in the whole run.
+
+**Record the design** once `/design-system` returns, taking the palette from `brand/tokens.ts`.
+Write `<tmp>/design.json` with the `Write` tool — the direction is free text the user chose, so it
+goes to a file rather than through the shell:
+
+```json
+{"direction":"<direction>","headingFont":"<font>","bodyFont":"<font>","darkMode":"<enabled|disabled>","palette":[{"name":"Primary","value":"#rrggbb"}]}
+```
+
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section design --json-file <tmp>/design.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id design --status done
+```
+
+Only `#rrggbb` literals render as swatches; any other value is shown as text rather than
+becoming an arbitrary CSS value.
+
### Step 7 — Auth config
**Telemetry checkpoint: `configure_native_authentication`**
+This step asks the user for an app registration, so it opens as waiting. Without a phase of its
+own the plan showed nothing in progress here at all: the design phase closes before it and the
+Dataverse phase does not open until Step 8.
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id auth --status active --note "Waiting for your Entra ID app registration"
+```
+
**Print before starting:**
> "→ [Step 7/13] Configuring app authentication (Entra ID app registration)…"
@@ -1705,6 +2024,16 @@ Print:
Do NOT touch `src/playerConfig.ts` — auth identifiers live in `auth.config.json` only.
+Close the auth phase once the client ID is written and the config is in place:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section auth --json-file <tmp>/auth.json
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id auth --status done
+```
+
+`auth.json` is `{"status":"<Configured — how sign-in was set up|Deferred — why>"}`. It goes to a
+file like every other section: the status text can quote a registration name the user supplied.
+
### Step 8 — Apply data model
**Telemetry checkpoint: `apply_dataverse_data_model`**
@@ -1716,6 +2045,13 @@ skip sample data and offline-profile setup, print
`↷ Offline profile skipped — no Dataverse tables in this app.`, and continue to Step 9. A non-empty Dataverse plan in
this mode is a planning mismatch and must be corrected before continuing.
+Otherwise open the Dataverse phase now. Creating tables is one of the longest waits in the run, and
+with no phase open the plan reads "Waiting to start" through all of it:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status active
+```
+
**Print before starting:**
> "→ [Step 8/13] Preparing the approved Dataverse operation manifest, then invoking /add-dataverse for sequential metadata writes and service generation. Dataverse write time varies by environment; local manifest preparation is deterministic, not a wall-clock promise."
@@ -1908,7 +2244,13 @@ Skip only when `memory-bank.md` `## Offline profile` already records
`status: done` or `status: not-applicable`. Print:
`↷ Offline profile skipped — already <done|not-applicable> from a prior run.`
-Otherwise ask one neutral foreground question:
+Otherwise ask one neutral foreground question. Say so in the plan first, and replace the note
+once the user answers:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status active --note "Waiting for your offline support choice"
+```
+
> **Question header:** `Offline support`
>
@@ -1929,10 +2271,22 @@ It consumes the materialized manifest, owns its own profile approval flow, and
writes `offline-profile.json`. Surface concerns and stop on a substantive
failure. Do not reopen data-model or screen approvals after this choice.
+Tables and generated services now exist, so the Dataverse phase is complete:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id dataverse --status done
+```
+
### Step 9 — Apply native capabilities
**Telemetry checkpoint: `configure_native_capabilities`**
+Open the capabilities phase; Step 10 closes it after connectors are added:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id capabilities --status active
+```
+
**Print before starting:**
> "→ [Step 9/13] Wiring <N> native capabilities: <list>. Each runs sequentially."
@@ -2057,10 +2411,79 @@ Run sequentially — each generates files under `src/generated/`. Parallel write
**Mutation-heavy steps stay sequential.** Dataverse table creation (Step 8), connector adds (Step 10), and generated-service writes are all sequential by design. The fast path in this skill is **parallel screen generation** (Step 11) plus **fewer prompts** (token cache, sticky policies, auto-proceed) — NOT parallelizing the data-source/service mutations. Do not attempt to parallel-batch `npx power-apps add-data-source` or `/add-connector` invocations; they share `src/generated/` and `power.config.json` and will race or corrupt state.
+Device capabilities and connectors are both wired, so close the phase:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id capabilities --status done
+```
+
+**Finalise the trust report.** Gate 1 wrote a first pass from the approved plan; everything it
+claimed is now decided — which capabilities were actually wired, which connectors were added, and
+what the offline profile syncs. Rewrite it in full and mark it `approved`, so it describes what the
+app *does* rather than what was intended. `set` merges, so restate every key you want to change.
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" set --section trust --json-file <tmp>/trust.json --state approved
+```
+
+`trust.json` has four keys:
+
+- **`permissions[]`** — one entry per OS permission the app could plausibly touch, **including the
+ ones it never asks for**. `{ "name", "status", "detail", "activation" }`. A report that lists only
+ what was granted answers the easy question; "Microphone — NOT REQUESTED — no audio workflow exists
+ anywhere in the app" is the one a reviewer actually needs.
+
+ `status` names **how the permission is acquired**, not merely whether it is. Two apps can end up
+ with the same grant and be nothing alike — asking at first launch and asking when the user taps
+ Scan are different postures. Use one of:
+
+ | `status` | When the prompt happens | Typical example |
+ |---|---|---|
+ | `on-demand` | Explicitly requested when the user invokes the feature | Camera, after tapping Scan |
+ | `on-startup` | Explicitly requested during launch or onboarding | Notifications at first launch. Technically fine, usually discouraged — prefer `on-demand` |
+ | `on-first-access` | The OS prompts automatically the first time the app touches the API | Core Bluetooth initialization on Apple platforms |
+ | `per-operation` | Authorized every time, with no lasting grant | Face ID / Touch ID |
+ | `incremental` | Narrow access first, broader only when justified | Foreground location now, background later |
+ | `system-settings` | No normal dialog exists, so the app sends the user to Settings | Android overlay or all-files access |
+ | `system-mediated` | The OS hands over just the selected data, granting nothing broader | The iOS/Android photo picker |
+ | `not-requested` | Never asked for at all | Microphone in an app with no audio workflow |
+
+ Anything unrecognised renders as `not-requested`, so a wrong value understates rather than
+ overstates access. Prefer the **narrowest accurate** pattern: if the OS picker gives you the one
+ file you need, that is `system-mediated` and not a library permission.
+
+ `detail` must say **when** the request happens and **why** — "Requested when the technician starts
+ photo capture on a work order", not "Used for photos". `activation` is optional and records the
+ separate question of **when the hardware actually runs**: holding a camera grant is not the same
+ as the lens being on, and a reviewer needs both.
+
+ **Do not claim the permission is absent from the build.** The binary is produced from a signed
+ pre-built base and `/add-native` may not edit `app.config.js`, so the declared permission set is
+ the wrapper's and is the same for every generated app. Least privilege here is a **runtime**
+ property — which permissions this app ever requests and which hardware it ever activates — not a
+ manifest one. Say "no screen requests it", never "the OS cannot prompt for it".
+- **`handles[]`** — the record types and identity data the app actually reads or writes.
+- **`notCollected[]`** — what it deliberately does not touch. Be specific: name the field classes a
+ reader would otherwise have to assume about.
+- **`battery[]`** — `{ "name", "detail" }` for each background-cost decision: polling, sensor
+ subscriptions, sync intervals, and anything that runs off-screen.
+
+Derive every entry from the approved `native-app-plan.md`, `offline-profile.json`, and the
+capabilities you just wired. **Do not claim a boundary you have not checked** — an unverified "no
+location access" is worse than omitting the line, because the plan is the artifact a reviewer
+trusts. Capabilities the user declined at Gate 1 belong here as `not-requested`.
+
### Step 10b — Wire navigation layout
**Telemetry checkpoint: `wire_app_navigation`**
+Open the screens phase here rather than at the first screen wave. Navigation, shared code and the
+first wave are most of what is left of the run, and the plan should say what is being built:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active
+```
+
Read `## Screens → Navigation Pattern` from `native-app-plan.md`.
- **Stack** — skip. `app/(app)/_layout.tsx` already renders `<Stack>`. Nothing to do.
@@ -2568,6 +2991,15 @@ After handling every builder status in the wave, run the **Screen-wave gate** be
npx tsc --noEmit
```
+**Mark screen progress in the plan** once the wave's TypeScript gate is clean:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active --note "<n> of <total> screens built"
+```
+
+The plan's phone is already showing the screen carousel from Step 6.75, so there is nothing to
+re-point here — only the count to keep honest.
+
If the wave gate fails, capture the full error list once, group failures by root cause, and repair in batch. For screen-owned files, re-spawn the affected screen-builder(s) with the consolidated TypeScript output appended to their prompts. Affected builders can be re-spawned in parallel. Cap retries at 2 per screen, then surface the failure to the user. Do not launch the next wave until the current wave gate is clean.
Common wave-gate repair classes to batch instead of fixing line-by-line:
@@ -2649,7 +3081,13 @@ Then continue only if TypeScript is clean. Step 11.4 may leave concerns, but it
#### Optional static preview
-After `tsc` passes, offer a static HTML preview. The dev server starts next (Step 12), so default is skip:
+After `tsc` passes, offer a static HTML preview. The dev server starts next (Step 12), so default is skip.
+Mark the wait, since the run does not continue until the user picks:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status active --note "Waiting for your preview choice"
+```
+
> "→ N screens built and type-checked. The live app starts next.
>
@@ -2667,6 +3105,12 @@ After `tsc` passes, offer a static HTML preview. The dev server starts next (Ste
---
+Every screen is built and type-checked, so close the screens phase:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id screens --status done
+```
+
### Step 12 — Start dev server (Metro writes project-local logs)
**Telemetry checkpoint: `launch_metro_dev_server`**
@@ -2674,6 +3118,12 @@ After `tsc` passes, offer a static HTML preview. The dev server starts next (Ste
**Print before starting:**
> "→ [Step 12/13] Launching Metro so you can scan the QR; logs will be written under .powernative/."
+Open the final phase (Step 13 marks it done):
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id run --status active
+```
+
This skill launches the template's canonical `npm run dev` command. Its `predev` lifecycle runs schema generation followed by the final TypeScript gate before Expo starts, and logging is configured in `metro.config.js`.
1. Expo prints the native Metro URL and may also render a QR in its terminal. Capture the URL and generate the QR PNG below so the user always receives a scannable code even when Metro runs in a background terminal or the host does not expose terminal rendering.
@@ -2719,12 +3169,12 @@ Branch as follows:
- Define `METRO_QR="<working_dir>/.expo/metro-qr.png"` and run `npx --yes qrcode -o "$METRO_QR" "<metro-url>"`. If the project's npm config requires auth and the fetch fails with `E401`, retry once with `npm_config_registry=https://registry.npmjs.org/ npm_config_always_auth=false` prefixed.
- Verify the PNG with a host-neutral Node check: `node -e "const fs=require('node:fs'); process.exit(fs.existsSync(process.argv[1]) ? 0 : 1)" "$METRO_QR"`. If it fails, print the qrcode error and continue without the image.
- **Chat-first render (best effort):** read and base64-encode the file with Node (`node -e "process.stdout.write(require('node:fs').readFileSync(process.argv[1]).toString('base64'))" "$METRO_QR"`) and embed in markdown as a data URI (`![QR](data:image/png;base64,<data>)`) so hosts that support inline image markdown show the QR directly in chat.
- - **Guaranteed visible fallback:** if inline chat image rendering is unavailable, use the host's file-open tool when present. Otherwise use the quoted OS command (`open "$METRO_QR"` on macOS, `xdg-open "$METRO_QR"` on Linux, or `cmd /c start "" "$METRO_QR"` on Windows). If opening fails, print the quoted path. Never interpolate an unquoted project path.
+ - **Guaranteed visible fallback: the build plan, not a new window.** If inline chat image rendering is unavailable, do **not** open the PNG with the host's file-open tool or an OS command. The plan already draws the QR in its phone frame and links the file underneath it for scanning full size, so a window opening on top of a run the user is watching adds nothing. Print the quoted path instead, and point at the plan. Never interpolate an unquoted project path.
- Surface only the native Metro URL immediately after the image/fallback message.
2. Follow with:
> "✓ Metro is running on port `<port>`.
- > 📱 Scan the QR code shown above (or opened from `<working_dir>/.expo/metro-qr.png`) with your native dev client to load the app. Metro URL: `<metro-url>`
+ > 📱 Scan the QR code shown above (it is also in the build plan, and at `<working_dir>/.expo/metro-qr.png`) with your native dev client to load the app. Metro URL: `<metro-url>`
> 🔄 Edits hot-reload automatically. Debug logs: `<working_dir>/.powernative/metro-logs/`."
**Persist only stable discovery paths to memory bank** so resumed sessions and downstream skills can find the session without coupling to a host terminal:
@@ -2738,6 +3188,16 @@ Branch as follows:
Do not persist PIDs, ports, or Metro URLs to the memory bank. They are ephemeral and are resolved from the latest `.powernative` log when needed.
+**Put the QR in the plan** so the document ends on the thing the user acts on:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" phone --stage qr \
+ --qr-image "<working_dir>/.expo/metro-qr.png" --qr-url "<metro-url>"
+```
+
+The PNG is inlined as a data URI, so the plan still shows the code after `.expo/` is cleaned. This
+is the phone's final stage: animation while building, the screen carousel once designed, then this.
+
After Step 12 starts the long-running server, continue through the optional Step 12.5 debug handoff and print the Step 13 summary, then return so the user can iterate locally. Production build + tenant push remains a separate, explicit user action via the `/deploy` skill.
### Step 12.5 — Optional debug handoff
@@ -2775,12 +3235,26 @@ Approval wait : <N ms> (excluded from agent performance)
Execution : scaffold <N ms or not recorded> | mutation <N ms or not recorded>
App Insights : <enabled for selected customer-owned resource | disabled>
Dev server : Metro running on port <port>
+Build plan : docs/create-app-plan.html
Debug logs : .powernative/metro-logs/
─────────────────────────────────────────────
```
+Close the build plan before printing the summary:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir "<working_dir>" step --id run --status done
+```
+
+Point the user at `docs/create-app-plan.html` once — it holds the environment, the approved data
+model with its ER diagram, and the screen plan, and it outlives the terminal session.
+
If Step 1 emitted warnings, list them in one line each under the block (no decoration).
+Do **not** re-open the `run` phase for these. The build is finished, the plan has settled and
+stopped reloading, and marking a phase active again would restart that loop and report work in
+progress on a run that is over. These options are a menu, not a gate the run is blocked on.
+
Then present exactly these 6 options:
```
diff --git a/plugins/mobile-apps/skills/design-system/SKILL.md b/plugins/mobile-apps/skills/design-system/SKILL.md
index e57e1b77a..9a96a081e 100644
--- a/plugins/mobile-apps/skills/design-system/SKILL.md
+++ b/plugins/mobile-apps/skills/design-system/SKILL.md
@@ -182,7 +182,7 @@ Persist choice to `memory-bank.md`: `visual_companion: <yes|no|skip>`
**Branches:**
- **(a)** → continue all sub-steps (Sub-steps 3–7) (~3 min)
- **(b)** → skip Sub-step 3 (style picker), run Sub-steps 4–7 (spec + gallery + confirmation)
-- **(c) Brand preview** → skip Sub-steps 3–6, render key screen mockups (List + Form + Detail) with brand tokens applied, open browser, proceed to Sub-step 7. No extra question about how many screens — always shows 3 key screens.
+- **(c) Brand preview** → skip Sub-steps 3–6, render key screen mockups (List + Form + Detail) with brand tokens applied, open browser (standalone runs only; otherwise print the path), proceed to Sub-step 7. No extra question about how many screens — always shows 3 key screens.
- **(c) Apply defaults / (d) — no-brand path** → skip Sub-steps 3, 5. Run these in order:
1. **Minimal Sub-step 4** — write `brand/tokens.ts` from the industry's direction preset.
**Source-of-truth lookup order for the preset bundle:**
@@ -192,7 +192,7 @@ Persist choice to `memory-bank.md`: `visual_companion: <yes|no|skip>`
4. As a last fallback, if the source file is unreadable, use the inspection direction inlined in [`references/design-system-schema.md`](./references/design-system-schema.md).
Skip the full `brand/design-system.md` write — only `brand/tokens.ts` is needed. Record the chosen source in `memory-bank.md` under `## Design`: `direction: polished-inspection (default — white + Power-Platform green, demo-friendly enterprise polish)` so future runs know what was picked.
- 2. **Mini-preview (Sub-step 6.5 lite)** — render exactly 3 screens (List + Form + Detail archetypes from the plan's `## Screens`; if fewer exist, render whichever do) using the same HTML preview template + Tamagui-to-HTML mapping as `screen-planner`, with `brand/tokens.ts` values substituted. Write to `<working_dir>/_design_preview.html`, open in browser. Print: `"→ Polished-inspection preview ready at file://<working_dir>/_design_preview.html — confirm the look (or re-run /design-system --direction <inspection|saas|product> to switch)."`
+ 2. **Mini-preview (Sub-step 6.5 lite)** — render exactly 3 screens (List + Form + Detail archetypes from the plan's `## Screens`; if fewer exist, render whichever do) using the same HTML preview template + Tamagui-to-HTML mapping as `screen-planner`, with `brand/tokens.ts` values substituted. Write to `<working_dir>/_plan_preview.html` — the canonical filename. `/create-mobile-app` takes its screen carousel from that file and the build plan links it, so writing anything else leaves both empty on this path. Open it in the browser on standalone runs only; in orchestrator mode print the path, because the build plan already links it. Print: `"→ Polished-inspection preview ready at file://<working_dir>/_plan_preview.html — confirm the look (or re-run /design-system --direction <inspection|saas|product> to switch)."`
3. **Return DONE** so Step 9b of the orchestrator picks up `brand/tokens.ts` and applies [`references/tamagui-integration.md`](./references/tamagui-integration.md) in brand-import mode.
**Never return DONE without writing `brand/tokens.ts`.** The label promises "applied defaults"; the implementation must deliver tokens AND a preview, otherwise the user has no way to verify the look short of waiting for full screen-builders + emulator boot. The preview is fast (HTML, no JS execution) and uses the same renderer Sub-step 6.5 uses for paths (a)/(b).
@@ -239,7 +239,7 @@ Before processing any external content, apply the sanitization rules from [`refe
Follow the internal style picker in [`references/vibe/style-picker.md`](./references/vibe/style-picker.md):
- Pass `working_dir`, `target_screen` (first List screen), `default_direction` (from industry)
-- The style picker renders `_design_vibe.html`, opens browser, asks user
+- The style picker renders `_design_vibe.html`, opens browser (standalone runs only — in orchestrator mode print the path instead), asks user
- Returns: picked direction name + merged bundle dimensions
If brand_notes or --logo palette exist, prepend banner showing inferred recommendation.
@@ -403,7 +403,7 @@ The HTML gallery includes:
Write to `brand/design-system.html`.
-**Open in browser:**
+**Open in browser — standalone runs only:**
```bash
open "brand/design-system.html" 2>/dev/null \
@@ -411,6 +411,12 @@ open "brand/design-system.html" 2>/dev/null \
|| echo "Preview at: file://$(pwd)/brand/design-system.html"
```
+**Orchestrator mode opens nothing.** When `CODE_APPS_NATIVE_ORCHESTRATING=1`, skip the opener and
+print the path instead. `/create-mobile-app` keeps a build plan open in the user's browser and
+links every file this skill writes, so a tab opening on top of a run they are already watching
+interrupts rather than informs. Run standalone, open as usual — there is no plan page then.
+
+
---
## Sub-step 6 — Confirmation gate
@@ -472,7 +478,7 @@ Go back to Sub-step 3 (counts against retry cap of 2).
**Rendering:** Use the same HTML preview template and Tamagui-to-HTML mapping as the screen-planner (`shared/references/tamagui-html-mapping.md`). Replace default token values with the locked `brand/tokens.ts` values (palette, typography, spacing, radius).
-**Path (c) "Brand preview":** Skip this question — automatically render key screens (List + Form + Detail) with brand tokens applied. If the plan has fewer than 3 archetypes, render whichever exist. Open browser. Proceed to Sub-step 7.
+**Path (c) "Brand preview":** Skip this question — automatically render key screens (List + Form + Detail) with brand tokens applied. If the plan has fewer than 3 archetypes, render whichever exist. Open the browser on standalone runs only (see below). Proceed to Sub-step 7.
**Paths (a) and (b):** Ask:
```
@@ -489,7 +495,13 @@ Re-render screen preview with your brand tokens?
- **(b)** → re-render List + Form + Detail archetypes only (whichever exist in the plan)
- **(c)** → skip, proceed to Sub-step 7
-Overwrites `_plan_preview.html` with branded versions. Opens browser.
+Overwrites `_plan_preview.html` with branded versions.
+
+**Orchestrator mode opens nothing.** When `CODE_APPS_NATIVE_ORCHESTRATING=1`, skip the opener and
+print the path instead. `/create-mobile-app` keeps a build plan open in the user's browser and
+links every file this skill writes, so a tab opening on top of a run they are already watching
+interrupts rather than informs. Run standalone, open as usual — there is no plan page then.
+
---
diff --git a/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md b/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
index 987b90eb9..92f46b492 100644
--- a/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
+++ b/plugins/mobile-apps/skills/design-system/references/vibe/style-picker.md
@@ -34,7 +34,7 @@ A self-contained moodboard-before-build reference for `/design-system`. Three na
1. Verify plan + pick the target screen
2. Pick the recommended default direction
3. Render 3-up `_design_vibe.html`
-4. Open in browser (with cross-platform fallback)
+4. Open in browser (standalone runs only; with cross-platform fallback)
5. Ask the user
6. Write `## Design Direction` block + return
@@ -295,7 +295,7 @@ This sets the expectation that hybrid is real, named, and supported — without
**8. Explicit dark/light toggle per frame.** Render a small `Light / Dark` toggle pill above each phone frame, and make the alternate state available via `?dark=1` URL params or a click handler that swaps the frame's classes. This is what prevents the "I picked dark for aesthetics → got pushed into Inspection" failure mode.
-## Step 4 — Open the preview in the user's browser
+## Step 4 — Open the preview in the user's browser (standalone runs only)
**Print before starting:**
> "→ [design-system:vibe] Opening the preview in your default browser…"
@@ -306,7 +306,11 @@ Print the file path as a clickable link FIRST (always), then ask before launchin
>
> Want me to try opening it in your default browser? (yes / no — default: yes)"
-On `yes` (or no answer), try OS-appropriate openers in sequence and fall back to the printed link if all fail:
+On `yes` (or no answer), try OS-appropriate openers in sequence and fall back to the printed link if all fail.
+
+**Skip the opener entirely when `CODE_APPS_NATIVE_ORCHESTRATING=1`** and print the path: a
+`/create-mobile-app` run already has its build plan open in the browser, and a tab appearing over
+it interrupts the user rather than showing them something new.
```bash
open "<working_dir>/_design_vibe.html" 2>/dev/null \
@@ -338,11 +342,11 @@ Use `AskUserQuestion` with options if available; otherwise plain text.
**Handling responses:**
- **`a` / `b` / `c`** → resolve to the direction name; go to Step 6
-- **`hybrid: ...`** → parse the description, merge bundles by picking the named dimensions from each, regenerate `_design_vibe.html` with the merged bundle as a 4th column titled "Your hybrid", re-open, ask "use this hybrid? (yes / refine)"
-- **`mix: ...`** → element-level remix. Parse the picks (`Inspection's status pills, Product's typography, SaaS's spacing`), build a custom bundle by overriding the recommended direction's fields with the named picks, render as a 4th frame titled "Your mix", same re-open / confirm loop as hybrid
+- **`hybrid: ...`** → parse the description, merge bundles by picking the named dimensions from each, regenerate `_design_vibe.html` with the merged bundle as a 4th column titled "Your hybrid", re-open it (standalone runs only; otherwise print the path), ask "use this hybrid? (yes / refine)"
+- **`mix: ...`** → element-level remix. Parse the picks (`Inspection's status pills, Product's typography, SaaS's spacing`), build a custom bundle by overriding the recommended direction's fields with the named picks, render as a 4th frame titled "Your mix", same re-open (standalone runs only; otherwise print the path) / confirm loop as hybrid
- **`dark` / `light`** → flip the recommended direction's `background` field only (`dark-slate` ↔ `cool-gray-light`, `warm-cream` ↔ `rich-dark`); keep direction otherwise. Re-render the single affected frame so the user sees the swap before committing
- **`again`** → regenerate with alternate accents (e.g. Product with rust instead of sage; Inspection with amber instead of orange) — same three directions, different concrete realizations. Cap to 1 `again` per session to avoid taste-paralysis.
-- **`none of these`** → ask what's missing AND what each direction got wrong (capture as a "rejected" log line in `memory-bank.md`). Regenerate the 3-up with adjustments (palette swap, density change, etc.), re-open, ask again
+- **`none of these`** → ask what's missing AND what each direction got wrong (capture as a "rejected" log line in `memory-bank.md`). Regenerate the 3-up with adjustments (palette swap, density change, etc.), re-open it (standalone runs only; otherwise print the path), ask again
- **No reply / unclear** → ask once more, then default to the recommended direction with: `Defaulting to <name> based on app description; you can run /design-system --reskin any time to swap.`
Cap re-renders at **3 iterations** to avoid infinite loops. After 3 the skill must lock in either the user's last clear pick or the recommended default.