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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Fix a smoke-eval assertion that could never pass, and four crash paths from live testing (#399)
Akshay Malooff5f16d5c452
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex c76394f6e..899bb56eb 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.4.2",+ "version": "2.4.3","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex c76394f6e..899bb56eb 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.4.2",+ "version": "2.4.3","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex 28ba2c8e9..b8f98f76e 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -148,6 +148,17 @@ the pipeline and delegates each script's **behavioral spec** to the entries belogeneral rule this bug taught: **assert what you PRODUCED, not what you intended** — "some tablecomponent exists" was true of the corrupt apps too, and `ValidateApp` reported success on them.Pinned by `scripts/tests/app-entity-components-real-bundle.test.js`.+ The same rule binds **tests and evals**, with a distinction that is easy to get backwards:+ an EXPECTATION must come from the CONTRACT, independent of the code under test, while the FIXTURE+ that stands in for the environment should be generated from the builder's real output so it cannot+ drift from what ships. `smoke-eval.js` got both wrong at once: it asserted a `VectorIcon` the+ builder deliberately drops, and its unit test hand-wrote sitemap XML containing that value — so the+ offline suite stayed green while every live run failed. Deriving the expectation from `appDef`+ instead is the opposite failure and is just as bad: when the builder stops emitting a value, a+ derived "must be present" check silently becomes "must be absent" and still passes, leaving the+ eval unable to contradict the very code it exists to check. Assertions are therefore fixed by+ contract, the offline fixture is rendered from `appDef`, and `vendor-sdk-smoke.test.js` checks the+ bytes the real vendored SDK serializes.- **`scripts/teardown-model-app.js` → `scripts/lib/sdk-teardown.js`** — the first-class, **classifier-safe**teardown (reverse of the build), for cleaning up live-verification probes or a failed build. Deletesexactly the artifacts a given App Spec declares, in dependency-safe order (**app module → securitydiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 667c0f094..4355ffd6b 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -2,7 +2,59 @@All notable changes to the **model-apps** plugin.-## [Unreleased] — 2.4.2+## [Unreleased] — 2.4.3++Fixes four crash paths and a smoke-eval assertion that could never pass live.++### Fixed+- **Malformed specs now produce validation errors instead of raw `TypeError`s.** `validateAppSpec()`+ and `lintAppSpec()` crashed on a `null` spec, an object- or string-shaped collection+ (`entities: {}`), and `null` entries inside a collection; `preview-app` crashed when a persona+ privilege's `access` was a scalar rather than an array. These are work-in-progress shapes an author+ hits constantly, and a crash killed the authoring flow instead of reporting the problem. Coverage+ is now a single recursive descriptor shared by both gates (`lib/spec-shape.js`), reaching nested+ collections too — `entities[].columns`, `views[].filters`, `forms[].tabs[].sections`,+ `pages[].dataSources`, `commands[].buttons[].children`, and the `appShell.areas → groups →+ subAreas` chain — and errors name the exact path (`appShell.areas[0].groups must be an array`).+- **A malformed collection can no longer pass validation and then crash mid-build.** Validation+ inspects a normalized copy while the caller keeps the original, so a silently-repaired+ `appShell.areas: [null]` reported PASS and then threw inside the build — *after* the solution and+ data model had been written to Dataverse. A null entry is now a blocking error, so the failure+ happens at the gate with nothing deployed.+- **`migrateAppSpec` no longer crashes ahead of the gate.** Every CLI entry point migrates the spec+ it just read *before* validating it, so a malformed collection threw a raw `TypeError` before the+ validator that exists to report it ever ran. Migration is now defensive but does **not** repair —+ repairing would hand the gate a clean spec and the real problem would vanish.+- **`verify-model-app` no longer surfaces a raw Dataverse HTTP 400 for a missing table.** A declared+ table that does not exist makes the saved-view query 400 (`returnedtypecode` names an unknown+ entity); the read error is now captured and reported as a structured missing-artifact finding.+ Both the verify CLI and the build's verify step now print the failure `detail`, so a read that+ failed (throttling, auth expiry, a 5xx) is distinguishable from an artifact that is genuinely+ absent instead of both rendering as a bare `✗ view: <name>`.+- **The live smoke eval asserted an outcome the builder never produces.** Its spec put a bare Fluent+ `vectorIcon` ("Grid") on an *entity* subarea — the one shape the builder deliberately drops,+ because it breaks the modern app-designer property pane — while asserting the deployed sitemap+ contained `VectorIcon="Grid"`. The offline test hid it by hand-writing the sitemap XML it wanted to+ see. The spec now uses an emittable `/WebResources/<name>.svg` reference and keeps the bare token+ as a negative control; assertions are scoped to the `<SubArea>` that declared the icon (the spec+ reuses one icon on the parent `<Area>`, which a document-wide scan let satisfy every subarea check)+ and their expected values stay independent of the builder, so a builder that stops emitting the+ icon makes the eval FAIL rather than silently invert into an absence check.++### Changed+- **`download-model-app.js --app` now accepts a display name**, not just an id or `uniquename`. It+ resolves in identity order (id → `uniquename` → display name) and **fails closed** when a display+ name matches more than one app, listing the candidate unique names instead of guessing. A display+ name previously hit a dead-end "app 'x' not found", even though that is the only name the maker+ portal shows.++### Tests+- A contract test drives the **real vendored SDK** and asserts the serialized sitemap bytes: a+ platform-ref `VectorIcon` reaches the XML on an Entity subarea, and the bundle does **not** filter a+ bare Fluent token — pinning that `appDef` is the only guard, so the drop cannot be delegated to the+ SDK.++## [2.4.2]Fixes a malformed app module: generated apps did not actually contain their tables.diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex f9d528183..9fe88c0d8 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -317,11 +317,13 @@ async function buildModelApp(spec, opts, deps) {const vr = await deps.verify(spec);const present = vr.checks.length - vr.missing.length;log(`\n${vr.ok ? '✓ verify PASS' : `✗ verify FAIL — ${vr.missing.length} missing`} (${present}/${vr.checks.length} present)`);- if (!vr.ok) for (const m of vr.missing) log(` ✗ ${m.kind}: ${m.name}`);+ // Include `detail` on a failure so a READ that failed (throttling, auth expiry, a 5xx) is+ // not reported identically to an artifact that is genuinely absent.+ if (!vr.ok) for (const m of vr.missing) log(` ✗ ${m.kind}: ${m.name}${m.detail ? ` — ${m.detail}` : ''}`);// Propagate unableToRun from verifySpec (RECONCILIATION 1): verifySpec itself sets// unableToRun when the reader lacks pages/pageCode methods. Only include the property// when truthy so existing callers using deepStrictEqual are not affected on the normal path.- r.verify = { ok: vr.ok, present, total: vr.checks.length, missing: vr.missing.map((m) => `${m.kind}:${m.name}`), ...(vr.unableToRun ? { unableToRun: true } : {}) };+ r.verify = { ok: vr.ok, present, total: vr.checks.length, missing: vr.missing.map((m) => `${m.kind}:${m.name}${m.detail ? ` (${m.detail})` : ''}`), ...(vr.unableToRun ? { unableToRun: true } : {}) };if (journal) journal.record({ phase: 'verify', status: vr.ok ? 'ok' : 'error', label: `verify ${present}/${vr.checks.length} present`, ...(vr.ok ? {} : { detail: r.verify.missing.join(', ') }) });} catch (e) {if (mustVerifyPages) {diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex e8c8fe889..a496ec06c 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -5,7 +5,7 @@// pages (via pac list+download, incl. Maker-authored), its entities (minimal — the build reuses// existing tables idempotently), the icon web resources, and its solution, via hydrate-spec.//-// Usage: node download-model-app.js --env <orgUrl> --app <appId|uniqueName> --out <dir> [--allow-lossy-download]+// Usage: node download-model-app.js --env <orgUrl> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download]const fs = require('node:fs');const path = require('node:path');@@ -66,12 +66,35 @@ function makeProvision(env, workspaceDir) {return sdk;}+// Resolve `--app` to an app GUID. Accepts the app's id, its immutable `uniquename`, or — as a+// convenience — its DISPLAY name. Identity order matters: an id and a uniquename are unique and+// authoritative, so they are tried first and a display-name query is never issued for them.+//+// A display NAME is resolved only as a LAST RESORT and FAILS CLOSED on ambiguity. Unlike a+// uniquename it is mutable and NOT unique — Dataverse happily holds two appmodules both named+// "Sales" — so silently taking the first match could download a different app than the operator+// meant. On multiple matches we return the candidate unique names instead of guessing.+// Display names were previously rejected outright with a bare "not found", which is a dead end for+// an operator holding the name the maker portal shows them (the unique name is not surfaced there).+//+// Returns { appId, matchedBy?, uniqueName? } on success, or { error } describing how to retry.async function resolveAppId(sdk, appArg) {- if (/^[0-9a-fA-F-]{36}$/.test(appArg)) return appArg;- const rows = await sdk.queryRecords('appmodule', { select: ['appmoduleid'], filter: `uniquename eq '${String(appArg).replace(/'/g, "''")}'`, top: 1 });- return rows && rows[0] && rows[0].appmoduleid;-}-+ if (/^[0-9a-fA-F-]{36}$/.test(appArg)) return { appId: appArg };+ // OData string literals escape a single quote by DOUBLING it: O'Brien -> 'O''Brien'.+ const esc = String(appArg).replace(/'/g, "''");+ const byUnique = await sdk.queryRecords('appmodule', { select: ['appmoduleid'], filter: `uniquename eq '${esc}'`, top: 1 });+ if (byUnique && byUnique[0] && byUnique[0].appmoduleid) return { appId: byUnique[0].appmoduleid, matchedBy: 'uniqueName' };++ const byName = await sdk.queryRecords('appmodule', { select: ['appmoduleid', 'uniquename', 'name'], filter: `name eq '${esc}'`, top: 50 });+ const matches = (byName || []).filter((r) => r && r.appmoduleid);+ if (matches.length === 1) return { appId: matches[0].appmoduleid, matchedBy: 'displayName', uniqueName: matches[0].uniquename };+ if (matches.length > 1) {+ const names = matches.map((m) => m.uniquename).filter(Boolean).join(', ');+ return { error: `'${appArg}' is a DISPLAY name shared by ${matches.length} apps — display names are not unique, so re-run --app with one of these unique names: ${names}` };+ }+ return { error: `app '${appArg}' not found — --app takes the app's id (GUID), its unique name (e.g. new_myapp), or an unambiguous display name` };+}+// The distinct entity logical names + icon web-resource NAMES referenced by the app's sitemap. Returns// TWO name sets:// `icons` — BARE-NAME icon references (a locally-declared image web resource); fetched and@@ -723,14 +746,20 @@ async function main() {const outArg = typeof flags.out === 'string' ? flags.out : (typeof flags.output === 'string' ? flags.output : undefined);const allowLossyDownload = flags['allow-lossy-download'] === true;if (!env || !appArg || flags.app === true || flags.out === true || flags.output === true) {- process.stderr.write('Usage: node download-model-app.js --env <url> --app <appId|uniqueName> --out <dir> [--allow-lossy-download]\n');+ process.stderr.write('Usage: node download-model-app.js --env <url> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download]\n');process.exit(1);}const outDir = path.resolve(outArg || '.');fs.mkdirSync(outDir, { recursive: true });const sdk = makeProvision(env, path.join(outDir, '.maker-workspace'));- const appId = await resolveAppId(sdk, appArg);- if (!appId) { emitResult(false, { ok: false, error: `app '${appArg}' not found` }); return; }+ const resolved = await resolveAppId(sdk, appArg);+ if (resolved.error) { emitResult(false, { ok: false, error: resolved.error }); return; }+ const appId = resolved.appId;+ // Narrate a display-name match so the operator learns the app's stable identity: the unique name+ // is what every later build/teardown must be given, and it survives a rename of the display name.+ if (resolved.matchedBy === 'displayName') {+ process.stderr.write(`(resolved display name '${appArg}' to app unique name '${resolved.uniqueName}' — prefer the unique name, it is immutable)\n`);+ }// Resolve the app's unique name early — needed for fetchSitemap (MEMBERSHIP) + manifest lookup.const appRows = await sdk.queryRecords('appmodule', { select: ['uniquename'], filter: `appmoduleid eq ${appId}`, top: 1 });diff --git a/plugins/model-apps/scripts/lib/app-preview.js b/plugins/model-apps/scripts/lib/app-preview.jsindex c9df64d57..80ada4e5a 100644--- a/plugins/model-apps/scripts/lib/app-preview.js+++ b/plugins/model-apps/scripts/lib/app-preview.js@@ -92,15 +92,16 @@ function designSection(spec) {function securitySection(spec) {const personas = spec.personas || [];if (!personas.length) return [];+ const accessText = (access) => (Array.isArray(access) ? access : access == null ? [] : [access]).join('/');const out = [h('Security roles (personas)')];for (const p of personas) {const appOpens = p.appAccess !== false;out.push(` ⛊ role "${p.persona}"${appOpens ? ' (app opens for this persona)' : ' (data-only — no app access)'}`);for (const j of p.jobs || []) {out.push(` • job: ${j.name || '(unnamed)'}`);- for (const pr of j.privileges || []) out.push(` - ${lc(pr.entity)}: ${(pr.access || []).join('/')} @ ${pr.scope || 'user'}`);+ for (const pr of j.privileges || []) out.push(` - ${lc(pr.entity)}: ${accessText(pr.access)} @ ${pr.scope || 'user'}`);}- for (const pr of p.additionalPrivileges || []) out.push(` • baseline: ${lc(pr.entity)}: ${(pr.access || []).join('/')} @ ${pr.scope || 'user'}`);+ for (const pr of p.additionalPrivileges || []) out.push(` • baseline: ${lc(pr.entity)}: ${accessText(pr.access)} @ ${pr.scope || 'user'}`);const assigned = [...((p.assignTo && p.assignTo.teams) || []), ...((p.assignTo && p.assignTo.users) || [])];if (assigned.length) out.push(` • assigned to ${assigned.length} principal(s)`);}diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex c194e87a0..4c8a9555b 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -2,6 +2,7 @@// the app-builder's LLM proposal and the deterministic builder.const path = require('node:path');+const { normalizeSpecShape } = require('./spec-shape.js');// URL scheme allowlist for spec-supplied URLs that the built app will RENDER (iframe dashboard tiles,// sitemap URL subareas). Only http(s) is allowed — a `javascript:`, `data:`, `vbscript:`, or `file:`@@ -411,6 +412,12 @@ function validateAppSpec(spec, opts = {}) {if (!spec || typeof spec !== 'object') {return { ok: false, errors: ['spec is not an object'], warnings };}+ // Structural normalization (shared with lintAppSpec) so a half-typed collection produces findings+ // rather than a raw TypeError. Covers NESTED collections too — `entity.columns: {}` and+ // `appShell.areas: {}` are realistic mid-edit states that reach `for...of` and throw.+ const shape = normalizeSpecShape(spec);+ errors.push(...shape.errors);+ spec = shape.spec;if (!spec.solution || !spec.solution.uniqueName) {errors.push('solution.uniqueName is required');}@@ -1209,9 +1216,16 @@ function migrateAppSpec(spec) {out.schemaVersion = 2;const nameToKey = new Map();const used = new Set();+ // Migration runs BEFORE validateAppSpec at every CLI entry point (build/preview/verify/teardown+ // all migrate the file they just read, then validate), so a malformed collection reached these+ // loops and threw a raw TypeError before the gate that is supposed to report it ever ran. Iterate+ // defensively — but do NOT rewrite the value, or validateAppSpec would see a repaired spec and+ // report nothing. The shape error stays for the gate to find.+ const arr = (v) => (Array.isArray(v) ? v : []);// Pass 1: mint every key and wrap legacy codeFile→source. nameToKey is fully populated// after this loop so the rewrite pass below needs only a single scan (no forward-ref gaps).- for (const p of out.pages || []) {+ for (const p of arr(out.pages)) {+ if (!p || typeof p !== 'object') continue;let key = slugify(p.name);let n = 1;while (used.has(key)) { n += 1; key = `${slugify(p.name)}-${n}`; }@@ -1222,12 +1236,15 @@ function migrateAppSpec(spec) {}// Pass 2: rewrite name-refs to keys exactly once. Because nameToKey is complete, forward refs// (a page referencing a later-declared page) resolve correctly without a repeated second pass.- for (const p of out.pages || []) {- for (const nav of p.navigatesTo || []) { if (nav && nameToKey.has(nav.targetKey)) nav.targetKey = nameToKey.get(nav.targetKey); }+ for (const p of arr(out.pages)) {+ if (!p || typeof p !== 'object') continue;+ for (const nav of arr(p.navigatesTo)) { if (nav && nameToKey.has(nav.targetKey)) nav.targetKey = nameToKey.get(nav.targetKey); }}- for (const a of (out.appShell && out.appShell.areas) || []) {- for (const g of a.groups || []) {- for (const sa of g.subAreas || []) { if (sa && sa.page && nameToKey.has(sa.page)) sa.page = nameToKey.get(sa.page); }+ for (const a of arr(out.appShell && out.appShell.areas)) {+ if (!a || typeof a !== 'object') continue;+ for (const g of arr(a.groups)) {+ if (!g || typeof g !== 'object') continue;+ for (const sa of arr(g.subAreas)) { if (sa && sa.page && nameToKey.has(sa.page)) sa.page = nameToKey.get(sa.page); }}}return out;diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.jsindex 5a3f61fd0..2d4fefef1 100644--- a/plugins/model-apps/scripts/lib/spec-lint.js+++ b/plugins/model-apps/scripts/lib/spec-lint.js@@ -3,6 +3,7 @@// gate; warnings teach. Bakes in the modeling lessons hit live — notably the// relationship schema-name vs lookup-name collision Dataverse rejects.const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef } = require('./app-spec.js');+const { normalizeSpecShape } = require('./spec-shape.js');const CHOICE_OPTION_WARN = 12;const SEQNUM_RE = /\{SEQNUM(:\d+)?\}/i;@@ -16,11 +17,17 @@ function lintAppSpec(spec) {const warnings = [];const E = (m) => errors.push(m);const W = (m) => warnings.push(m);+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {+ return { ok: false, errors: ['spec is not an object'], warnings };+ }const lc = (s) => String(s || '').toLowerCase();// Lint runs on WORK-IN-PROGRESS specs (it is the gate the author hits before plan mode), so a// half-typed collection must produce findings, not a crash that kills the authoring flow.- // validateAppSpec is what reports the shape error itself.+ // Shared with validateAppSpec so the two gates can never disagree about what a malformed spec is.const arrOf = (v) => (Array.isArray(v) ? v : []);+ const shape = normalizeSpecShape(spec);+ for (const m of shape.errors) E(m);+ spec = shape.spec;const prefix = spec.solution && spec.solution.publisherPrefix;const entityNames = new Set();diff --git a/plugins/model-apps/scripts/lib/spec-shape.js b/plugins/model-apps/scripts/lib/spec-shape.jsnew file mode 100644index 000000000..735121fbf--- /dev/null+++ b/plugins/model-apps/scripts/lib/spec-shape.js@@ -0,0 +1,127 @@+// plugins/model-apps/scripts/lib/spec-shape.js+// Shared structural normalization for an App Spec, used by BOTH validateAppSpec (app-spec.js) and+// lintAppSpec (spec-lint.js).+//+// WHY this exists: both gates run on WORK-IN-PROGRESS specs — lint is the gate an author hits before+// plan mode, and validate runs on every hand-edited or partially-generated spec. A half-typed+// collection (`entities: {}`, a `null` left behind after deleting a column, an `appShell.areas` still+// being reshaped) must produce a structured finding, not a raw TypeError that kills the authoring+// flow. Both files previously implemented the same coercion verbatim, which is exactly the+// duplication the plugin's AGENTS.md forbids — and being duplicated, it also drifted.+//+// TWO RULES, and the second one matters more than it looks:+// 1. ARRAY-NESS — a known collection that is present but not an array is REPORTED and treated as+// empty, so `for (const x of value)` cannot throw "object is not iterable" and `value.map(...)`+// cannot throw "map is not a function".+// 2. NULL ENTRIES ARE ERRORS, NOT REPAIRS — a null/undefined entry is reported AND replaced with+// `{}`. The replacement exists only so the validator can finish and report every OTHER problem+// in one pass; it must never make the spec "valid". Normalizing silently was an active hazard:+// validateAppSpec checks its own normalized COPY while the caller keeps the ORIGINAL, so a+// silently-repaired `appShell.areas: [null]` passed validation and then threw inside the build+// — AFTER the solution and data model had already been written to Dataverse. Reporting it keeps+// the failure at the gate, where nothing has been deployed yet.+//+// What is deliberately NOT coerced: entries that are strings. Several collections legitimately hold+// scalars — `views[].columns` (['new_name']), `columns[].options` (['Open','Closed'], which may ALSO+// be objects), `alternateKeys[].columns`, `pages[].dataSources`, and a privilege's `access`. Those+// are marked `scalar` below and only have their array-ness enforced. A string entry in an OBJECT+// collection is harmless anyway: property access on a string yields undefined rather than throwing,+// so the existing "missing <field>" checks already report it.+'use strict';++// Declarative map of every collection either gate traverses, and the collections nested inside them.+// A recursive descriptor (rather than the flat per-owner lists this started as) is the point: the+// flat version silently omitted `views[].filters`, `forms[].tabs`, `pages[].dataSources` and+// `commands[].buttons[].children`, each of which still crashed lint. Adding a path here is now the+// single edit required to cover it.+// `scalar: true` → enforce array-ness only; entries are legitimately strings.+// `children` → collections nested on each entry of this collection.+const COLLECTIONS = {+ entities: { children: { columns: {}, alternateKeys: {}, statusReasons: {} } },+ relationships: {},+ globalChoices: {},+ webResources: {},+ views: { children: { filters: {}, columns: { scalar: true } } },+ charts: {},+ forms: { children: { subgrids: {}, events: {}, quickViews: {}, tabs: { children: { sections: {} } } } },+ commands: { children: { buttons: { children: { children: {} } } } },+ dashboards: { children: { tiles: {} } },+ pages: { children: { navigatesTo: {}, dataSources: { scalar: true } } },+ personas: { children: { jobs: { children: { privileges: {} } }, additionalPrivileges: {} } },+};++// appShell is an OBJECT at the root (not a collection), so its areas→groups→subAreas chain is walked+// separately. It is reshaped constantly while navigation is being designed, which makes a non-array+// at any of its three levels a realistic mid-edit state rather than a pathological one.+const APP_SHELL_COLLECTIONS = { areas: { children: { groups: { children: { subAreas: {} } } } } };++const isRecord = (v) => !!v && typeof v === 'object' && !Array.isArray(v);++// Normalize the collections described by `descriptors` on `owner`. Returns `owner` unchanged (same+// reference) when nothing needed fixing, so a well-formed spec leaves object identity intact for+// anything downstream that compares references.+// `path` is the dotted location used in messages ('' at the root, so root-level wording stays the+// historical `entities must be an array` that other callers and tests already read).+function normalizeCollections(owner, descriptors, path, errors) {+ if (!isRecord(owner)) return owner;+ let out = owner;+ const edit = () => { if (out === owner) out = { ...owner }; return out; };++ for (const [key, descriptor] of Object.entries(descriptors)) {+ const value = owner[key];+ if (value === undefined) continue;+ const here = path ? `${path}.${key}` : key;++ if (!Array.isArray(value)) {+ errors.push(`${here} must be an array`);+ edit()[key] = [];+ continue;+ }+ if (descriptor.scalar) continue; // array-ness enforced; entries are legitimately strings++ let changed = false;+ const next = value.map((item, i) => {+ // A hole is a real defect (a deleted entry), so report it rather than quietly healing it.+ if (item === null || item === undefined) {+ errors.push(`${here}[${i}] must be an object`);+ changed = true;+ return {};+ }+ if (!descriptor.children) return item;+ const fixed = normalizeCollections(item, descriptor.children, `${here}[${i}]`, errors);+ if (fixed !== item) changed = true;+ return fixed;+ });+ if (changed) edit()[key] = next;+ }+ return out;+}++// Return `{ spec, errors }` where `spec` is safe to walk with plain `for...of` / `.map()` over any+// known collection. NEVER mutates the caller's spec — a validator that rewrote its input would+// corrupt the very document the author is still editing.+//+// ROOT collections are always materialized as arrays, including absent ones. That is deliberate and+// predates this module: the code both gates share was written against a spec whose top-level+// collections are guaranteed to exist, so quietly making that conditional would be a behaviour+// change dressed up as an optimization. NESTED collections are only touched when something is+// actually wrong, so an entity that never declared `columns` does not suddenly gain an empty one.+function normalizeSpecShape(spec) {+ const errors = [];+ if (!isRecord(spec)) return { spec, errors };++ const normalized = normalizeCollections(spec, COLLECTIONS, '', errors);+ const out = normalized === spec ? { ...spec } : normalized;+ for (const key of Object.keys(COLLECTIONS)) {+ if (!Array.isArray(out[key])) out[key] = [];+ }++ if (isRecord(spec.appShell)) {+ const shell = normalizeCollections(spec.appShell, APP_SHELL_COLLECTIONS, 'appShell', errors);+ if (shell !== spec.appShell) out.appShell = shell;+ }++ return { spec: out, errors };+}++module.exports = { normalizeSpecShape, COLLECTIONS };diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 37d88345e..9318bb74c 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -39,9 +39,15 @@ async function verifySpec(spec, read, opts = {}) {// (reconcileView is additive-union, so a removed/renamed spec column would otherwise silently NOT// apply and still pass an existence-only verify). Best-effort: the column check only runs when the// deployed row actually carries layoutxml — an existence-only reader (no layoutxml) skips it.- const rows = await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });+ let rows = [];+ let readError = null;+ try {+ rows = await read.queryRecords('savedquery', { select: ['savedqueryid', 'layoutxml'], filter: `returnedtypecode eq '${String(v.entity).toLowerCase()}' and name eq '${odataLit(v.name)}'`, top: 1 });+ } catch (error) {+ readError = error;+ }const row = rows && rows[0];- add('view', viewName, row);+ add('view', viewName, row, readError ? String(readError.message || readError) : '');const specCols = (v.columns || []).map((c) => String(c).toLowerCase());if (row && row.layoutxml && specCols.length) {// Deployed column set from the saved view's layoutxml (<cell name="…"/> per column). We requirediff --git a/plugins/model-apps/scripts/smoke-eval.js b/plugins/model-apps/scripts/smoke-eval.jsindex 9ce71f459..30f678d96 100644--- a/plugins/model-apps/scripts/smoke-eval.js+++ b/plugins/model-apps/scripts/smoke-eval.js@@ -15,12 +15,25 @@ const { spawnSync } = require('node:child_process');// A minimal 1x1 transparent PNG (base64) for the nav-icon web resource.const PNG_1x1 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';+// A minimal square SVG (base64) for the vector nav-icon web resource:+// <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 4h16v16H4z"/></svg>+const SVG_SQUARE = 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZD0iTTQgNGgxNnYxNkg0eiIvPjwvc3ZnPg==';// A canonical smoke spec exercising the shipped features: an entity with columns (so default views-// enrich), an image web resource, and a subarea with a raster icon + a Fluent vectorIcon.+// enrich), raster + SVG web resources, and two subareas that pin BOTH directions of the entity+// `vectorIcon` contract (see appDef in lib/sdk-build.js):+// 1. a PLATFORM REF (`/WebResources/<name>.svg`) — emitted verbatim, so a custom nav glyph and the+// download->build round-trip survive. This is the shape a real app carries.+// 2. a BARE Fluent TOKEN ("Grid") — deliberately DROPPED on an entity subarea, because that shape+// breaks the modern app-designer property pane. Kept as a live NEGATIVE CONTROL so the drop is+// proven against the org rather than trusted from a code comment; validateAppSpec warns about+// it by design (warnings are non-blocking), which the unit tests assert is intentional.+// The bare token used to sit on the ONLY subarea while the assertion demanded VectorIcon="Grid" in+// the deployed sitemap — an outcome the builder can never produce, so the live smoke could only fail.function buildSmokeSpec(prefix = 'smk') {const ent = `new_${prefix}order`;const icon = `new_${prefix}icon.png`;+ const vectorIcon = `new_${prefix}vec.svg`;return {solution: { uniqueName: `${prefix}SmokeSln`, displayName: `${prefix} smoke`, publisherPrefix: 'new' },app: { name: `${prefix} Smoke App`, description: 'smoke eval' },@@ -35,21 +48,43 @@ function buildSmokeSpec(prefix = 'smk') {],},],- webResources: [{ name: icon, displayName: 'Smoke Icon', type: 'png', contentBase64: PNG_1x1 }],+ webResources: [+ { name: icon, displayName: 'Smoke Icon', type: 'png', contentBase64: PNG_1x1 },+ { name: vectorIcon, displayName: 'Smoke Vector Icon', type: 'svg', contentBase64: SVG_SQUARE },+ ],views: [],charts: [],forms: [],commands: [],dashboards: [],- appShell: { areas: [{ label: 'Main', icon, groups: [{ label: 'Records', subAreas: [{ entity: ent, title: 'Orders', icon, vectorIcon: 'Grid' }] }] }] },+ appShell: {+ areas: [{+ label: 'Main',+ icon,+ groups: [{+ label: 'Records',+ subAreas: [+ { entity: ent, title: 'Orders', icon, vectorIcon: `/WebResources/${vectorIcon}` },+ { entity: ent, title: 'Orders (token)', icon, vectorIcon: 'Grid' },+ ],+ }],+ }],+ },};}// Run the server-side assertions against a deployed app. `read` is { queryRecords(set, opts) ->// rows, sitemapXml(appId) -> xml }. Returns [{ name, ok, detail }].+//+// Expectations are stated from the CONTRACT (the spec's authored values + the documented drop rule),+// never derived from `appDef`. Deriving them would make this eval unable to contradict the very code+// it exists to check: when appDef stops emitting a value, a derived "must be present" assertion+// silently becomes "must be absent" and still passes. Keeping the expectation independent is what+// makes a live FAIL possible. The offline suite (scripts/tests/smoke-eval.test.js) carries the other+// half of the guarantee — that buildSmokeSpec and appDef still AGREE with this contract — so an+// unsatisfiable assertion is caught before anyone spends a live run on it.async function runSmokeAssertions(spec, appId, read) {const ent = spec.entities[0].schemaName.toLowerCase();- const iconName = spec.webResources[0].name.toLowerCase();const results = [];const views = (await read.queryRecords('savedquery', { select: ['name', 'layoutxml'], filter: `returnedtypecode eq '${ent}' and querytype eq 0` })) || [];@@ -57,13 +92,64 @@ async function runSmokeAssertions(spec, appId, read) {results.push({ name: 'default view enriched (has new_status column)', ok: enriched, detail: `${views.length} querytype-0 views` });const xml = (await read.sitemapXml(appId)) || '';- results.push({ name: `sitemap subarea carries Icon="${iconName}"`, ok: xml.toLowerCase().includes(`icon="${iconName}"`), detail: '' });- results.push({ name: 'sitemap subarea carries VectorIcon="Grid"', ok: /VectorIcon="Grid"/.test(xml), detail: '' });+ // Subarea 0 declares a PLATFORM-REF vectorIcon (must round-trip); subarea 1 declares a BARE Fluent+ // token (must be dropped). buildSmokeSpec fixes these roles and the unit tests pin them.+ const subAreas = (((spec.appShell || {}).areas || [])[0] || {}).groups || [];+ const [refSub, tokenSub] = (subAreas[0] || {}).subAreas || [];++ for (const [sub, label] of [[refSub, 'platform-ref'], [tokenSub, 'bare-token']]) {+ if (!sub) { results.push({ name: `smoke spec is missing its ${label} subarea`, ok: false, detail: 'buildSmokeSpec shape changed' }); continue; }+ const tag = subAreaTag(xml, sub.title);+ // A collapsed nav must FAIL rather than vacuously satisfy the icon checks below.+ results.push({ name: `sitemap contains subarea "${sub.title}"`, ok: !!tag, detail: tag ? '' : 'no matching <SubArea> in the deployed sitemap' });+ if (!tag) continue;+ results.push({ name: `subarea "${sub.title}" carries Icon="${sub.icon}"`, ok: hasSitemapAttr(tag, 'Icon', sub.icon), detail: '' });+ }++ if (refSub) {+ const tag = subAreaTag(xml, refSub.title);+ results.push({ name: `subarea "${refSub.title}" carries VectorIcon="${refSub.vectorIcon}"`, ok: !!tag && hasSitemapAttr(tag, 'VectorIcon', refSub.vectorIcon), detail: 'a platform-ref vectorIcon must round-trip onto an entity subarea' });+ }+ if (tokenSub) {+ // Document-scoped on purpose: a bare Fluent token must appear NOWHERE in the sitemap, so this+ // also catches it leaking onto a different element than the one that declared it.+ results.push({ name: `bare token VectorIcon="${tokenSub.vectorIcon}" is absent from the sitemap`, ok: !hasSitemapAttr(xml, 'VectorIcon', tokenSub.vectorIcon), detail: 'a bare token on an entity subarea breaks the app designer and must be dropped' });+ }results.push({ name: 'app module was created', ok: !!appId, detail: appId || '(none)' });return results;}+// Escape a value for embedding in a RegExp source string.+const escapeRe = (v) => String(v).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++// The OPEN TAG of the <SubArea> whose title is `title`, or '' when there is none. The sitemap nests+// the label as a child, e.g.:+// <SubArea Id="sub_0_0_0" Entity="new_torder" … Icon="x.png" VectorIcon="/WebResources/y.svg">+// <Titles><Title LCID="1033" Title="Orders" /></Titles>+// </SubArea>+// Located by the SPEC's authored title rather than the builder's generated `Id`, so the eval does not+// take its bearings from the component under test. The lookahead stops the lazy scan at the next+// <SubArea>, so a title can never be matched against a LATER subarea's tag. Only the open tag is+// returned: attribute checks must not be satisfiable by the nested <Title Title="…"> attribute, nor+// by the parent <Area Icon="…"> (the smoke spec deliberately reuses one icon across area + subareas,+// so a document-wide scan would let <Area> alone satisfy every subarea icon assertion).+function subAreaTag(xml, title) {+ const re = new RegExp(`<SubArea\\b[^>]*>(?:(?!<SubArea\\b)[\\s\\S])*?<Title\\b[^>]*\\bTitle="${escapeRe(title)}"`, 'i');+ const m = re.exec(String(xml || ''));+ if (!m) return '';+ const open = /^<SubArea\b[^>]*>/i.exec(m[0]);+ return open ? open[0] : '';+}++// Match a sitemap attribute exactly within `fragment`. `\b` before the name keeps `Icon="x"` from+// matching inside `VectorIcon="x"` (there is no word boundary between `r` and `I`), which a plain+// substring check does not. Matching is case-insensitive because Dataverse lower-cases bare+// web-resource names; the VALUE is regex-escaped so a path's `/` and `.` stay literal.+function hasSitemapAttr(fragment, attr, value) {+ return new RegExp(`\\b${attr}="${escapeRe(value)}"`, 'i').test(String(fragment || ''));+}+// --- live orchestration -----------------------------------------------------------------function pluginScript(name) {@@ -179,4 +265,4 @@ if (require.main === module) {main(env, prefix).then((code) => process.exit(code));}-module.exports = { buildSmokeSpec, runSmokeAssertions };+module.exports = { buildSmokeSpec, runSmokeAssertions, subAreaTag, hasSitemapAttr };diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.jsindex e940c220b..473323512 100644--- a/plugins/model-apps/scripts/tests/app-spec.test.js+++ b/plugins/model-apps/scripts/tests/app-spec.test.js@@ -17,6 +17,19 @@ test('validateAppSpec accepts the sample', () => {assert.strictEqual(r.ok, true, JSON.stringify(r.errors));});+test('validateAppSpec returns structured errors for malformed collections instead of throwing', () => {+ for (const spec of [+ { entities: {} },+ { forms: {} },+ { entities: [null] },+ { forms: [null] },+ ]) {+ assert.doesNotThrow(() => validateAppSpec(spec));+ const result = validateAppSpec(spec);+ assert.equal(result.ok, false, JSON.stringify(spec));+ }+});+test('relationshipSchemaName: all-custom default is unchanged (backward compatible)', () => {const rel = { type: 'OneToMany', referenced: 'new_customer', referencing: 'new_ticket' };assert.strictEqual(relationshipSchemaName(rel, 'new'), 'new_customer_new_ticket');@@ -1058,4 +1071,4 @@ test('validateAppSpec detects whitespace-distinct persona names as duplicates (S{ persona: ' Agent ', jobs: [{ name: 'b', privileges: [{ entity: 'pt_task', access: ['read'] }] }] },]));assert.ok(!r.ok && r.errors.some((e) => /duplicate persona name/.test(e)), JSON.stringify(r.errors));-});+});diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex bdd80d581..0cc9490df 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -8,17 +8,57 @@ const { resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata,test('resolveAppId returns a guid as-is, else resolves by uniquename', async () => {const guid = '11111111-2222-3333-4444-555555555555';- assert.strictEqual(await resolveAppId({}, guid), guid);+ assert.deepStrictEqual(await resolveAppId({}, guid), { appId: guid });const sdk = { queryRecords: async (l, o) => { assert.match(o.filter, /uniquename eq 'new_app'/); return [{ appmoduleid: 'app-1' }]; } };- assert.strictEqual(await resolveAppId(sdk, 'new_app'), 'app-1');+ assert.deepStrictEqual(await resolveAppId(sdk, 'new_app'), { appId: 'app-1', matchedBy: 'uniqueName' });});-test('resolveAppId escapes apostrophes and returns undefined for a missing app', async () => {+test('resolveAppId escapes apostrophes and reports an actionable error for a missing app', async () => {const calls = [];const sdk = { queryRecords: async (logical, opts) => { calls.push({ logical, opts }); return []; } };- assert.strictEqual(await resolveAppId(sdk, "new_bob's_app"), undefined);+ const r = await resolveAppId(sdk, "new_bob's_app");+ assert.match(r.error, /not found/);+ // The dead-end "app 'x' not found" gave an operator holding a display name nowhere to go.+ assert.match(r.error, /unique name/);+ assert.strictEqual(r.appId, undefined);assert.strictEqual(calls[0].logical, 'appmodule');assert.match(calls[0].opts.filter, /uniquename eq 'new_bob''s_app'/);+ // The display-name fallback must escape the apostrophe the same way, or it is an OData syntax error.+ assert.match(calls[1].opts.filter, /name eq 'new_bob''s_app'/);+});++// A live tester hit this: the maker portal shows a DISPLAY name, but --app only accepted the unique+// name, so the obvious input failed with a dead-end error.+test('resolveAppId falls back to an unambiguous display name and reports the unique name', async () => {+ const sdk = {+ queryRecords: async (_l, o) => (/uniquename eq/.test(o.filter) ? [] : [{ appmoduleid: 'app-9', uniquename: 'new_smokeapp', name: 'Smoke App' }]),+ };+ assert.deepStrictEqual(await resolveAppId(sdk, 'Smoke App'), { appId: 'app-9', matchedBy: 'displayName', uniqueName: 'new_smokeapp' });+});++// Display names are mutable AND non-unique, so guessing could download a different app than the+// operator meant — refuse and hand back the unique names instead.+test('resolveAppId fails closed when a display name matches more than one app', async () => {+ const sdk = {+ queryRecords: async (_l, o) => (/uniquename eq/.test(o.filter) ? [] : [+ { appmoduleid: 'app-1', uniquename: 'new_sales', name: 'Sales' },+ { appmoduleid: 'app-2', uniquename: 'contoso_sales', name: 'Sales' },+ ]),+ };+ const r = await resolveAppId(sdk, 'Sales');+ assert.strictEqual(r.appId, undefined, 'must not pick one of the ambiguous matches');+ assert.match(r.error, /shared by 2 apps/);+ assert.match(r.error, /new_sales, contoso_sales/);+});++// A GUID is authoritative: resolving it must not cost a query, and must never reach the+// display-name fallback (an app DISPLAY-named like a GUID could otherwise shadow a real id).+test('resolveAppId issues no query for a GUID', async () => {+ let queried = false;+ const sdk = { queryRecords: async () => { queried = true; return []; } };+ const r = await resolveAppId(sdk, 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');+ assert.strictEqual(r.appId, 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');+ assert.strictEqual(queried, false);});test('collectSitemap gathers distinct entities + icons from the sitemap', () => {diff --git a/plugins/model-apps/scripts/tests/preview-app.test.js b/plugins/model-apps/scripts/tests/preview-app.test.jsindex 940ce312c..862938de2 100644--- a/plugins/model-apps/scripts/tests/preview-app.test.js+++ b/plugins/model-apps/scripts/tests/preview-app.test.js@@ -83,3 +83,19 @@ test('malformed JSON exits non-zero before a partial preview is printed', () =>assert.equal(res.stdout, '');assert.match(res.stderr, /SyntaxError/);});++test('renders scalar persona privilege access without crashing', () => {+ const specPath = writeSpec({+ personas: [+ {+ persona: 'Support',+ jobs: [{ name: 'Read tickets', privileges: [{ entity: 'new_ticket', access: 'read' }] }],+ },+ ],+ });++ const res = run(['--spec', '@' + specPath]);++ assert.equal(res.status, 0, res.stderr);+ assert.match(res.stdout, /new_ticket: read @ user/);+});diff --git a/plugins/model-apps/scripts/tests/smoke-eval.test.js b/plugins/model-apps/scripts/tests/smoke-eval.test.jsindex d37a26d21..9a809c859 100644--- a/plugins/model-apps/scripts/tests/smoke-eval.test.js+++ b/plugins/model-apps/scripts/tests/smoke-eval.test.js@@ -1,8 +1,34 @@'use strict';const { test } = require('node:test');const assert = require('node:assert');-const { buildSmokeSpec, runSmokeAssertions } = require('../smoke-eval.js');+const { buildSmokeSpec, runSmokeAssertions, subAreaTag, hasSitemapAttr } = require('../smoke-eval.js');const { validateAppSpec } = require('../lib/app-spec.js');+const { appDef } = require('../lib/sdk-build.js');++// Render the sitemap XML the platform returns for a built spec, FROM the definition the builder+// actually emits (including the parent <Area> icon and the nested <Titles> the real SDK writes).+// This is a faithful stand-in for the org, not a statement of what we want to see: the live+// assertions carry their own expectations, so if appDef stops emitting a value this XML stops+// containing it and the assertion FAILS — which is how the offline suite now catches, before a live+// run, the class of defect that previously only showed up against a real org.+function sitemapXmlFor(spec) {+ const def = appDef(spec, { forms: {}, views: {}, charts: {}, dashboards: {}, pages: {} });+ const area = def.siteMap.areas[0];+ const subs = area.groups[0].subAreas.map((s) => {+ const attrs = [+ `Id="${s.id}"`,+ s.entity ? `Entity="${s.entity}"` : '',+ s.icon !== undefined ? `Icon="${s.icon}"` : '',+ s.vectorIcon !== undefined ? `VectorIcon="${s.vectorIcon}"` : '',+ ].filter(Boolean);+ return `<SubArea ${attrs.join(' ')}><Titles><Title LCID="1033" Title="${s.title}" /></Titles></SubArea>`;+ });+ return `<SiteMap><Area Id="${area.id}"${area.icon ? ` Icon="${area.icon}"` : ''}><Titles><Title LCID="1033" Title="${area.title}" /></Titles>`+ + `<Group Id="${area.groups[0].id}">${subs.join('')}</Group></Area></SiteMap>`;+}++const enrichedViews = async () => [{ name: 'Active t Orders', layoutxml: '<grid><row><cell name="new_name"/><cell name="new_status"/></row></grid>' }];+const runAgainst = (spec, xml) => runSmokeAssertions(spec, 'app-1', { queryRecords: enrichedViews, sitemapXml: async () => xml });test('buildSmokeSpec produces a valid spec that exercises icons + default-view enrichment', () => {const spec = buildSmokeSpec('t');@@ -10,26 +36,120 @@ test('buildSmokeSpec produces a valid spec that exercises icons + default-view eassert.strictEqual(r.ok, true, JSON.stringify(r.errors));assert.strictEqual(spec.entities[0].columns.length, 2, 'has extra columns so default views enrich');assert.ok(spec.appShell.areas[0].groups[0].subAreas[0].icon, 'subarea has a raster icon');- assert.strictEqual(spec.appShell.areas[0].groups[0].subAreas[0].vectorIcon, 'Grid');+ assert.ok(spec.webResources.some((w) => w.type === 'svg'), 'declares an SVG web resource for the vector nav icon');+});++// The roles the live assertions depend on. If these two subareas are ever reordered or reshaped, the+// live eval starts asserting the wrong thing, so pin them here rather than in a comment.+test('the smoke spec fixes subarea 0 as the platform-ref case and subarea 1 as the bare-token case', () => {+ const [refSub, tokenSub] = buildSmokeSpec('t').appShell.areas[0].groups[0].subAreas;+ assert.strictEqual(refSub.vectorIcon, '/WebResources/new_tvec.svg');+ assert.strictEqual(tokenSub.vectorIcon, 'Grid');+ assert.ok(refSub.entity && tokenSub.entity, 'both are ENTITY subareas — that is the case the drop rule is about');+ assert.notStrictEqual(refSub.title, tokenSub.title, 'titles must differ; they are how the sitemap subareas are located');});-test('runSmokeAssertions passes when the deployed app is correct', async () => {+// The regression this file exists to prevent: a vectorIcon the smoke spec DECLARES on subarea 0 must+// be one the builder actually EMITS, or the live assertion is unsatisfiable. A bare Fluent token+// fails this, which is why "Grid" alone could never pass live.+test('the smoke spec asks for a vectorIcon the builder actually emits', () => {const spec = buildSmokeSpec('t');- const read = {- queryRecords: async () => [{ name: 'Active t Orders', layoutxml: '<grid><row><cell name="new_name"/><cell name="new_status"/></row></grid>' }],- sitemapXml: async () => '<SiteMap><SubArea Icon="new_ticon.png" VectorIcon="Grid"/></SiteMap>',- };- const results = await runSmokeAssertions(spec, 'app-1', read);- assert.ok(results.every((r) => r.ok), JSON.stringify(results));+ const emitted = appDef(spec, { forms: {}, views: {}, charts: {}, dashboards: {}, pages: {} }).siteMap.areas[0].groups[0].subAreas;+ assert.strictEqual(emitted[0].vectorIcon, '/WebResources/new_tvec.svg', 'platform-ref vectorIcon survives appDef on an Entity subarea');+ assert.strictEqual(emitted[0].icon, 'new_ticon.png');+ assert.strictEqual(emitted[1].vectorIcon, undefined, 'the bare token is dropped from the emitted definition');+});++// The negative control is deliberate, not an authoring mistake: validateAppSpec must WARN about the+// bare token rather than reject the spec, or the smoke build would refuse to run at all.+test('a bare Fluent token on an entity subarea is warned about, not rejected', () => {+ const r = validateAppSpec(buildSmokeSpec('t'));+ assert.strictEqual(r.ok, true, 'a dropped vectorIcon is a warning, never a build-blocking error');+ assert.strictEqual((r.warnings || []).filter((w) => /vectorIcon 'Grid' is a bare token/.test(w)).length, 1);+});++test('runSmokeAssertions passes against the sitemap the builder actually produces', async () => {+ const spec = buildSmokeSpec('t');+ const results = await runAgainst(spec, sitemapXmlFor(spec));+ assert.ok(results.every((r) => r.ok), JSON.stringify(results, null, 1));});test('runSmokeAssertions fails when enrichment or icons are missing', async () => {const spec = buildSmokeSpec('t');- const read = {+ const results = await runSmokeAssertions(spec, 'app-1', {queryRecords: async () => [{ name: 'Active t Orders', layoutxml: '<grid><row><cell name="new_name"/></row></grid>' }],sitemapXml: async () => '<SiteMap><SubArea/></SiteMap>',- };- const results = await runSmokeAssertions(spec, 'app-1', read);+ });assert.ok(results.some((r) => !r.ok && /enriched/.test(r.name)), 'enrichment assertion should fail');assert.ok(results.some((r) => !r.ok && /Icon/.test(r.name)), 'icon assertion should fail');});++// A regression that started writing bare tokens onto entity subareas again would still satisfy every+// positive assertion, so the negative control has to be the thing that fails.+test('runSmokeAssertions fails when the bare token reappears in the deployed sitemap', async () => {+ const spec = buildSmokeSpec('t');+ const xml = sitemapXmlFor(spec).replace(/(<SubArea\b[^>]*Id="sub_0_0_1"[^>]*?)>/, '$1 VectorIcon="Grid">');+ assert.match(xml, /VectorIcon="Grid"/, 'the fixture must actually contain the regressed value');+ const results = await runAgainst(spec, xml);+ const control = results.find((r) => /bare token VectorIcon="Grid" is absent/.test(r.name));+ assert.ok(control && !control.ok, 'negative control must fail when the bare token is emitted again');+});++// THE key guard. The eval's expectations must NOT be derived from appDef: if they were, a builder+// that stopped emitting the vectorIcon would flip "must be present" into "must be absent" and the+// live run would report PASS while shipping apps with no nav glyph.+test('runSmokeAssertions FAILS when the builder stops emitting the platform-ref vectorIcon', async () => {+ const spec = buildSmokeSpec('t');+ // A deployed sitemap exactly as a regressed builder (one that drops ALL entity vectorIcons) leaves it.+ const xml = sitemapXmlFor(spec).replace(/ VectorIcon="[^"]*"/g, '');+ const results = await runAgainst(spec, xml);+ const positive = results.find((r) => /carries VectorIcon="\/WebResources\/new_tvec\.svg"/.test(r.name));+ assert.ok(positive && !positive.ok, 'the missing platform-ref vectorIcon must be reported as a FAILURE');+ assert.ok(!results.every((r) => r.ok), 'the eval as a whole must fail');+});++// A nav that collapses to nothing must fail loudly rather than vacuously satisfy every check.+test('runSmokeAssertions fails when the deployed sitemap has no subareas at all', async () => {+ const spec = buildSmokeSpec('t');+ const results = await runAgainst(spec, '<SiteMap><Area Id="area_0" Icon="new_ticon.png"><Group Id="group_0_0"></Group></Area></SiteMap>');+ assert.ok(results.some((r) => !r.ok && /contains subarea "Orders"/.test(r.name)), 'a missing subarea must be reported');+ assert.ok(!results.every((r) => r.ok));+});++// The smoke spec reuses one raster icon on the AREA and both subareas, so a document-wide scan would+// let <Area Icon="…"> alone satisfy every per-subarea icon assertion.+test('a subarea icon assertion is not satisfied by the parent Area icon', async () => {+ const spec = buildSmokeSpec('t');+ // Strip Icon from the SubArea elements only; the Area keeps its identical icon.+ const xml = sitemapXmlFor(spec).replace(/(<SubArea\b[^>]*?) Icon="[^"]*"/g, '$1');+ assert.match(xml, /<Area\b[^>]*Icon="new_ticon\.png"/, 'the Area still carries the same icon value');+ const results = await runAgainst(spec, xml);+ const iconChecks = results.filter((r) => /carries Icon=/.test(r.name));+ assert.strictEqual(iconChecks.length, 2, 'both subareas are icon-checked');+ assert.ok(iconChecks.every((r) => !r.ok), 'neither may be satisfied by the Area-level icon');+});++test('subAreaTag returns only the matching SubArea open tag', () => {+ const xml = '<SiteMap><Area Id="area_0" Icon="area.png"><Titles><Title Title="Main" /></Titles>'+ + '<SubArea Id="a" Icon="one.png"><Titles><Title LCID="1033" Title="Orders" /></Titles></SubArea>'+ + '<SubArea Id="b" Icon="two.png" VectorIcon="Grid"><Titles><Title LCID="1033" Title="Orders (token)" /></Titles></SubArea>'+ + '</Area></SiteMap>';+ assert.match(subAreaTag(xml, 'Orders'), /Id="a"/);+ // "Orders" must not match the LATER "Orders (token)" subarea, and vice versa — parentheses in the+ // title are regex metacharacters and must be escaped.+ assert.match(subAreaTag(xml, 'Orders (token)'), /Id="b"/);+ assert.ok(!/Id="b"/.test(subAreaTag(xml, 'Orders')), 'the lazy scan must stop at the next <SubArea>');+ assert.strictEqual(subAreaTag(xml, 'Nope'), '', 'absent title yields no tag');+ // Only the OPEN tag is returned, so a nested <Title Title="…"> can never satisfy an attribute check.+ assert.ok(!/<Titles>/.test(subAreaTag(xml, 'Orders')));+});++test('hasSitemapAttr matches whole attribute names and escapes path values', () => {+ const tag = '<SubArea Id="a" Icon="new_ticon.png" VectorIcon="/WebResources/new_tvec.svg">';+ assert.strictEqual(hasSitemapAttr(tag, 'VectorIcon', '/WebResources/new_tvec.svg'), true);+ assert.strictEqual(hasSitemapAttr(tag, 'Icon', 'new_ticon.png'), true);+ // `Icon` must not match inside `VectorIcon` — a substring check would conflate the two.+ assert.strictEqual(hasSitemapAttr(tag, 'Icon', '/WebResources/new_tvec.svg'), false);+ // `.` and `/` in a platform ref must stay literal, not act as regex metacharacters.+ assert.strictEqual(hasSitemapAttr(tag, 'VectorIcon', '/WebResources/new_tvecXsvg'), false);+});diff --git a/plugins/model-apps/scripts/tests/spec-lint.test.js b/plugins/model-apps/scripts/tests/spec-lint.test.jsindex 6718bdb2e..fba4fc488 100644--- a/plugins/model-apps/scripts/tests/spec-lint.test.js+++ b/plugins/model-apps/scripts/tests/spec-lint.test.js@@ -21,6 +21,20 @@ test('a clean spec passes with no errors', () => {assert.strictEqual(r.errors.length, 0);});+test('malformed top-level collections return lint errors instead of throwing', () => {+ for (const spec of [+ null,+ { entities: {} },+ { relationships: {} },+ { forms: {} },+ { entities: [null] },+ ]) {+ assert.doesNotThrow(() => lintAppSpec(spec));+ const result = lintAppSpec(spec);+ assert.equal(result.ok, false, JSON.stringify(spec));+ }+});+test('a view named like the stock default ("Active <Plural>") WARNS about the merge-onto-default collision', () => {const s = base();s.views = [{ entity: 'new_ticket', name: 'Active Tickets', columns: ['new_name', 'new_priority'], activeOnly: true }];@@ -379,4 +393,4 @@ test('lint accepts a v2 page subarea referenced by KEY when key !== name (no falconst bad = JSON.parse(JSON.stringify(spec));bad.appShell.areas[0].groups[0].subAreas[0].page = 'nope-not-a-page';assert.ok(lintAppSpec(bad).errors.some((e) => /unknown page/i.test(e)), 'an unknown page ref still errors');-});+});diff --git a/plugins/model-apps/scripts/tests/spec-shape.test.js b/plugins/model-apps/scripts/tests/spec-shape.test.jsnew file mode 100644index 000000000..23cb499a7--- /dev/null+++ b/plugins/model-apps/scripts/tests/spec-shape.test.js@@ -0,0 +1,169 @@+'use strict';+// Both authoring gates run on WORK-IN-PROGRESS specs, so every shape below is a realistic mid-edit+// state, not a pathological one: a collection still being reshaped (`{}`), or a hole left behind by+// deleting an entry (`[null]`). Each of these threw a raw TypeError before the shared normalizer —+// "object is not iterable" from `for...of`, "map is not a function", or a null dereference — which+// killed the authoring flow instead of reporting the problem.+const { test } = require('node:test');+const assert = require('node:assert');+const { validateAppSpec, migrateAppSpec } = require('../lib/app-spec.js');+const { lintAppSpec } = require('../lib/spec-lint.js');+const { normalizeSpecShape } = require('../lib/spec-shape.js');++const base = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' } };+const ent0 = [{ schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_name', displayName: 'N' }, columns: [] }];+const withEntity = (extra) => ({+ ...base,+ entities: [{ schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_name', displayName: 'N' }, columns: [], ...extra }],+});+const shell = (areas) => ({ ...withEntity({}), appShell: { areas } });++// Every gate must survive these; the message text is asserted separately below.+const MALFORMED = [+ ['entity.columns = {}', withEntity({ columns: {} })],+ ['entity.columns = "x"', withEntity({ columns: 'x' })],+ ['entity.alternateKeys = {}', withEntity({ alternateKeys: {} })],+ ['entity.statusReasons = {}', withEntity({ statusReasons: {} })],+ ['entity.columns = [null]', withEntity({ columns: [null] })],+ ['appShell.areas = {}', shell({})],+ ['area.groups = {}', shell([{ label: 'A', groups: {} }])],+ ['group.subAreas = {}', shell([{ label: 'A', groups: [{ label: 'G', subAreas: {} }] }])],+ ['areas = [null]', shell([null])],+ ['persona.jobs = {}', { ...withEntity({}), personas: [{ persona: 'P', jobs: {} }] }],+ ['job.privileges = {}', { ...withEntity({}), personas: [{ persona: 'P', jobs: [{ name: 'j', privileges: {} }] }] }],+ ['form.subgrids = {}', { ...withEntity({}), forms: [{ entity: 'new_t', subgrids: {} }] }],+ ['dashboard.tiles = {}', { ...withEntity({}), dashboards: [{ name: 'D', tiles: {} }] }],+];++for (const [label, spec] of MALFORMED) {+ test(`validateAppSpec returns a structured result (never throws) for ${label}`, () => {+ const r = validateAppSpec(spec);+ assert.ok(Array.isArray(r.errors), 'must return a structured result rather than throwing');+ });+ test(`lintAppSpec returns findings (never throws) for ${label}`, () => {+ const r = lintAppSpec(spec);+ assert.ok(Array.isArray(r.errors), 'must return a structured result');+ });+}++// A non-array is a shape ERROR; so is a null HOLE, because validation checks its own normalized COPY+// while the caller keeps the ORIGINAL. A silently-repaired `appShell.areas: [null]` used to PASS+// validation and then throw inside the build — after the solution and data model had been written.+test('every malformed shape BLOCKS validation, so the build never starts', () => {+ for (const [label, spec] of MALFORMED) {+ assert.strictEqual(validateAppSpec(spec).ok, false, `${label} must not pass validation`);+ }+});++test('a null entry is reported rather than silently repaired', () => {+ assert.ok(validateAppSpec(shell([null])).errors.includes('appShell.areas[0] must be an object'));+ assert.ok(validateAppSpec(withEntity({ columns: [null] })).errors.includes('entities[0].columns[0] must be an object'));+});++test('a non-array nested collection is named by its exact path, not reported generically', () => {+ assert.ok(validateAppSpec(withEntity({ columns: {} })).errors.includes('entities[0].columns must be an array'));+ assert.ok(validateAppSpec(shell({})).errors.includes('appShell.areas must be an array'));+ assert.ok(validateAppSpec(shell([{ label: 'A', groups: {} }])).errors.includes('appShell.areas[0].groups must be an array'));+ assert.ok(validateAppSpec(shell([{ label: 'A', groups: [{ label: 'G', subAreas: {} }] }])).errors.includes('appShell.areas[0].groups[0].subAreas must be an array'));+ // Both gates share one normalizer, so they cannot disagree about what a malformed spec is.+ assert.ok(lintAppSpec(withEntity({ columns: {} })).errors.includes('entities[0].columns must be an array'));+});++// These paths crashed lint even AFTER the first round of hardening, because the registry was a flat+// per-owner list that silently omitted them. They are the reason the descriptor is now recursive.+test('the deeper collections both gates traverse are covered', () => {+ const deep = [+ [{ ...base, entities: ent0, views: [{ entity: 'new_t', name: 'V', filters: {} }] }, 'views[0].filters must be an array'],+ [{ ...base, entities: ent0, forms: [{ entity: 'new_t', tabs: {} }] }, 'forms[0].tabs must be an array'],+ [{ ...base, entities: ent0, forms: [{ entity: 'new_t', tabs: [{ label: 't', sections: {} }] }] }, 'forms[0].tabs[0].sections must be an array'],+ [{ ...base, entities: ent0, pages: [{ key: 'p', name: 'P', dataSources: {} }] }, 'pages[0].dataSources must be an array'],+ [{ ...base, entities: ent0, pages: [{ key: 'p', name: 'P', navigatesTo: {} }] }, 'pages[0].navigatesTo must be an array'],+ [{ ...base, entities: ent0, commands: [{ entity: 'new_t', buttons: [{ label: 'b', children: {} }] }] }, 'commands[0].buttons[0].children must be an array'],+ ];+ for (const [spec, expected] of deep) {+ assert.ok(validateAppSpec(spec).errors.includes(expected), `validate: ${expected}`);+ assert.ok(Array.isArray(lintAppSpec(spec).errors), 'lint must not throw');+ assert.ok(lintAppSpec(spec).errors.includes(expected), `lint: ${expected}`);+ }+});++// Migration runs BEFORE validation at every CLI entry point, so it must neither crash nor REPAIR —+// repairing would hand the gate a clean spec and the real problem would vanish.+test('migrateAppSpec survives malformed collections without hiding them from validation', () => {+ for (const [spec, expected] of [+ [{ ...base, entities: ent0, pages: {} }, 'pages must be an array'],+ [{ ...base, entities: ent0, appShell: { areas: {} } }, 'appShell.areas must be an array'],+ [{ ...base, entities: ent0, appShell: { areas: [null] } }, 'appShell.areas[0] must be an object'],+ [{ ...base, entities: {} }, 'entities must be an array'],+ ]) {+ let migrated;+ assert.doesNotThrow(() => { migrated = migrateAppSpec(spec); }, 'migration must not crash before the gate runs');+ assert.ok(validateAppSpec(migrated).errors.includes(expected), `after migration the gate still reports: ${expected}`);+ }+});++// The root-level message text predates the shared normalizer and other callers/tests read it.+test('root-level collection errors keep their original unprefixed wording', () => {+ assert.ok(validateAppSpec({ ...base, entities: {} }).errors.includes('entities must be an array'));+ assert.ok(lintAppSpec({ ...base, entities: {} }).errors.includes('entities must be an array'));+});++// Scalar collections are legitimately arrays of strings. Coercing their entries to objects would+// destroy real values, so the normalizer must leave them exactly as authored.+test('normalizeSpecShape preserves scalar collections verbatim', () => {+ const spec = {+ ...base,+ entities: [{ schemaName: 'new_t', columns: [{ schemaName: 'new_c', type: 'Choice', options: ['Open', 'Closed'] }], alternateKeys: [{ schemaName: 'k', columns: ['new_c'] }] }],+ views: [{ entity: 'new_t', name: 'V', columns: ['new_name', 'new_c'] }],+ personas: [{ persona: 'P', jobs: [{ name: 'j', privileges: [{ entity: 'new_t', access: ['read', 'write'] }] }] }],+ };+ const { spec: out, errors } = normalizeSpecShape(spec);+ assert.deepStrictEqual(errors, []);+ assert.deepStrictEqual(out.entities[0].columns[0].options, ['Open', 'Closed']);+ assert.deepStrictEqual(out.entities[0].alternateKeys[0].columns, ['new_c']);+ assert.deepStrictEqual(out.views[0].columns, ['new_name', 'new_c']);+ assert.deepStrictEqual(out.personas[0].jobs[0].privileges[0].access, ['read', 'write']);+});++// A validator that rewrote its input would corrupt the document the author is still editing.+test('normalizeSpecShape never mutates the caller spec', () => {+ const spec = { ...base, entities: [{ schemaName: 'new_t', columns: {} }], appShell: { areas: {} } };+ const snapshot = JSON.stringify(spec);+ const { spec: out } = normalizeSpecShape(spec);+ assert.strictEqual(JSON.stringify(spec), snapshot, 'input is untouched');+ assert.notStrictEqual(out, spec);+ assert.deepStrictEqual(out.entities[0].columns, []);+ assert.deepStrictEqual(out.appShell.areas, []);+});++// The contract both gates were written against: every ROOT collection exists as an array afterwards,+// including ones the spec never declared. Making that conditional would be a behaviour change+// disguised as an optimization, so it is pinned. NESTED collections are the opposite — an entity+// that never declared `columns` must not silently gain an empty one.+test('normalizeSpecShape materializes absent root collections but not absent nested ones', () => {+ const { spec: out } = normalizeSpecShape({ ...base, entities: [{ schemaName: 'new_t' }] });+ for (const key of ['entities', 'relationships', 'globalChoices', 'webResources', 'views', 'charts', 'forms', 'commands', 'dashboards', 'pages', 'personas']) {+ assert.ok(Array.isArray(out[key]), `${key} must be materialized as an array`);+ }+ assert.strictEqual(out.entities[0].columns, undefined, 'an undeclared nested collection stays undeclared');+ assert.strictEqual(out.appShell, undefined, 'an absent appShell is not invented');+});++// A clean spec must pass through with its nested objects untouched by identity, so nothing+// downstream that compares references can be disturbed by validation.+test('normalizeSpecShape leaves well-formed nested objects by reference', () => {+ const entity = { schemaName: 'new_t', columns: [{ schemaName: 'new_c' }] };+ const area = { label: 'A', groups: [{ label: 'G', subAreas: [] }] };+ const { spec: out, errors } = normalizeSpecShape({ ...base, entities: [entity], appShell: { areas: [area] } });+ assert.deepStrictEqual(errors, []);+ assert.strictEqual(out.entities[0], entity, 'a clean entity is not copied');+ assert.strictEqual(out.appShell.areas[0], area, 'a clean area is not copied');+});++test('normalizeSpecShape tolerates a non-object spec without throwing', () => {+ for (const bad of [null, undefined, 'x', 42, []]) {+ const r = normalizeSpecShape(bad);+ assert.deepStrictEqual(r.errors, []);+ assert.strictEqual(r.spec, bad);+ }+});diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.jsindex 055640300..0b0602ef8 100644--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js@@ -530,3 +530,84 @@ test('CONTRACT: the vendored bundle still carries the exact SDK role-ownership m});++// A custom nav glyph — and the download->build round-trip — depend on a PLATFORM-REF `VectorIcon`+// surviving serialization onto an ENTITY subarea. Reading the minified bundle cannot prove that; only+// the serialized payload can, so assert the bytes the SDK would POST.+test('CONTRACT: a platform-ref VectorIcon on an Entity subarea reaches the serialized sitemap XML', async () => {+ const { createMakerSdk } = require(BUNDLE);+ const { appDef } = require('../lib/sdk-build.js');+ const { buildSmokeSpec } = require('../smoke-eval.js');+ const spec = buildSmokeSpec('t');+ const def = appDef(spec, { forms: {}, views: {}, charts: {}, dashboards: {}, pages: {} });++ let sitemapXml = '';+ const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';+ // The push resolves each sitemap table to an OData reference and reads the pinned components back,+ // both fail-closed — answer those reads (same shape as the escaping contract above) so an unrelated+ // refusal cannot masquerade as an icon-serialization failure.+ const httpClient = {+ get: async (url) => {+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);+ if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };+ if (/\/appmodulecomponents/.test(url)) return { status: 200, headers: {}, body: { value: [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };+ if (/\/appmodules/.test(url)) {+ const row = { appmoduleid: '11111111-1111-1111-1111-111111111111', appmoduleidunique: '33333333-3333-3333-3333-333333333333' };+ return { status: 200, headers: {}, body: /RetrieveUnpublishedMultiple/i.test(url) ? { value: [row] } : row };+ }+ return { status: 200, headers: {}, body: {} };+ },+ post: async (url, body) => {+ if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) sitemapXml = String(body.sitemapxml);+ return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} };+ },+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: mkTempWorkspace('sdk-vecicon-'), instanceUrl: 'https://example.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ const art = sdk.createArtifact('app', { name: spec.app.name, uniqueName: 'new_vecapp', description: '', siteMap: def.siteMap, components: def.components });+ await assert.doesNotReject(sdk.pushArtifact('app', art.id), 'the smoke spec must push without a component-verification refusal');++ assert.ok(sitemapXml, 'the sitemap was serialized and posted');+ assert.match(sitemapXml, /<SubArea[^>]*Entity="new_torder"[^>]*VectorIcon="\/WebResources\/new_tvec\.svg"/, 'platform-ref VectorIcon is serialized onto the Entity subarea');+ // The bare token is absent only because appDef already removed it — asserting that here would+ // re-test appDef, not the bundle. The test below establishes what the BUNDLE actually does.+ assert.ok(!/VectorIcon="Grid"/.test(sitemapXml), 'appDef removed the bare token before the payload reached the SDK');+});++// Establishes WHERE the bare-Fluent-token guard lives, by pushing a hand-built siteMap that bypasses+// appDef entirely. The vendored SDK happily serializes `VectorIcon="Grid"` onto an Entity subarea —+// it has no such guard — which is exactly why `appDef` must drop it (lib/sdk-build.js) and why the+// drop cannot be delegated to the bundle. If a future re-vendor ADDS a guard, this test fails and+// tells us the defense moved, rather than silently leaving two layers that both assume the other.+test('CONTRACT: the vendored SDK does NOT filter a bare Fluent VectorIcon — appDef is the only guard', async () => {+ const { createMakerSdk } = require(BUNDLE);+ let sitemapXml = '';+ const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';+ const httpClient = {+ get: async (url) => {+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);+ if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };+ if (/\/appmodulecomponents/.test(url)) return { status: 200, headers: {}, body: { value: [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };+ if (/\/appmodules/.test(url)) {+ const row = { appmoduleid: '11111111-1111-1111-1111-111111111111', appmoduleidunique: '33333333-3333-3333-3333-333333333333' };+ return { status: 200, headers: {}, body: /RetrieveUnpublishedMultiple/i.test(url) ? { value: [row] } : row };+ }+ return { status: 200, headers: {}, body: {} };+ },+ post: async (url, body) => { if (/\/sitemaps\b/.test(url) && body && body.sitemapxml) sitemapXml = String(body.sitemapxml); return { status: 204, headers: { 'odata-entityid': 'https://x/y(11111111-1111-1111-1111-111111111111)' }, body: {} }; },+ patch: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspacePath: mkTempWorkspace('sdk-vecraw-'), instanceUrl: 'https://example.crm.dynamics.com', httpClient });+ sdk.initWorkspace();+ const siteMap = { areas: [{ id: 'area_0', title: 'Main', groups: [{ id: 'g0', title: 'G', subAreas: [+ { id: 's0', title: 'Orders', type: 'Entity', entity: 'new_torder', vectorIcon: 'Grid' },+ ] }] }] };+ const art = sdk.createArtifact('app', { name: 'Raw Token', uniqueName: 'new_rawtoken', description: '', siteMap, components: { forms: [], views: [], charts: [] } });+ await sdk.pushArtifact('app', art.id);+ assert.match(sitemapXml, /<SubArea[^>]*Entity="new_torder"[^>]*VectorIcon="Grid"/, 'the bundle serializes a bare token when handed one — so the plugin must not hand it one');+});diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex 0e344b1db..fee4202cc 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -56,6 +56,28 @@ test('verifySpec: a missing entity skips its column checks', async () => {assert.ok(!r.checks.some((c) => c.kind === 'column'), 'no column checks when the entity is absent');});+test('verifySpec reports missing entities without propagating dependent Dataverse read errors', async () => {+ const spec = {+ entities: [{ schemaName: 'new_missing', columns: [] }],+ views: [{ entity: 'new_missing', name: 'Missing View' }],+ appShell: { areas: [] },+ };+ const read = {+ findTable: async () => null,+ findColumns: async () => [],+ queryRecords: async () => {+ throw new Error('HTTP 400 metadata cache: entity was not found');+ },+ sitemapXml: async () => '',+ };++ const r = await verifySpec(spec, read);++ assert.equal(r.ok, false);+ assert.ok(r.missing.some((m) => m.kind === 'entity'));+ assert.ok(r.missing.some((m) => m.kind === 'view'));+});+test('verifySpec: a Main form check is type-scoped — a same-named Quick View sibling does NOT satisfy it', async () => {const spec = { entities: [], views: [], charts: [], forms: [{ entity: 'zava_javavendor', name: 'Information', formType: 'Main' }], appShell: { areas: [] } };let captured;@@ -521,7 +543,7 @@ test('verifySpec: a missing persona role (or a foreign same-name role) is a loudassert.ok(r.missing.some((m) => m.kind === 'role' && m.name === 'Agent'));});-+// ── AI app features (ADO 6603383 / 6560699) ────────────────────────────────────────────────────// verifySpec had NO awareness of spec.ai, so a build whose every requested AI feature was skipped// (admin gate off) or silently not persisted still reported a clean PASS.@@ -584,9 +606,9 @@ const DEFAULT_SETTINGS = {NLChartDataVisualizationSetting: '1',m365copilotmodelappenabled: '0',};-const aiMissing = (r, feature) => r.missing.find((m) => m.kind === 'ai-feature' && m.name === feature);-// The override proof retries the ABSENT case with real backoff; these tests drive that path-// constantly, so they opt out of the delay. Retry BEHAVIOUR has its own dedicated test below.+const aiMissing = (r, feature) => r.missing.find((m) => m.kind === 'ai-feature' && m.name === feature);+// The override proof retries the ABSENT case with real backoff; these tests drive that path+// constantly, so they opt out of the delay. Retry BEHAVIOUR has its own dedicated test below.const verifyAi = (spec, read) => verifySpec(spec, read, { proofDelayMs: 0 });test('verifySpec: requested AI features that are NOT in effect fail verify (no more false PASS)', async () => {diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 9feaa6865..13b60e51f 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -182,10 +182,13 @@ async function main() {const sdk = makeProvision(env, workspaceDir);const genpageCli = makeGenpageCli(env);const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir }));- for (const c of r.checks) process.stderr.write(` ${c.present ? '✓' : '✗'} ${c.kind}: ${c.name}\n`);+ // Show `detail` on a failing check. Without it a READ that failed (throttling, auth expiry, a 5xx)+ // is indistinguishable from an artifact that is genuinely absent — verifySpec records the cause+ // but the operator saw only "✗ view: Active Orders" and would chase a phantom deployment drift.+ for (const c of r.checks) process.stderr.write(` ${c.present ? '✓' : '✗'} ${c.kind}: ${c.name}${!c.present && c.detail ? ` — ${c.detail}` : ''}\n`);process.stderr.write(`\n${r.ok ? '✓ verify PASS' : `✗ verify FAIL — ${r.missing.length} missing`} (${r.checks.length - r.missing.length}/${r.checks.length} present)\n`);// Include `errors` (alias of missing) so emitResult's failure note reports an accurate count.- const missing = r.missing.map((m) => `${m.kind}:${m.name}`);+ const missing = r.missing.map((m) => `${m.kind}:${m.name}${m.detail ? ` (${m.detail})` : ''}`);emitResult(r.ok, { ok: r.ok, present: r.checks.length - r.missing.length, total: r.checks.length, missing, errors: missing });}diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 9cc1423ba..a423143ad 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -403,9 +403,13 @@ existing app (add a field/view/page, edit a page's code, retitle/reorder nav, swdeployed app fresh into a spec first**, then edit that spec and re-run Phase 2:```bash-node "${PLUGIN_ROOT}/scripts/download-model-app.js" --env <envUrl> --app <appId|uniqueName> --out <working-dir>+node "${PLUGIN_ROOT}/scripts/download-model-app.js" --env <envUrl> --app <appId|uniqueName|displayName> --out <working-dir>```+`--app` resolves in identity order: app id (GUID) → `uniquename` → display name. Prefer the **unique+name** — it is immutable, while a display name can be renamed and is not unique. A display name that+matches more than one app is refused, listing the candidate unique names rather than guessing.+This reconstructs the app into `<working-dir>/app-spec.json`. **Round-trip scope — be precise, it isnot everything:**- **Round-trips:** the sitemap → `appShell` (all subareas + icons), **every** generative page (via