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.

81.8 KB
Raw Blame
'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');
const { createSkillWorkflow } = require('./helpers/create-skill');
const { APP_AREA, PHONE, phoneShellCss } = require('../lib/phone-shell');

/** 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: {},
    // Recorded so a test can fire an event the page subscribed to (see `dispatch`).
    listeners: {},
    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(name, value) { attributes[name] = String(value); },
    getAttribute(name) { return Object.hasOwn(attributes, name) ? attributes[name] : null; },
    removeAttribute() {},
    addEventListener(type, listener) { (this.listeners[type] = this.listeners[type] || []).push(listener); },
    removeEventListener() {}, remove() {},
    dispatch(type) { (this.listeners[type] || []).forEach((listener) => listener({ type })); },
    querySelector() { return null; }, querySelectorAll() { return []; },
    closest() { return null; }, focus() {}, scrollIntoView() {},
    getBoundingClientRect() { return { top: 0, left: 0, width: 0, height: 0 }; },
    clientWidth: 282, clientHeight: 602,
  };
}

/**
 * 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', activeElement: null,
  };

  const diagrams = [];
  const renders = [];
  const errors = [];
  // The page's self-reload: each interval callback it schedules, and each URL it reloads through.
  const intervals = [];
  const reloads = [];
  const location = {
    hash: '', href: 'file:///app/docs/create-app-plan.html', reload() {},
    replace(url) { reloads.push(url); },
  };
  const sandbox = {
    URL,
    performance: { getEntriesByType: () => [{ type: 'navigate' }] },
    document,
    window: {
      document,
      addEventListener() {}, removeEventListener() {},
      location,
      matchMedia() { return { matches: false, addEventListener() {} }; },
      setTimeout() { return 0; }, setInterval() { return 0; }, scrollTo() {}, scrollY: 0,
    },
    location,
    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' },
    // Parsing/sanitizing decisions have separate node-level tests below. The page harness
    // retains the source only to exercise the srcdoc handoff, not to emulate an HTML parser.
    DOMParser: class {
      parseFromString(source) {
        const head = node('head');
        head.prepend = (child) => head.children.unshift(child);
        return {
          head,
          createElement: document.createElement,
          querySelectorAll: () => [],
          documentElement: {
            get outerHTML() {
              const policies = head.children.map((child) =>
                `<meta http-equiv="${child.getAttribute('http-equiv')}" content="${child.getAttribute('content')}">`).join('');
              return `<html><head>${policies}</head><body>${source}</body></html>`;
            },
          },
        };
      }
    },
    console: { log() {}, warn() {}, error(message) { errors.push(String(message)); } },
    setTimeout() { return 0; }, clearTimeout() {},
    setInterval(callback) { intervals.push(callback); return intervals.length; }, 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, document, intervals, reloads, window: sandbox.window,
  };
}

/** 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: 'Data model gate - 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]: 'Data model gate - 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]: 'Architecture gate - 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]: 'Data model gate - 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 13.
  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 } }) },
    DOMParser: class { parseFromString() { return { 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('styles survive only in Mermaid output or isolated screen documents', () => {
  // 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]);
  const styled = calls.filter((c) => /keepStyle/.test(c));
  assert.ok(styled.includes('result.svg, { keepStyle: true }'));
  assert.ok(styled.filter((c) => !c.startsWith('result.svg')).every((c) => /asDocument: true/.test(c)),
    'mockup styles must stay in a separate document');
});

test('isolated screen documents retain CSS but refuse handlers, scripts, and remote navigation', () => {
  const style = element('style');
  const script = element('SCRIPT');
  const link = element('a', { href: 'https://contoso.com/', onclick: 'void(0)' });
  const icon = element('use', { href: '#check' });
  const refresh = element('META', { 'http-equiv': 'refresh', content: '0;url=https://contoso.com/' });
  sanitize([style, script, link, icon, refresh], { keepStyle: true, asDocument: true });
  assert.equal(style.removed, false);
  assert.equal(script.removed, true);
  assert.deepEqual(link.attrs, {});
  assert.equal(icon.attrs.href, '#check');
  assert.equal(refresh.removed, true);
});

test('preview extraction keeps shared styles, theme attributes, and ancestors without gallery chrome', () => {
  function markup(tag, attributes = {}, children = [], text = '') {
    const attrs = { ...attributes };
    const created = {
      children: [],
      textContent: text,
      get id() { return attrs.id; },
      getAttribute(name) { return attrs[name] || null; },
      removeAttribute(name) { delete attrs[name]; },
      classList: { add(name) { attrs.class = `${attrs.class || ''} ${name}`.trim(); } },
      style: { setProperty(name, value, priority) { attrs.style = `${name}:${value}!${priority}`; } },
      appendChild(child) { this.children.push(child); child.parentElement = this; },
      cloneNode(deep) {
        return markup(tag, attrs, deep ? this.children.map((child) => child.cloneNode(true)) : [], this.textContent);
      },
      get outerHTML() {
        const encodedAttrs = Object.entries(attrs).map(([name, value]) => ` ${name}="${value}"`).join('');
        return `<${tag}${encodedAttrs}>${this.textContent}${this.children.map((child) => child.outerHTML).join('')}</${tag}>`;
      },
    };
    children.forEach((child) => created.appendChild(child));
    return created;
  }

  const products = markup('div', { id: 'products', class: 'screen', hidden: '' }, [], 'Products');
  const detail = markup('div', { id: 'detail', class: 'screen' }, [], 'Details');
  const area = markup('div', { class: 'screen-area', style: '--spacing:12px' }, [products, detail]);
  const wrap = markup('div', { class: 'screen-wrap' }, [markup('svg', { class: 'status-bar' }), area]);
  const body = markup('body', { class: 'brand', style: '--brand:#0078d4' }, [
    markup('div', { class: 'page-title' }, [], 'Gallery'),
    markup('div', { class: 'phone' }, [wrap]),
  ]);
  const style = markup('style', {}, [], ':root{--brand:#0078d4}.card{display:flex;gap:12px}');
  const source = {
    documentElement: markup('html', { lang: 'en', class: 'dark' }),
    body,
    querySelectorAll(selector) {
      return {
        '[data-screen]': [
          markup('button', { 'data-screen': 'products' }, [], 'Products'),
          markup('button', { 'data-screen': 'detail' }, [], 'Product details'),
        ],
        '.screen': [products, detail],
        style: [style],
      }[selector];
    },
  };
  const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');
  const extract = template.slice(template.indexOf('  function previewScreens('), template.indexOf('  function mockupDocument('));
  const context = vm.createContext({
    document: { createElement: (tag) => markup(tag) },
    sanitizeMockup(input, options) {
      assert.equal(input, 'complete preview');
      assert.equal(options.keepStyle, true);
      assert.equal(options.asDocument, true);
      return source;
    },
  });
  const screens = vm.runInContext(`${extract}\npreviewScreens('complete preview')`, context);
  assert.deepEqual(Array.from(screens, (screen) => screen.name), ['Products', 'Product details']);
  for (const screen of screens) {
    assert.match(screen.html, /<html lang="en" class="dark">/);
    assert.match(screen.html, /<body class="brand" style="--brand:#0078d4">/);
    assert.match(screen.html, /\.card\{display:flex;gap:12px\}/);
    assert.match(screen.html, /class="screen-area" style="--spacing:12px"/);
    assert.match(screen.html, /class="screen active" style="display:flex!important"/);
    assert.doesNotMatch(screen.html, /class="page-title"|class="status-bar"| hidden=/);
  }
  assert.doesNotMatch(screens[0].html, /id="detail"/);
  assert.doesNotMatch(screens[1].html, /id="products"/);
});

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 while the screens are planned. 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 for its mockup carousel; 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 shows its live preview in the plan and opens only that one tab', () => {
  const skill = createSkillWorkflow();

  // The running app replaces the plan-time HTML mockups: a static approximation next to the
  // real screens would only disagree with them. No runnable command opens or carries the file.
  for (const block of skill.matchAll(/```(?:bash|sh)\n([\s\S]*?)```/g)) {
    assert.doesNotMatch(block[1], /_plan_preview\.html/,
      `a command still handles the static mockups: ${block[1].trim().slice(0, 80)}`);
  }
  assert.doesNotMatch(skill, /phone --stage screens/);

  // The plan embeds the live app, and only a loopback URL - the one origin its CSP frames.
  assert.match(skill, /phone --stage live --preview-url "http:\/\/localhost:<port>"/);
  assert.match(skill, /POWER_APPS_WEB_PREVIEW=1 npm run dev -- --port <port> < \/dev\/null/);
  // The phone is the preview: the server must not open a second page beside the plan.
  for (const block of skill.matchAll(/```(?:bash|sh)\n([\s\S]*?)```/g)) {
    assert.doesNotMatch(block[1], /(?:expo start|npm run dev)[^\n]*--web/, 'the preview server opens no browser tab');
  }
  assert.match(skill, /Your app is running in the build plan's phone frame/);
  // `/design-system` is told the real app is on screen, so it skips its own mockups.
  assert.match(skill, /live_preview: http:\/\/localhost:<port>/);
});

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 = createSkillWorkflow();
  // 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\{[^}]*top:var\(--topbar-h\);height:calc\(100vh - var\(--topbar-h\) - var\(--footer-h\)\)/);
});

test('the short-phone container query overrides the default QR copy sizes', () => {
  const template = fs.readFileSync(
    path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',
  );
  const compact = template.indexOf('@container (max-height:520px)');
  assert.ok(compact > template.indexOf('.qr-title{font-size:16px'));
  assert.ok(compact > template.indexOf('.qr-sub{font-size:12.5px'));
  assert.ok(compact > template.indexOf('.qr-url{font-family:var(--mono);font-size:11px'));
});

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('screen documents are sandboxed and scaled, with carousel controls outside the device', async () => {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-frame-'));
  const state = initState(root, { appName: 'Screens' });
  setPhone(state, { stage: 'screens', screens: [
    { name: 'Products', html: '<style>.card{display:flex;gap:12px}</style><div class="card">Products</div>' },
  ] });
  save(root, state);
  const { elements, thrown } = await runPage(outputPath(root));
  assert.deepEqual(thrown.map((error) => error.message), []);
  const device = elements.get('deviceScreen');
  const frame = device.children[0].children[0];
  const viewport = frame.children[0];
  assert.equal(viewport.tagName, 'IFRAME');
  assert.equal(viewport.getAttribute('sandbox'), '');
  assert.equal(viewport.getAttribute('referrerpolicy'), 'no-referrer');
  assert.equal(viewport.getAttribute('title'), 'Products');
  assert.match(viewport.srcdoc, /script-src 'none'/);
  assert.match(viewport.srcdoc, /default-src 'none'/);
  assert.match(viewport.srcdoc, /\.card\{display:flex;gap:12px\}/);
  const scale = Number(viewport.style.transform.match(/scale\(([^)]+)\)/)[1]);
  assert.equal(scale, Math.min(282 / APP_AREA.width, 602 / APP_AREA.height));
  assert.equal(elements.get('device').getAttribute('data-tone'), 'light', 'mockups are light screens');
  assert.equal(elements.get('railControls').hidden, false);
  assert.equal(elements.get('railControls').children[0].className, 'car-nav');
});

/** Every element under `root` whose tag or class matches, depth first. */
function findAll(root, match) {
  const found = [];
  (function walk(target) {
    if (match(target)) found.push(target);
    target.children.forEach(walk);
  })(root);
  return found;
}

function livePlan(previewUrl, { raw = false } = {}) {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-live-'));
  const state = initState(root, { appName: 'Field "Readings"', dataPlatform: 'dataverse' });
  // `raw` writes the stored value directly, as a hand-edited or corrupted plan would, so the
  // page's own check is exercised without app-docs.js validating first.
  if (raw) state.phone = { stage: 'live', screens: [], previewUrl };
  else setPhone(state, { stage: 'live', previewUrl });
  save(root, state);
  return outputPath(root);
}

test('the live stage frames the running app, sandboxed and scaled like the carousel', async () => {
  const page = await runPage(livePlan('http://localhost:8082'));
  assert.deepEqual(page.thrown.map((error) => error.message), []);
  assert.deepEqual(page.errors, []);

  const frames = findAll(page.elements.get('deviceScreen'), (n) => n.tagName === 'IFRAME');
  assert.equal(frames.length, 1, 'the live stage draws exactly one frame');
  const [frame] = frames;
  assert.equal(frame.getAttribute('src'), 'http://localhost:8082/');
  assert.equal(frame.getAttribute('sandbox'), 'allow-scripts allow-same-origin allow-forms allow-popups');
  assert.equal(frame.getAttribute('referrerpolicy'), 'no-referrer');
  // The name is plan data, so it reaches the attribute as text, quotes and all.
  assert.equal(frame.getAttribute('title'), 'Live preview of Field "Readings"');
  assert.equal(frame.srcdoc, undefined, 'the live app is loaded by URL, not injected as markup');

  // The phone's app area, as wide as the carousel's. Unlike a mockup, the running app takes
  // whatever height fills the box, so it is never letterboxed.
  const scale = Number(frame.style.transform.match(/scale\(([^)]+)\)/)[1]);
  assert.equal(scale, 282 / APP_AREA.width);
  assert.equal(Number.parseFloat(frame.style.height) * scale, 602);
  assert.equal(frame.style.left, '0px');
  const classes = findAll(page.elements.get('deviceScreen'), (n) => n.className).map((n) => n.className);
  assert.ok(classes.includes('live') && classes.includes('device-app'));
  // The app follows the browser's colour scheme, so the status bar over it does too.
  assert.equal(page.elements.get('device').getAttribute('data-tone'), 'system');
  assert.ok(!classes.includes('car') && !classes.includes('bld'), 'no carousel and no build animation');

  assert.equal(page.elements.get('railTitle').textContent, 'Live preview');
  assert.match(page.elements.get('railCaption').textContent, /^Sample data\. Edits hot-reload here\.$/);
  assert.equal(page.elements.get('railControls').hidden, true, 'the live app has no carousel controls');
  assert.equal(page.elements.get('railNote').hidden, true, 'the mockup caveat does not apply to the real app');

  // A link out, for the full window and the browser's dev tools. It leaves this page's origin,
  // so it carries noreferrer as well as noopener.
  const links = findAll(page.elements.get('railPreviewLink'), (n) => String(n.className).split(' ').includes('rail-link'));
  assert.equal(links.length, 1);
  assert.match(links[0].textContent, /Open the live preview in a browser tab/);
  assert.equal(links[0].getAttribute('href'), 'http://localhost:8082/');
  assert.equal(links[0].getAttribute('target'), '_blank');
  assert.equal(links[0].getAttribute('rel'), 'noopener noreferrer');
  assert.equal(findAll(page.elements.get('railPreviewLink'), (n) => n.className === 'store-btn').length, 0,
    'the store links wait for the QR');
});

test('a QR recorded during the live stage sits under the frame and leaves the preview in it', async () => {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-live-qr-'));
  const state = initState(root, { appName: 'Live QR', dataPlatform: 'dataverse' });
  setPhone(state, { stage: 'live', previewUrl: 'http://localhost:8082' });
  // What the preview gate's `phone --qr-image --qr-url` call produces: no stage change.
  setPhone(state, {
    qrImage: 'data:image/png;base64,iVBORw0KGgo=',
    qrHref: '../.expo/metro-qr.png',
    qrUrl: 'http://192.168.1.4:8082/',
  });
  assert.equal(state.phone.stage, 'live', 'recording the code must not take the preview out of the phone');
  save(root, state);

  const page = await runPage(outputPath(root));
  assert.deepEqual(page.thrown.map((e) => e.message), []);
  assert.equal(findAll(page.elements.get('deviceScreen'), (n) => n.tagName === 'IFRAME').length, 1,
    'the browser preview stays in the phone frame');
  const rail = page.elements.get('railPreviewLink');
  const cards = findAll(rail, (n) => n.className === 'rail-qr');
  assert.equal(cards.length, 1, 'the code is drawn under the frame');
  assert.equal(findAll(cards[0], (n) => n.tagName === 'IMG')[0].src, 'data:image/png;base64,iVBORw0KGgo=');
  // The phone app is usable now, so the card says where to get it, as compact text links: the
  // full store buttons would take height from the phone above.
  const stores = findAll(cards[0], (n) => n.className === 'rail-qr-stores')[0];
  const storeLinks = findAll(stores, (n) => n.tagName === 'A');
  assert.deepEqual(storeLinks.map((n) => n.textContent), ['App Store', 'Google Play']);
  assert.ok(storeLinks.every((n) => n.getAttribute('rel') === 'noopener noreferrer'));
  assert.equal(findAll(rail, (n) => n.className === 'store-btn').length, 0);
  // The code itself opens the PNG full size, so the rail drops the separate link row, which a
  // short window would push behind the footer.
  const full = findAll(cards[0], (n) => n.className === 'rail-qr-full');
  assert.equal(full.length, 1);
  assert.equal(full[0].getAttribute('href'), '../.expo/metro-qr.png');
  const railLinks = findAll(rail, (n) => String(n.className).split(' ').includes('rail-link'));
  assert.deepEqual(railLinks.map((n) => n.textContent), ['Open the live preview in a browser tab \u2197']);

  // A code that is not an inlined PNG is not drawn: the CSP admits only data: images.
  setPhone(state, { qrImage: 'https://example.com/qr.png' });
  save(root, state);
  const rejected = await runPage(outputPath(root));
  assert.equal(findAll(rejected.elements.get('railPreviewLink'), (n) => n.className === 'rail-qr').length, 0);
});

test('a live stage whose address fails the page check falls back to the build animation', async () => {
  // Each of these would get past a prefix test. `@` makes everything before it userinfo, so the
  // first frames example.com; the CSP would also refuse it, and this is the check before that.
  for (const url of [
    'http://localhost:[email protected]/',
    'http://localhost:8082\\@example.com/',
    'https://localhost:8082/',
    'http://localhost:/',
    'javascript:alert(1)//http://localhost:8082/',
    'http://localhost:8082/?next=https://example.com',
    undefined,
  ]) {
    const page = await runPage(livePlan(url, { raw: true }));
    assert.deepEqual(page.thrown.map((error) => error.message), [], String(url));
    assert.equal(findAll(page.elements.get('deviceScreen'), (n) => n.tagName === 'IFRAME').length, 0,
      `${url} must not be framed`);
    assert.equal(page.elements.get('railTitle').textContent, 'Building your app', String(url));
    assert.equal(findAll(page.elements.get('railPreviewLink'), (n) => n.className === 'rail-link').length, 0,
      `${url} must not be linked`);
  }
});

test('after the preview is stopped, the phone says real data is being connected and links nothing', async () => {
  const CONNECTING = 'Connecting real data. The QR code to open the app on your phone appears here next.';
  const BEFORE = 'A live preview of your app appears here once its screens are built.';
  const iframes = (page) => findAll(page.elements.get('deviceScreen'), (n) => n.tagName === 'IFRAME');
  const railLinks = (page) => findAll(page.elements.get('railPreviewLink'),
    (n) => String(n.className).split(' ').includes('rail-link'));

  // Step 14 stops the sample-data web server, because plain Expo web cannot sign in to
  // Dataverse, and moves the phone back to `building`. The address is still in state.
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-stopped-'));
  const state = initState(root, { appName: 'Stopped', dataPlatform: 'dataverse' });
  setPhone(state, { stage: 'live', previewUrl: 'http://localhost:8082' });
  setPhone(state, { stage: 'building' });
  save(root, state);

  const stopped = await runPage(outputPath(root));
  assert.deepEqual(stopped.thrown.map((error) => error.message), []);
  assert.equal(iframes(stopped).length, 0, 'the stopped server must not be framed');
  assert.equal(railLinks(stopped).length, 0, 'the stopped server must not be linked');
  assert.equal(stopped.elements.get('railTitle').textContent, 'Building your app');
  assert.equal(findAll(stopped.elements.get('deviceScreen'), (n) => n.className === 'bld').length, 1,
    'the build animation is back');
  assert.equal(stopped.elements.get('railCaption').textContent, CONNECTING);

  // Before any preview has run, the animation keeps saying what is coming.
  const early = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-early-'));
  save(early, initState(early, { appName: 'Early', dataPlatform: 'dataverse' }));
  const fresh = await runPage(outputPath(early));
  assert.equal(fresh.elements.get('railCaption').textContent, BEFORE);

  // A `live` stage whose address fails the page check also draws the animation, but no preview
  // has been stopped, so it must not claim real data is being connected.
  const rejected = await runPage(livePlan('http://localhost:[email protected]/', { raw: true }));
  assert.equal(rejected.elements.get('railCaption').textContent, BEFORE);
});

test('the plan reloads only when it changed, and never over someone using the live preview', async () => {
  const open = async () => {
    const planPath = livePlan('http://127.0.0.1:19006/');
    const page = await runPage(planPath);
    assert.deepEqual(page.thrown.map((error) => error.message), []);
    assert.equal(page.intervals.length, 1, 'a run in progress schedules its check');
    assert.equal(page.elements.get('refreshStatus').textContent, 'Auto-refresh on: this page updates when the plan changes.');
    const [frame] = findAll(page.elements.get('deviceScreen'), (n) => n.tagName === 'IFRAME');
    const version = fs.readFileSync(planPath, 'utf8').match(/"version":"([0-9a-f]+)"/)[1];
    const probes = () => findAll(page.document.body, (n) => n.tagName === 'SCRIPT');
    // What the version file does when it loads: report the version app-docs.js last rendered.
    const report = (v) => page.window.__planVersion(v);
    return { page, frame, tick: page.intervals[0], version, probes, report };
  };

  // Every reload restarts the app in the phone on its first screen, so an unchanged plan must
  // never reload. A tick only asks the version file for the current version.
  const unchanged = await open();
  unchanged.tick();
  unchanged.report(unchanged.version);
  unchanged.tick();
  assert.deepEqual(unchanged.page.reloads, [], 'nothing changed, so the app keeps its place');
  const [probe] = unchanged.probes();
  assert.match(probe.src, /^create-app-plan\.version\.js\?t=\d+$/, 'a fresh URL, so a cached copy is never read');

  // A newer render, and nobody using the page: the check that finds it reloads through a fresh URL.
  const changed = await open();
  changed.report('a-newer-render');
  assert.equal(changed.page.reloads.length, 1, 'a changed plan refreshes itself at once');
  const reloaded = new URL(changed.page.reloads[0]);
  assert.match(reloaded.pathname, /create-app-plan\.html$/);
  assert.match(reloaded.searchParams.get('t'), /^\d+$/, 'a fresh URL, so the cached page is never shown');

  // A browser that blocks file scripts: fall back to the timed refresh rather than leave the page stale.
  const blocked = await open();
  blocked.tick();
  blocked.probes()[0].dispatch('error');
  blocked.tick();
  assert.equal(blocked.page.reloads.length, 1, 'no version file means the old timed refresh');

  // Clicks inside a cross-origin frame never reach this page's listeners, so the pointer over the
  // frame is all the page can go on - and a change waits for the reader.
  const hovered = await open();
  hovered.frame.dispatch('pointerenter');
  hovered.report('a-newer-render');
  hovered.tick();
  hovered.tick();
  assert.deepEqual(hovered.page.reloads, [], 'the pointer is over the preview');

  // Leaving restarts the quiet window rather than letting the next tick reload.
  const left = await open();
  left.frame.dispatch('pointerenter');
  left.frame.dispatch('pointerleave');
  left.report('a-newer-render');
  left.tick();
  assert.deepEqual(left.page.reloads, [], 'the reader only just left the preview');

  // Keyboard focus stays in the frame after the reader goes to the terminal to answer, so it is not
  // a sign of use. Counting it held off every update until the browser was reloaded by hand.
  const focused = await open();
  focused.page.document.activeElement = focused.frame;
  focused.report('a-newer-render');
  assert.equal(focused.page.reloads.length, 1, 'focus left in the preview does not freeze the plan');

  // Switching to the terminal fires no pointerleave, so the pointer still reads as over the frame.
  // A window without focus means the reader is elsewhere, and the update goes ahead.
  const elsewhere = await open();
  elsewhere.frame.dispatch('pointerenter');
  elsewhere.page.document.hasFocus = () => false;
  elsewhere.report('a-newer-render');
  assert.equal(elsewhere.page.reloads.length, 1, 'the reader is in another app');
});

test('a preview without screen blocks reports the problem instead of silently showing an animation', async () => {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-invalid-preview-'));
  const state = initState(root, { appName: 'Invalid preview' });
  setPhone(state, { stage: 'screens', previewHtml: '<html><body>No screens</body></html>' });
  save(root, state);
  const { elements, errors, thrown } = await runPage(outputPath(root));
  assert.deepEqual(thrown.map((error) => error.message), []);
  assert.equal(elements.get('railTitle').textContent, 'Screen preview unavailable');
  assert.match(elements.get('railCaption').textContent, /no \.screen blocks/);
  assert.equal(errors.length, 1);
  assert.equal(elements.get('railControls').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|child-src|object-src/);

  // One exception, for the live preview: frames may load only the two loopback hosts, over
  // http, on any port. Nothing broader - no wildcard host, no https:, no scheme-only source -
  // so an injected frame still cannot reach remote content.
  const frameSources = (policy.match(/(?:^|;\s*)frame-src ([^;]*)/) || [])[1];
  assert.ok(frameSources, 'the live preview needs a frame-src');
  assert.deepEqual(frameSources.trim().split(/\s+/), ['http://localhost:*', 'http://127.0.0.1:*']);
  assert.equal((policy.match(/frame-src/g) || []).length, 1);
  assert.doesNotMatch(policy, /frame-src \*|https:|\bhttp:(?!\/\/(?:localhost|127\.0\.0\.1):\*)/);

  // 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, /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');

  // Mermaid inserts a cleaned fragment; screens serialize a cleaned, sandboxed document.
  const sanitized = [...template.matchAll(/appendChild\(sanitizeMockup\(/g)];
  assert.equal(sanitized.length, 1, 'Mermaid output must be cleaned');
  assert.match(template, /viewport\.srcdoc = mockupDocument\(current\.html\)/);
  assert.match(template, /function mockupDocument\(markup\) \{\s+var source = sanitizeMockup/);
  // 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(phoneShellCss(), /\.device-app\{[^}]*contain:layout paint/);
  assert.equal((template.match(/el\('div', 'device-app'\)/g) || []).length, 2, 'the carousel and the live app both use it');
  assert.match(template, /viewport\.setAttribute\('sandbox', ''\)/);
  // The mockup carousel runs nothing. The live preview is the one frame given any sandbox
  // tokens, and it is a cross-origin frame onto the local Expo web server, not mockup markup.
  const sandboxes = [...template.matchAll(/(\w+)\.setAttribute\('sandbox', '([^']*)'\)/g)]
    .map((m) => [m[1], m[2]]);
  assert.deepEqual(sandboxes, [
    ['liveFrame', 'allow-scripts allow-same-origin allow-forms allow-popups'],
    ['viewport', ''],
  ]);
});

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');
});

test('every phone the plugin draws is the same iPhone 18 Pro', () => {
  // The build plan and edit page draw the shell from lib/phone-shell.js. The screen-preview and
  // design-system templates are standalone HTML that agents copy, so they repeat its sizes; a
  // mockup laid out for another phone would be letterboxed or cropped in the plan's app area.
  const read = (file) => fs.readFileSync(path.resolve(__dirname, '..', '..', file), 'utf8');
  const mapping = read('shared/references/tamagui-html-mapping.md');
  assert.match(mapping, new RegExp(`\\.phone \\{ width: ${PHONE.width}px; height: ${PHONE.height}px;`));
  assert.match(mapping, new RegExp(`\\.status-bar \\{[^}]*height: ${PHONE.statusBar}px;`));
  assert.match(mapping, new RegExp(`\\.home-ind \\{ height: ${PHONE.homeIndicator}px;`));
  assert.match(mapping, new RegExp(`<svg class="status-bar" viewBox="0 0 ${PHONE.width} ${PHONE.statusBar}"`));
  assert.match(mapping, new RegExp(`class="island"[^>]*width="${PHONE.island.width}" height="${PHONE.island.height}"`));
  assert.doesNotMatch(mapping, /class="notch"/);
  const gallery = read('skills/design-system/references/preview-template.md');
  assert.match(gallery, new RegExp(`width: ${PHONE.width}px; height: ${PHONE.height}px;`));
  assert.match(gallery, new RegExp(`\\.status-bar-mock \\{[^}]*height: ${PHONE.statusBar}px;`));
  assert.equal(APP_AREA.height, PHONE.height - PHONE.statusBar - PHONE.homeIndicator);
});