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.

model-apps 2.8.0: app-builder is now GA (#563)

Akshay Malooa804d33267c9
diff --git a/.github/workflows/validate-repository-metadata.yml b/.github/workflows/validate-repository-metadata.yml
index 6a5ae41e4..aec644dcd 100644
--- a/.github/workflows/validate-repository-metadata.yml
+++ b/.github/workflows/validate-repository-metadata.yml
@@ -40,6 +40,16 @@ jobs:
- name: validate-hooks-manifests
run: node scripts/validate-hooks-manifests.js
+ # An agent that declares AskUserQuestion / EnterPlanMode / ExitPlanMode specifies a
+ # flow that CANNOT complete — a Task subagent is headless, so the question never
+ # reaches the user and the approval is never given. Agent frontmatter is prose to
+ # every other test in the repo, which is how one such contradiction survived ~2.5
+ # months without anything failing.
+ - name: test-agent-interactivity-validator
+ run: node --test scripts/tests/validate-agent-interactivity.test.js
+
+ - name: validate-agent-interactivity
+ run: node scripts/validate-agent-interactivity.js
- name: test-secure-process-execution-validator
run: node --test scripts/tests/validate-secure-process-execution.test.js
diff --git a/README.md b/README.md
index 7441f6f21..f34c70aad 100644
--- a/README.md
+++ b/README.md
@@ -66,7 +66,7 @@ Create and deploy Power Pages sites using modern development approaches.
Build model-driven Power Apps end to end, and the generative pages that go in them.
-**Skills**: `/app-builder` (**Preview**) builds and edits a whole app — tables, relationships, forms,
+**Skills**: `/app-builder` builds and edits a whole app — tables, relationships, forms,
views, charts, security roles, app + sitemap — from a natural-language intent; `/genpage` builds
generative pages for an app that already exists. Use either independently — neither requires the other
@@ -272,6 +272,7 @@ duplicating display/update metadata.
- [Power Pages Code Sites](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)
- [Power Pages REST API](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites)
- [Generative Pages with External Tools](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/generative-page-external-tools)
+- [Build Model-Driven Apps with External Tools](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/model-driven-app-external-tools)
- [Power Apps Code Apps](https://learn.microsoft.com/power-apps/developer/code-apps/)
- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference)
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index d7443022a..594f44be9 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -451,7 +451,7 @@
"app_selection": "user selects an existing app from pac model list"
},
"expectations": [
- "Phase 1 (Planner): With the connectors feature flag OFF, the feature gate (scripts/lib/feature-flags.js) is checked, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
+ "Phase 1 (Planner): For a mock-data page, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
"Phase 2: Entity-builder is SKIPPED (mock data)",
"Phase 4: RuntimeTypes generation is SKIPPED (mock data)",
"Phase 5 (Page Builder): genpage-page-builder is invoked with Data mode: mock",
@@ -471,20 +471,40 @@
"new_or_edit": "Create new page(s)",
"data_source": "SharePoint (connector)",
"specific_requirements": "list documents"
- },
- "feature_flags": {
- "connectors": "ON (GENPAGE_ENABLE_CONNECTORS=1)"
}
},
"expectations": [
- "Phase 1 (Planner): With the connectors feature flag ON, the feature gate passes (enabled) and list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
- "Phase 4.5 / Phase 6 (connectors ON): connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
+ "Phase 1 (Planner): For a connector-backed page, list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
+ "Phase 4.5 / Phase 6: connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
"Phase 2: Entity-builder is SKIPPED (no entities to create)",
"Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder",
"Phase 5b: Orchestrator reads ${PLUGIN_ROOT}/references/verified-icons.txt before writing the .tsx",
"Phase 5b: A relevant sample file is read (e.g., 7-responsive-cards.tsx for card layout)",
"Phase 5b: After writing, orchestrator greps the .tsx for `from \"@fluentui/react-icons\"` imports and verifies each named import against verified-icons.txt — rewrites if any are missing"
]
+ },
+ {
+ "id": 19,
+ "tier": "full",
+ "prompt": "Edit the Seattle Weather page in my Operations Hub app — pull the current conditions from the real MSN Weather connector instead of the hard-coded numbers. Leave the five-day forecast alone.",
+ "data": {
+ "question_answers": {
+ "new_or_edit": "Edit existing",
+ "app_and_page": "user selects Operations Hub, then the Seattle Weather page, from pac model list / pac model genpage list",
+ "changes": "Bind current conditions to the MSN Weather connector; preserve the five-day forecast"
+ }
+ },
+ "expectations": [
+ "Phase 1 (Planner): User indicates 'edit existing'; planner returns { action: 'edit' }, skipping Phases 2-8 of the create flow",
+ "Edit Phase 1a: pac model list is run to discover available apps — orchestrator does NOT guess or invent app names",
+ "Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names",
+ "Edit Phase 4: genpage-edit-planner agent is invoked via Task tool",
+ "Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)",
+ "Edit Phase 3.5 (connector edit): genpage-connector-builder is dispatched with Mode: edit and the existing bindings, runs list-connections.js, and writes connectors.json as a bare JSON array",
+ "Edit Phase 5 (REST connector): the page calls executeConnectorOperation for an operation-based connector — never queryConnectorTable — presence-checks the method, and checks response.ok before reading response.body",
+ "Edit Phase 5 (preservation): content the connector cannot supply is preserved per the edit plan's Preservation Constraints rather than dropped",
+ "Edit Phase 6 (connector edit): the upload passes --page-id and --connectors, omits --add-to-sitemap, and --prompt carries only the edit delta"
+ ]
}
]
}
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md b/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md
similarity index 96%
rename from evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md
rename to evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md
index cd5691e62..a1ceefb89 100644
--- a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/17-weather-mock-data/genpage-plan.md
@@ -41,7 +41,7 @@ No connector bindings.
## Design Preferences
-- Inline mock weather data (connectors feature flag OFF — connector not available at this time)
+- Inline mock weather data (maker chose mock data — no connector binding requested)
- KPI-style metric cards for temperature, conditions, humidity
- 5-day forecast card row below current conditions
- Responsive flex layout (no 100vh / 100vw)
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx b/evals/model-apps/genpage/fixtures/17-weather-mock-data/weather-dashboard.tsx
similarity index 95%
rename from evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx
rename to evals/model-apps/genpage/fixtures/17-weather-mock-data/weather-dashboard.tsx
index a470bc443..9c845ed61 100644
--- a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx
+++ b/evals/model-apps/genpage/fixtures/17-weather-mock-data/weather-dashboard.tsx
@@ -14,8 +14,8 @@ import {
WaterRegular,
} from '@fluentui/react-icons';
-// Mock weather data for Seattle — the MSN Weather connector is gated behind the
-// connectors feature flag (currently OFF), so this page uses inline mock data.
+// Mock weather data for Seattle — the maker chose "Mock data" as the data source,
+// so this page carries inline sample data rather than an MSN Weather connector binding.
interface WeatherRecord {
date: string;
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md b/evals/model-apps/genpage/fixtures/17-weather-mock-data/workflow-log.md
similarity index 89%
rename from evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
rename to evals/model-apps/genpage/fixtures/17-weather-mock-data/workflow-log.md
index 701a3bdae..7c2349ba1 100644
--- a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/17-weather-mock-data/workflow-log.md
@@ -1,4 +1,4 @@
-# Workflow Log — Eval 17: Seattle Weather Dashboard (connectors feature flag OFF)
+# Workflow Log — Eval 17: Seattle Weather Dashboard (mock data)
## Phase 0 — Working directory setup
- Working directory created: `seattle-weather-dashboard/` (kebab-case derived from "current weather for Seattle")
@@ -23,8 +23,8 @@
### Connector Detection (delegated to genpage-connector-builder)
- Request implies external weather data (MSN Weather connector) → planner delegates all connector work to the `genpage-connector-builder` agent (mode: create) via the Task tool
-- genpage-connector-builder probes the gate FIRST: `node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors` → `disabled` (exit 1)
-- Connectors feature flag OFF: connector discovery SKIPPED; list-connections.js NOT run
+- genpage-connector-builder assesses the data source FIRST: the maker answered "Mock data", so there is no connector data source to discover
+- Connector discovery SKIPPED; list-connections.js NOT run
- Agent wrote `connector-bindings.md` = `No connector bindings.` and `connectors.json` = `[]`
- Page falls back to inline mock weather data for Seattle
@@ -68,4 +68,4 @@
## Phase 8 — Summary
- 1 page deployed: weather-dashboard.tsx → "Seattle Weather" in Operations Hub app
- No entities created
-- No connector bindings (connectors flag OFF — mock data used)
+- No connector bindings (maker chose mock data)
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/genpage-plan.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.md
similarity index 100%
rename from evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/genpage-plan.md
rename to evals/model-apps/genpage/fixtures/18-sharepoint-connectors/genpage-plan.md
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/sharepoint-docs.tsx b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/sharepoint-docs.tsx
similarity index 100%
rename from evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/sharepoint-docs.tsx
rename to evals/model-apps/genpage/fixtures/18-sharepoint-connectors/sharepoint-docs.tsx
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/workflow-log.md
similarity index 94%
rename from evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
rename to evals/model-apps/genpage/fixtures/18-sharepoint-connectors/workflow-log.md
index c7282b271..515a55412 100644
--- a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors/workflow-log.md
@@ -1,4 +1,4 @@
-# Workflow Log — Eval 18: SharePoint Team Documents (connectors feature flag ON)
+# Workflow Log — Eval 18: SharePoint Team Documents (connector-backed)
## Phase 0 — Working directory setup
- Working directory created: `sharepoint-team-docs/` (kebab-case derived from "SharePoint team site documents")
@@ -23,8 +23,7 @@
### Connector Detection (delegated to genpage-connector-builder)
- Request is explicitly for SharePoint connector → planner delegates all connector work to the `genpage-connector-builder` agent (mode: create) via the Task tool
-- genpage-connector-builder probes the gate FIRST: `node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors` → `enabled` (exit 0)
-- Connectors feature flag ON: proceeding with connector discovery
+- genpage-connector-builder assesses the data source FIRST: the maker answered "SharePoint (connector)", so connector discovery runs
- `node "${PLUGIN_ROOT}/scripts/list-connections.js" "https://contoso-dev.crm10.dynamics.com/"` → 2 connections found:
- SharePoint Online: logical name `new_uxtest_sharepoint`, connectorId `/providers/Microsoft.PowerApps/apis/shared_sharepointonline`
- OneDrive for Business: logical name `new_uxtest_onedrive`, connectorId `/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness`
diff --git a/evals/model-apps/genpage/fixtures/19-add-weather-connector/genpage-edit-plan.md b/evals/model-apps/genpage/fixtures/19-add-weather-connector/genpage-edit-plan.md
new file mode 100644
index 000000000..4f8f3c484
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/19-add-weather-connector/genpage-edit-plan.md
@@ -0,0 +1,50 @@
+# GenPage Edit Plan — Seattle Weather
+
+## Page Under Edit
+
+- App: Operations Hub (`aa112233-1122-1122-1122-aabbccdd1234`)
+- Page: Seattle Weather (`bb223344-2233-2233-2233-bbccddee2345`)
+- Downloaded to: `seattle-weather-edit/bb223344-2233-2233-2233-bbccddee2345/`
+- Current data mode: mock (no `dataSources` in `config.json`, no `connectorBindings`)
+
+## User Requirements (delta)
+
+Pull the current conditions from the real MSN Weather connector instead of the
+hard-coded numbers. Leave the five-day forecast alone.
+
+## Connector Changes
+
+Action: **add** a connector binding. The page currently has none.
+
+| Logical Name | Connector | Dataset | Operations |
+|---|---|---|---|
+| `new_uxtest_msnweather` | `/providers/Microsoft.PowerApps/apis/shared_msnweather` | (none — REST connector) | `CurrentWeather` |
+
+MSN Weather is a REST/action connector, so the page calls
+`executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', { … })` —
+the REST pattern in `references/connectors.md`, not `queryConnectorTable`.
+
+## Changes
+
+1. Bind the **current conditions** card to the connector operation, with the
+ existing hard-coded values kept as the fallback shown before the call resolves
+ and whenever it is unavailable or fails.
+2. Add a `Live` / `Sample` badge so the user can tell which they are looking at.
+3. Surface a warning `MessageBar` when the connector call fails.
+
+## Preservation Constraints
+
+- The **five-day forecast strip keeps its inline sample data**. The `CurrentWeather`
+ operation returns current conditions only, so replacing the forecast with connector
+ data is not possible — dropping it would silently remove a feature the maker did
+ not ask to lose.
+- The page title, layout, Fluent tokens and the existing icon set are unchanged.
+- `export default GeneratedComponent` and the `props.dataApi` / `props.pageInput`
+ signature are unchanged.
+
+## Deployment
+
+- Upload with `--page-id bb223344-2233-2233-2233-bbccddee2345` and
+ `--connectors seattle-weather-edit/connectors.json`.
+- **No** `--add-to-sitemap` — the page is already in the sitemap.
+- `--prompt` carries only this edit's delta, not the original page description.
diff --git a/evals/model-apps/genpage/fixtures/19-add-weather-connector/weather-panel.tsx b/evals/model-apps/genpage/fixtures/19-add-weather-connector/weather-panel.tsx
new file mode 100644
index 000000000..3c89461c3
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/19-add-weather-connector/weather-panel.tsx
@@ -0,0 +1,276 @@
+import { useState, useEffect } from 'react';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Card,
+ CardHeader,
+ Badge,
+ MessageBar,
+ MessageBarBody,
+} from '@fluentui/react-components';
+import {
+ TemperatureRegular,
+ WeatherSunnyRegular,
+ WaterRegular,
+} from '@fluentui/react-icons';
+
+// EDITED PAGE — this started life as a mock-data weather dashboard (eval 17). The maker's edit
+// request was "pull the current conditions from the real MSN Weather connector instead of the
+// hard-coded numbers", so the page now binds to the new_uxtest_msnweather connection reference.
+//
+// MSN Weather is a REST/action connector, not a table/list one, so it uses the
+// executeConnectorOperation pattern from references/connectors.md — NOT queryConnectorTable.
+// The weekly forecast below is deliberately left as inline sample data: the edit plan's
+// Preservation Constraints keep it, because the operation returns current conditions only.
+
+interface WeatherRecord {
+ date: string;
+ tempHigh: number;
+ tempLow: number;
+ conditions: string;
+ humidity: number;
+}
+
+interface CurrentConditions {
+ temperature: number;
+ feelsLike: number;
+ conditions: string;
+ humidity: number;
+ location: string;
+}
+
+// PRESERVED from the original mock page — the connector operation returns current conditions
+// only, so the forecast strip keeps its sample data rather than losing the feature.
+const weeklyForecast: WeatherRecord[] = [
+ { date: 'Mon', tempHigh: 58, tempLow: 45, conditions: 'Partly Cloudy', humidity: 72 },
+ { date: 'Tue', tempHigh: 54, tempLow: 43, conditions: 'Rainy', humidity: 88 },
+ { date: 'Wed', tempHigh: 62, tempLow: 48, conditions: 'Partly Sunny', humidity: 65 },
+ { date: 'Thu', tempHigh: 65, tempLow: 50, conditions: 'Sunny', humidity: 58 },
+ { date: 'Fri', tempHigh: 60, tempLow: 47, conditions: 'Cloudy', humidity: 75 },
+];
+
+// Shown until the connector answers, and whenever it is unavailable or fails.
+const FALLBACK_CURRENT: CurrentConditions = {
+ temperature: 58,
+ feelsLike: 54,
+ conditions: 'Partly Cloudy',
+ humidity: 72,
+ location: 'Seattle, WA',
+};
+
+const CONNECTOR_LOGICAL_NAME = 'new_uxtest_msnweather';
+const OPERATION_NAME = 'CurrentWeather';
+const winAny = window as any;
+const CACHE_KEY = '__ppWeatherCurrentCache';
+const INFLIGHT_KEY = '__ppWeatherCurrentInflight';
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ pageTitle: { marginBottom: tokens.spacingVerticalS },
+ currentCard: { padding: tokens.spacingHorizontalL },
+ currentRow: {
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalL,
+ },
+ bigTemp: {
+ fontSize: tokens.fontSizeHero800,
+ fontWeight: tokens.fontWeightSemibold,
+ lineHeight: tokens.lineHeightHero800,
+ },
+ metric: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalXS,
+ color: tokens.colorNeutralForeground2,
+ },
+ metricIcon: { color: tokens.colorBrandForeground1, flexShrink: 0 },
+ forecastStrip: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
+ gap: tokens.spacingHorizontalM,
+ '@media (max-width: 480px)': {
+ gridTemplateColumns: '1fr',
+ },
+ },
+ dayCard: { padding: tokens.spacingHorizontalM },
+ dayName: { fontWeight: tokens.fontWeightSemibold },
+ daySub: { color: tokens.colorNeutralForeground2, fontSize: tokens.fontSizeBase200 },
+});
+
+const DayCard = (props: { day: WeatherRecord }) => {
+ const { day } = props;
+ const styles = useStyles();
+ return (
+ <Card
+ className={styles.dayCard}
+ aria-label={`${day.date}: ${day.conditions}, high ${day.tempHigh}, low ${day.tempLow}, humidity ${day.humidity} percent`}
+ >
+ <Text className={styles.dayName}>{day.date}</Text>
+ <Text className={styles.daySub}>{day.conditions}</Text>
+ <Text className={styles.daySub}>
+ {day.tempHigh}° / {day.tempLow}°
+ </Text>
+ </Card>
+ );
+};
+
+const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ // Cast to an OPTIONAL connector shape — the runtime may not expose the method if the
+ // connection reference is not active yet.
+ const connectorApi = dataApi as unknown as {
+ executeConnectorOperation?: (
+ connectorLogicalName: string,
+ operationName: string,
+ parameters: Record<string, unknown>
+ ) => Promise<{ ok: boolean; body: unknown }>;
+ };
+ const dataReady = !!dataApi;
+ const [{ current, live, error }, setData] = useState<{
+ current: CurrentConditions;
+ live: boolean;
+ error: string | null;
+ }>(() => {
+ const cached = winAny[CACHE_KEY] as CurrentConditions | undefined;
+ return { current: cached ?? FALLBACK_CURRENT, live: cached !== undefined, error: null };
+ });
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = winAny[CACHE_KEY] as CurrentConditions | undefined;
+ if (cached !== undefined) {
+ if (current !== cached) {
+ setData({ current: cached, live: true, error: null });
+ }
+ return;
+ }
+
+ // Presence-check before calling, per references/connectors.md.
+ if (typeof connectorApi?.executeConnectorOperation !== 'function') {
+ setData({ current: FALLBACK_CURRENT, live: false, error: null });
+ return;
+ }
+
+ let cancelled = false;
+ let inflight = winAny[INFLIGHT_KEY] as Promise<CurrentConditions> | undefined;
+ if (!inflight) {
+ inflight = connectorApi
+ .executeConnectorOperation(CONNECTOR_LOGICAL_NAME, OPERATION_NAME, {
+ Location: 'Seattle',
+ units: 'I',
+ })
+ .then((response) => {
+ // Check `ok` before reading `body` — a failed operation still resolves.
+ if (!response.ok) throw new Error('operation returned ok:false');
+ const body = response.body as {
+ temperature?: number;
+ feelsLike?: number;
+ conditions?: string;
+ humidity?: number;
+ location?: string;
+ };
+ const mapped: CurrentConditions = {
+ temperature: body.temperature ?? FALLBACK_CURRENT.temperature,
+ feelsLike: body.feelsLike ?? FALLBACK_CURRENT.feelsLike,
+ conditions: body.conditions ?? FALLBACK_CURRENT.conditions,
+ humidity: body.humidity ?? FALLBACK_CURRENT.humidity,
+ location: body.location ?? FALLBACK_CURRENT.location,
+ };
+ winAny[CACHE_KEY] = mapped;
+ return mapped;
+ })
+ .finally(() => {
+ if (winAny[INFLIGHT_KEY] === inflight) {
+ delete winAny[INFLIGHT_KEY];
+ }
+ });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((mapped) => {
+ if (!cancelled) {
+ setData({ current: mapped, live: true, error: null });
+ }
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setData({
+ current: FALLBACK_CURRENT,
+ live: false,
+ error: 'Could not reach the MSN Weather connector. Showing sample conditions.',
+ });
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ // dataApi is a new reference on each render, so depend on readiness only.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady]);
+
+ return (
+ <div className={styles.root}>
+ <Text as="h1" size={800} weight="semibold" className={styles.pageTitle}>
+ Seattle Weather
+ </Text>
+
+ {error && (
+ <MessageBar intent="warning">
+ <MessageBarBody>{error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <Card className={styles.currentCard}>
+ <CardHeader
+ header={<Text weight="semibold">Current conditions — {current.location}</Text>}
+ action={
+ <Badge appearance="outline" aria-label={live ? 'Live connector data' : 'Sample data'}>
+ {live ? 'Live' : 'Sample'}
+ </Badge>
+ }
+ />
+ <div className={styles.currentRow}>
+ <Text className={styles.bigTemp}>{current.temperature}°</Text>
+ <div className={styles.metric}>
+ <WeatherSunnyRegular className={styles.metricIcon} aria-hidden="true" />
+ <Text>{current.conditions}</Text>
+ </div>
+ <div className={styles.metric}>
+ <TemperatureRegular className={styles.metricIcon} aria-hidden="true" />
+ <Text>Feels like {current.feelsLike}°</Text>
+ </div>
+ <div className={styles.metric}>
+ <WaterRegular className={styles.metricIcon} aria-hidden="true" />
+ <Text>{current.humidity}% humidity</Text>
+ </div>
+ </div>
+ </Card>
+
+ <Text as="h2" size={500} weight="semibold">
+ Five-day forecast
+ </Text>
+ <div className={styles.forecastStrip}>
+ {weeklyForecast.map((day) => (
+ <DayCard key={day.date} day={day} />
+ ))}
+ </div>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/19-add-weather-connector/workflow-log.md b/evals/model-apps/genpage/fixtures/19-add-weather-connector/workflow-log.md
new file mode 100644
index 000000000..7edae76ed
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/19-add-weather-connector/workflow-log.md
@@ -0,0 +1,82 @@
+# Workflow Log — Eval 19: adding a connector to an existing page (edit flow)
+
+## Phase 0 — Working directory setup
+- Working directory created: `seattle-weather-edit/` (kebab-case derived from "Seattle weather page edit")
+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`
+
+## Phase 1 — Planner (genpage-planner agent invoked via Task)
+
+### Prereq checks
+- `node --version` → v20.11.0
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
+- (Commands run separately, not chained with &&)
+
+### Auth check
+- `pac auth list` → active profile `[email protected]`
+- Active environment: https://contoso-dev.crm10.dynamics.com/ (reported to user)
+
+### Discovery questions (AskUserQuestion)
+- Question 1 (new or edit): user answered "Edit existing"
+- Planner returned `{ "action": "edit" }` — Phases 2-8 of the create flow are skipped
+
+## Edit Phase 1 — App and page selection
+
+### 1a. App discovery
+- `pac model list` → 2 apps found:
+ - Operations Hub — `aa112233-1122-1122-1122-aabbccdd1234`
+ - Field Service Lite — `cc334455-3344-3344-3344-ccddeeff3456`
+- Apps presented via AskUserQuestion using the actual Display Name + app-id from that output
+- User selected "Operations Hub" (`aa112233-1122-1122-1122-aabbccdd1234`)
+
+### 1b. Page discovery
+- `pac model genpage list --app-id aa112233-1122-1122-1122-aabbccdd1234` → 2 pages found:
+ - Seattle Weather — `bb223344-2233-2233-2233-bbccddee2345`
+ - SharePoint Documents — `dd445566-4455-4455-4455-ddeeff004567`
+- Pages presented via AskUserQuestion using the actual names + page-id GUIDs
+- User selected "Seattle Weather" (`bb223344-2233-2233-2233-bbccddee2345`)
+
+### 1c. Selection restated
+- "Editing page **Seattle Weather** (`bb223344-…`) in app **Operations Hub** (`aa112233-…`)." — confirmed before download
+
+## Edit Phase 2 — Download
+- `pac model genpage download --app-id aa112233-1122-1122-1122-aabbccdd1234 --page-id bb223344-2233-2233-2233-bbccddee2345 --path seattle-weather-edit`
+- Produced `seattle-weather-edit/bb223344-2233-2233-2233-bbccddee2345/` with page.tsx, page.js, config.json, prompt.txt
+
+## Edit Phase 3 — Schema generation
+- `config.json` read: `dataSources` is absent and `connectorBindings` is absent → page is mock-data with no connectors
+- RuntimeTypes generation SKIPPED (no Dataverse data sources)
+
+## Edit Phase 3.5 — Connector edit (delegated to genpage-connector-builder)
+- Edit intent mentions a real weather source → orchestrator dispatches `genpage-connector-builder` via the Task tool with **Mode: `edit`**, the working directory, `${PLUGIN_ROOT}`, the envUrl, and the EXISTING bindings (none — the page had no `connectorBindings`)
+- `node "${PLUGIN_ROOT}/scripts/list-connections.js" "https://contoso-dev.crm10.dynamics.com/"` → 2 connections found:
+ - MSN Weather: logical name `new_uxtest_msnweather`, connectorId `/providers/Microsoft.PowerApps/apis/shared_msnweather`, readyToBind true
+ - SharePoint Online: logical name `new_uxtest_sharepoint`, connectorId `/providers/Microsoft.PowerApps/apis/shared_sharepointonline`
+- Selected MSN Weather (best match for "real weather"): `new_uxtest_msnweather`
+- Agent wrote `connector-bindings.md` (binding table) and `connectors.json`
+- `connectors.json` written to seattle-weather-edit/connectors.json as a BARE JSON ARRAY (not the config.json `{ "connectorBindings": [...] }` wrapper): [{ "logicalName": "new_uxtest_msnweather", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "dataset": "", "operations": ["CurrentWeather"] }]
+
+## Edit Phase 4 — Edit planning
+- `genpage-edit-planner` agent invoked via Task tool
+- edit-planner read page.tsx, config.json and prompt.txt from the `bb223344-…/` folder
+- `genpage-edit-plan.md` written to the working directory root (not inside `bb223344-…/`)
+- Plan records `## Connector Changes` = add `new_uxtest_msnweather`, and `## Preservation Constraints` = keep the five-day forecast sample data
+
+## Edit Phase 5 — Apply edits
+- Orchestrator read genpage-edit-plan.md, references/rules.md, references/connectors.md and page.tsx
+- Read `${PLUGIN_ROOT}/references/verified-icons.txt` before editing
+- Edits applied inline with the Edit tool on `seattle-weather-edit/bb223344-2233-2233-2233-bbccddee2345/page.tsx`
+- MSN Weather is a REST connector → used `executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', { Location: 'Seattle', units: 'I' })`, NOT queryConnectorTable
+- Presence-checked the method, checked `response.ok` before reading `response.body`, and kept the inline sample conditions as the fallback
+- Five-day forecast left untouched per the plan's Preservation Constraints
+- Post-edit icon verification: grep `from "@fluentui/react-icons"` → `TemperatureRegular`, `WeatherSunnyRegular`, `WaterRegular` all verified against verified-icons.txt
+
+## Edit Phase 6 — Deployment
+- `pac model genpage upload --app-id aa112233-1122-1122-1122-aabbccdd1234 --page-id bb223344-2233-2233-2233-bbccddee2345 --code-file seattle-weather-edit/bb223344-2233-2233-2233-bbccddee2345/page.tsx --connectors "seattle-weather-edit/connectors.json" --prompt "Bind the current conditions card to the MSN Weather connector; leave the five-day forecast as sample data." --model claude-sonnet`
+- `--add-to-sitemap` omitted (page already in the sitemap)
+- `--prompt` is the DELTA of this edit only, not a restatement of the original page description
+- Upload succeeded
+
+## Phase 8 — Summary
+- 1 page updated: Seattle Weather in Operations Hub
+- Connector binding added: `new_uxtest_msnweather` (MSN Weather, CurrentWeather operation)
+- Five-day forecast preserved as sample data
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index 70f95efbe..d8582890b 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -17,10 +17,52 @@ function fail(reason) { return { status: 'fail', reason }; }
function pass() { return { status: 'pass', reason: '' }; }
function skip(reason) { return { status: 'skip', reason }; }
+// An EDIT-flow fixture produces `genpage-edit-plan.md` and never `genpage-plan.md`: the create
+// flow's planning phases (solution question, EnterPlanMode approval, plan-schema conformance,
+// entity prefix discipline) do not run at all on that path.
+//
+// Those assertions must SKIP rather than fail for such a fixture. Until eval 19 the suite had no
+// edit fixture — eval 3 is edit-flow but ships none — so the create-flow assumption baked into the
+// COMMON assertions was never exercised, and the first edit fixture added reported six false
+// failures that say nothing about the page under test.
+function isEditFlowFixture(fixture) {
+ return Boolean(fixture && fixture.genpageEditPlan && !fixture.genpagePlan);
+}
+
function logHas(log, pattern) {
return Boolean(log) && new RegExp(pattern, 'mi').test(log);
}
+function isUnattendedLog(log) {
+ return Boolean(log) && (
+ /Unattended default:/i.test(log) ||
+ // The mode probe, in prose (`interactive: false`) or as the raw resolve-interaction-mode.js
+ // line (`{"ok":true,"interactive":false,...}`) — hence the optional quotes.
+ // The lookbehind is load-bearing: without it `non-interactive: false`, which describes an
+ // ATTENDED run, matches on the tail of the word and flips the log to the unattended branch.
+ /(?<![\w-])"?interactive"?\s*[:=]\s*"?false"?/i.test(log) ||
+ // The two `reason` strings resolveInteractionMode() emits, and only ever for interactive:false.
+ // Anchored to the `reason` field rather than matched as bare phrases: an ATTENDED log
+ // legitimately *negates* them ("attended (no --non-interactive flag, TTY present)",
+ // "POWER_PLATFORM_SKILLS_NONINTERACTIVE is set -> no"), and an unanchored match would
+ // grade that correct attended run down the unattended branch and fail it for lacking an
+ // `Unattended default:` marker. Shape emitted by scripts/resolve-interaction-mode.js:
+ // {"ok":true,"interactive":false,"reason":"--non-interactive flag"}
+ /"?reason"?\s*[:=]\s*"?(?:--non-interactive flag|POWER_PLATFORM_SKILLS_NONINTERACTIVE\s+is set)/i.test(log)
+ // Deliberately NO free-prose alternative here (e.g. matching "Interaction mode: unattended").
+ // Prose is unbounded and every attempt to pattern-match it closed one negation position while
+ // opening another: a bare `\bunattended\b` matches inside "not unattended"; anchoring on
+ // `mode: unattended` fixes that but then admits "Mode: unattended = false",
+ // "Interaction mode: unattended? no", and "the Unattended column" — all ATTENDED logs, each
+ // graded unattended and failed for lacking a marker, which is the exact false failure this
+ // function was fixed to stop causing.
+ // Instead the contract is pinned in the doc: genpage SKILL.md's unattended table requires the
+ // mode to be recorded as `Unattended default: interaction mode → unattended (<reason>)`, which
+ // the first alternative already matches. Matching the documented marker is decidable; matching
+ // English is not. Re-adding a prose alternative re-opens the negation problem.
+ );
+}
+
function planSection(plan, heading) {
// Returns text under "## <heading>" up to the next "## " heading or end-of-file.
// Implemented as line scan to avoid JS regex \Z limitation.
@@ -283,6 +325,26 @@ function validateGenpagePlanSchema(plan) {
}
}
+ // `## Custom API Bindings` is spec'd as always-present: plan-schema.md:212 gives it the same
+ // "Exact literal ... when empty" sentinel rule as `## Connector Bindings` at :211, and :213
+ // reserves "Opt-in" for `## Solution Packaging` alone — which is why OPTIONAL_PLAN_SECTIONS
+ // contains only that one section. (The "opt-in, unlike the always-present ## Connector Bindings"
+ // sentence at :158-160 sits inside the Solution Packaging block and describes IT, not this
+ // section.) In practice though, 0 of the 12 fixture plans emit `## Custom API Bindings` and
+ // REQUIRED_PLAN_SECTIONS omits it, so requiring it here would fail every existing plan. This
+ // check is therefore conditional until the fixtures catch up with the spec — a deliberate
+ // accommodation of a spec-vs-reality divergence, not a statement that the section is optional.
+ // Without it the Custom API half had no enforcement at all: the sentinel was stated but never
+ // checked, so a prompt regression leaking a `----- BEGIN/END ... -----` delimiter into this
+ // section scored green, while the identical regression in the connector half fails loudly.
+ const customApiSection = byTitle.get('Custom API Bindings');
+ if (customApiSection) {
+ const body = customApiSection.content.trim();
+ if (body !== 'No custom API bindings.' && !findMarkdownTable(body, ['Name', 'Kind', 'Bound Entity'])) {
+ errors.push(schemaError('missing-customapi-table', '## Custom API Bindings must be the exact no-bindings sentinel or the Custom API binding table', { section: 'Custom API Bindings' }));
+ }
+ }
+
const samplesSection = byTitle.get('Relevant Samples');
if (samplesSection && !findMarkdownTable(samplesSection.content, ['Page', 'Sample', 'Reason'])) {
errors.push(schemaError('missing-samples-table', '## Relevant Samples must contain a table with Page, Sample, and Reason columns', { section: 'Relevant Samples' }));
@@ -392,7 +454,9 @@ WORKFLOW_ASSERTIONS.set(
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
- if (!/AskUserQuestion/.test(log)) return fail('workflow-log does not record any AskUserQuestion call');
+ const unattended = isUnattendedLog(log);
+ if (!unattended && !/AskUserQuestion/.test(log)) return fail('workflow-log does not record any AskUserQuestion call');
+ if (unattended && !/Unattended default:/i.test(log)) return fail('unattended workflow-log does not record its default decision');
// The planner spec allows the "new vs edit" question to be inferred
// from $ARGUMENTS when the prompt clearly states a new page. Accept any of:
// - explicit question recorded
@@ -416,6 +480,7 @@ WORKFLOW_ASSERTIONS.set(
'Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows',
({ fixture }) => {
const plan = fixture.genpagePlan;
+ if (isEditFlowFixture(fixture)) return skip('edit flow — no genpage-plan.md is produced');
if (!plan) return fail('genpage-plan.md not present in fixture');
const env = planSection(plan, 'Environment');
if (!env) return fail('plan has no "## Environment" section');
@@ -432,9 +497,17 @@ WORKFLOW_ASSERTIONS.set(
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
+ if (isEditFlowFixture(fixture)) return skip('edit flow — the solution question belongs to the create flow');
if (!plan) return fail('no genpage-plan.md');
const needsMetadata = entitiesNeedCreating(plan) || newAppNeeded(plan);
const asked = solutionQuestionAsked(log);
+ if (isUnattendedLog(log)) {
+ if (asked) return fail('unattended flow recorded an interactive solution question');
+ if (needsMetadata && !/Unattended default:[^\n]*solution/i.test(log)) {
+ return fail('metadata work required in unattended mode but no solution default/decision was recorded');
+ }
+ return pass();
+ }
if (needsMetadata && !asked) return fail('metadata work required but solution question not asked');
if (!needsMetadata && asked) return fail('code-only flow asked solution question (should be skipped)');
return pass();
@@ -464,6 +537,20 @@ WORKFLOW_ASSERTIONS.set(
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
+ if (isEditFlowFixture(fixture)) return skip('edit flow — approval is presented from genpage-edit-plan.md');
+ if (isUnattendedLog(log)) {
+ if (/EnterPlanMode called|ExitPlanMode called|AskUserQuestion:/i.test(log)) {
+ return fail('unattended workflow-log contains an attended interaction marker');
+ }
+ // Alternative B (`Unattended default:[^\n]*approved`) strictly subsumed this, making the
+ // plan/approval context dead code: any `Unattended default:` line containing "approved" —
+ // e.g. a solution-selection default — satisfied an assertion that claims to check PLAN
+ // approval. The documented marker is `Unattended default: plan approval → approved (...)`.
+ if (!/Unattended default:[^\n]*(plan|approval)[^\n]*approved/i.test(log)) {
+ return fail('unattended workflow-log does not record plan approval');
+ }
+ return pass();
+ }
if (!/EnterPlanMode/.test(log)) return fail('workflow-log does not record EnterPlanMode');
return pass();
}
@@ -472,6 +559,7 @@ WORKFLOW_ASSERTIONS.set(
WORKFLOW_ASSERTIONS.set(
'Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md',
({ fixture }) => {
+ if (isEditFlowFixture(fixture)) return skip('edit flow — no genpage-plan.md is produced');
if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
const errors = validateGenpagePlanSchema(fixture.genpagePlan);
if (errors.length > 0) {
@@ -490,6 +578,7 @@ WORKFLOW_ASSERTIONS.set(
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
+ if (isEditFlowFixture(fixture)) return skip('edit flow — entity creation belongs to the create flow');
if (!plan) return fail('no genpage-plan.md');
if (!entitiesNeedCreating(plan)) return skip('no entity creation required');
if (!/check-auth\.js/.test(log)) return fail('check-auth.js not invoked');
@@ -523,6 +612,7 @@ WORKFLOW_ASSERTIONS.set(
'Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.',
({ fixture }) => {
const plan = fixture.genpagePlan;
+ if (isEditFlowFixture(fixture)) return skip('edit flow — no ## Entity Creation Required section exists');
if (!plan) return fail('no genpage-plan.md');
const section = planSection(plan, 'Entity Creation Required');
if (!section || /No entity creation required/i.test(section)) return skip('no entity creation');
@@ -947,41 +1037,30 @@ PHASE_EXPECTATIONS.set(
}
);
-// Eval 17: connector feature flag OFF — regression guard confirming that the
-// planner probes the feature gate and skips connector discovery entirely when
-// the flag is disabled, leaving ## Connector Bindings as the exact sentinel.
+// Eval 17: mock-data page — regression guard confirming the planner does NOT run
+// connector discovery for a page with no connector data source, leaving
+// ## Connector Bindings as the exact sentinel. (Connector authoring is GA and
+// always available, so the thing worth pinning is that it stays OFF THE PATH when
+// the maker asked for mock data — otherwise every mock page pays for a `pac
+// connection list` round trip and risks inventing a binding nobody asked for.)
PHASE_EXPECTATIONS.set(
- "Phase 1 (Planner): With the connectors feature flag OFF, the feature gate (scripts/lib/feature-flags.js) is checked, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
+ "Phase 1 (Planner): For a mock-data page, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
({ fixture }) => {
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
if (!plan) return fail('no genpage-plan.md');
- // (a) A line in the workflow log must reference feature-flags.js with
- // "connectors" AND "disabled" or "OFF" — evidence the gate was probed
- // and returned the OFF result.
- const hasFlagDisabled = log.split('\n').some((l) =>
- /feature-flags(?:\.js)?/i.test(l) &&
- /\bconnectors\b/i.test(l) &&
- /\b(?:disabled|OFF)\b/i.test(l)
- );
- if (!hasFlagDisabled) {
- return fail(
- 'workflow-log does not record a feature-flags.js probe for connectors returning disabled/OFF'
- );
- }
-
- // (b) list-connections.js must NOT be invoked — a `node ... list-connections.js`
+ // (a) list-connections.js must NOT be invoked — a `node ... list-connections.js`
// command must be absent. A narrative mention like "list-connections.js NOT
// run" in a comment is acceptable and does not count as an invocation.
if (/\bnode\b[^\n]*list-connections\.js/.test(log)) {
return fail(
- 'list-connections.js was invoked but connectors flag is OFF — connector discovery should be skipped'
+ 'list-connections.js was invoked for a mock-data page — connector discovery should be skipped'
);
}
- // (c) Plan's ## Connector Bindings body must be exactly the no-binding sentinel.
+ // (b) Plan's ## Connector Bindings body must be exactly the no-binding sentinel.
const cbSection = planSection(plan, 'Connector Bindings');
if (!cbSection) {
return fail('genpage-plan.md is missing ## Connector Bindings section');
@@ -996,39 +1075,25 @@ PHASE_EXPECTATIONS.set(
}
);
-// Eval 18: connector feature flag ON — regression guard confirming that the
-// planner probes the gate, gets "enabled", runs list-connections.js for
-// discovery, and records at least one real binding in the plan.
+// Eval 18: connector-backed page — regression guard confirming that the planner
+// runs list-connections.js for discovery and records at least one real binding.
PHASE_EXPECTATIONS.set(
- "Phase 1 (Planner): With the connectors feature flag ON, the feature gate passes (enabled) and list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
+ "Phase 1 (Planner): For a connector-backed page, list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
({ fixture }) => {
const log = fixture.workflowLog;
const plan = fixture.genpagePlan;
if (!log) return fail('no workflow-log.md');
if (!plan) return fail('no genpage-plan.md');
- // (a) A line in the workflow log must reference feature-flags.js with
- // "connectors" AND "enabled" or "ON" — evidence the gate passed.
- const hasFlagEnabled = log.split('\n').some((l) =>
- /feature-flags(?:\.js)?/i.test(l) &&
- /\bconnectors\b/i.test(l) &&
- /\b(?:enabled|ON)\b/i.test(l)
- );
- if (!hasFlagEnabled) {
- return fail(
- 'workflow-log does not record a feature-flags.js probe for connectors returning enabled/ON'
- );
- }
-
- // (b) A `node ... list-connections.js` invocation must appear in the log —
- // discovery should run when the flag is ON.
+ // (a) A `node ... list-connections.js` invocation must appear in the log —
+ // discovery must run for a connector-backed data source.
if (!/\bnode\b[^\n]*list-connections\.js/.test(log)) {
return fail(
- 'list-connections.js not invoked — expected when connectors flag is ON'
+ 'list-connections.js not invoked — expected for a connector-backed page'
);
}
- // (c) Plan's ## Connector Bindings must contain at least one real binding,
+ // (b) Plan's ## Connector Bindings must contain at least one real binding,
// detected by a table pipe (|) or a shared_ connector id.
const cbSection = planSection(plan, 'Connector Bindings');
if (!cbSection || cbSection.trim() === '') {
@@ -1036,7 +1101,7 @@ PHASE_EXPECTATIONS.set(
}
if (cbSection.trim() === 'No connector bindings.') {
return fail(
- '## Connector Bindings says "No connector bindings." but flag is ON and a binding was expected'
+ '## Connector Bindings says "No connector bindings." but the page is connector-backed and a binding was expected'
);
}
if (!/\|/.test(cbSection) && !/shared_/.test(cbSection)) {
@@ -1049,11 +1114,11 @@ PHASE_EXPECTATIONS.set(
}
);
-// Eval 18: connectors ON deploy — connectors.json is written as a bare array (not
+// Eval 18: connector deploy — connectors.json is written as a bare array (not
// the config.json { connectorBindings: [...] } wrapper) and the upload passes
// --connectors. Locks in the connectors.json shape and the deploy wiring.
PHASE_EXPECTATIONS.set(
- "Phase 4.5 / Phase 6 (connectors ON): connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
+ "Phase 4.5 / Phase 6: connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
@@ -1068,6 +1133,126 @@ PHASE_EXPECTATIONS.set(
}
);
+// --- Eval 19: adding a connector to an EXISTING page (edit flow) -------------
+//
+// Connector work on the create path (eval 18) and on the edit path are different code paths:
+// the edit path dispatches genpage-connector-builder in `edit` mode with the page's EXISTING
+// bindings, and must merge rather than replace. Nothing covered the edit path until this eval.
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 3.5 (connector edit): genpage-connector-builder is dispatched with Mode: edit and the existing bindings, runs list-connections.js, and writes connectors.json as a bare JSON array',
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ if (!log) return fail('no workflow-log.md');
+
+ // (a) The builder must be dispatched in EDIT mode. A create-mode dispatch would discard the
+ // page's existing bindings instead of merging the new one into them.
+ if (!/genpage-connector-builder/.test(log)) return fail('genpage-connector-builder was not dispatched');
+ if (!/Mode:\s*`?edit`?/i.test(log)) return fail('connector-builder was not dispatched with Mode: edit');
+ if (!/existing bindings/i.test(log)) return fail('the existing bindings were not passed to the builder');
+
+ // (b) Discovery still runs on the edit path.
+ if (!/\bnode\b[^\n]*list-connections\.js/.test(log)) {
+ return fail('list-connections.js not invoked on the edit path');
+ }
+
+ // (c) Same bare-array shape as the create path — `pac` wraps it into config.json itself.
+ // Asserted POSITIVELY (the recorded content opens with `[{`) rather than by banning the
+ // string `{ "connectorBindings"`: a log line legitimately names the wrapper in order to
+ // contrast with it, and a negative match cannot tell the two apart.
+ if (!/connectors\.json/.test(log)) return fail('workflow-log does not record connectors.json');
+ const jsonLine = log.split('\n').find((l) => /connectors\.json/.test(l) && /\[\s*\{/.test(l));
+ if (!jsonLine) return fail('workflow-log does not show connectors.json content as a bare JSON array');
+ if (/:\s*\{\s*"connectorBindings"/.test(jsonLine)) {
+ return fail('connectors.json written as the config.json object wrapper, not a bare array');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 5 (REST connector): the page calls executeConnectorOperation for an operation-based connector — never queryConnectorTable — presence-checks the method, and checks response.ok before reading response.body',
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ const tsx = (fixture.files || []).map((f) => f.content).join('\n');
+ if (!log) return fail('no workflow-log.md');
+ if (!tsx) return fail('no .tsx file in fixture');
+
+ // A REST/action connector (MSN Weather) is called with executeConnectorOperation. Using the
+ // table API for it is the mistake this pins: queryConnectorTable takes dataset+table, which an
+ // operation-based connector does not have, so the call fails at runtime.
+ //
+ // Both checks match an actual CALL (`.name(`), not a mention: generated pages legitimately
+ // carry a comment explaining which API they chose and why, and banning the bare identifier
+ // would fail the very code that documents itself correctly.
+ if (!/\.executeConnectorOperation\s*\(/.test(tsx)) {
+ return fail('.tsx does not call executeConnectorOperation for the REST connector');
+ }
+ if (/\.queryConnectorTable\s*\(/.test(tsx)) {
+ return fail('.tsx calls queryConnectorTable for an operation-based connector');
+ }
+ // Presence-check before calling — the runtime may not expose the method yet.
+ if (!/typeof[^\n]*executeConnectorOperation[^\n]*!==\s*'function'/.test(tsx)) {
+ return fail('.tsx does not presence-check executeConnectorOperation before calling it');
+ }
+ // `ok` is checked before `body` is read; an operation that failed still RESOLVES.
+ const okIdx = tsx.search(/response\.ok/);
+ const bodyIdx = tsx.search(/response\.body/);
+ if (okIdx === -1) return fail('.tsx does not check response.ok');
+ if (bodyIdx !== -1 && okIdx > bodyIdx) return fail('.tsx reads response.body before checking response.ok');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Edit Phase 5 (preservation): content the connector cannot supply is preserved per the edit plan's Preservation Constraints rather than dropped",
+ ({ fixture }) => {
+ const plan = fixture.genpageEditPlan;
+ const tsx = (fixture.files || []).map((f) => f.content).join('\n');
+ if (!plan) return fail('no genpage-edit-plan.md');
+ if (!tsx) return fail('no .tsx file in fixture');
+
+ if (!/##\s*Preservation Constraints/i.test(plan)) {
+ return fail('genpage-edit-plan.md has no ## Preservation Constraints section');
+ }
+ // The concrete case: the CurrentWeather operation returns current conditions only, so the
+ // five-day forecast must survive the edit as inline data. Silently dropping it would remove a
+ // feature the maker never asked to lose — the most common edit-flow regression.
+ if (!/weeklyForecast|forecast/i.test(tsx)) {
+ return fail('.tsx no longer contains the preserved forecast data');
+ }
+ if (!/\{\s*date:\s*'/.test(tsx)) {
+ return fail('.tsx no longer carries the preserved inline forecast rows');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 6 (connector edit): the upload passes --page-id and --connectors, omits --add-to-sitemap, and --prompt carries only the edit delta',
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ if (!log) return fail('no workflow-log.md');
+ const upload = (log.split('\n').find((l) => /genpage upload/.test(l)) || '');
+ if (!upload) return fail('no `pac model genpage upload` command in the workflow log');
+
+ if (!/--page-id\b/.test(upload)) return fail('edit upload must pass --page-id');
+ if (!/--connectors\b/.test(upload)) return fail('edit upload must pass --connectors');
+ // An existing page is already in the sitemap; re-adding it creates a duplicate subarea.
+ if (/--add-to-sitemap\b/.test(upload)) return fail('edit upload must omit --add-to-sitemap');
+
+ // --prompt must be the DELTA. The page's original description ("dashboard showing the current
+ // weather ... temperature, conditions, and humidity") must not be restated, or each edit
+ // re-sends the whole history and the stored prompt drifts from what the page now is.
+ const m = upload.match(/--prompt\s+"([^"]*)"/);
+ if (!m) return fail('edit upload has no quoted --prompt value');
+ if (/temperature, conditions, and humidity/i.test(m[1])) {
+ return fail('--prompt restates the original page description instead of this edit\'s delta');
+ }
+ return pass();
+ }
+);
+
module.exports = {
WORKFLOW_ASSERTIONS,
PHASE_EXPECTATIONS,
diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
index bf34eb122..4b396cb66 100644
--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
@@ -232,6 +232,81 @@ test('node --version and pac help: fail when version not verified', () => {
assert.equal(result.status, 'fail');
});
+test('unattended create/edit determination passes without AskUserQuestion marker', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion');
+ const log = `Unattended default: create new or edit existing → create new (--non-interactive flag)`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+});
+
+test('unattended plan approval passes without attended interaction markers', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const log = `Unattended default: plan approval → approved (--non-interactive flag)`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+});
+
+test('unattended plan approval rejects attended marker text even when phrased as not called', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const log = `Unattended default: plan approval → approved (--non-interactive flag)\nEnterPlanMode called → NOT called`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+});
+
+// `non-interactive: false` describes an ATTENDED run. Reading `interactive: false` out of the tail
+// of that word flipped the whole log to the unattended branch, which then failed it for having no
+// `Unattended default:` marker — a real attended run rejected for recording its own mode.
+test('an attended log that records the flag as off is not misread as unattended', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion');
+ const log = `Interaction mode resolved: non-interactive: false\nAskUserQuestion: new or edit → create new`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+});
+
+// resolve-interaction-mode.js emits `{"ok":true,"interactive":false,"reason":"..."}`. A log that
+// pastes that line is reporting an unattended run, so the QUOTED JSON key must register the same as
+// the prose form. Isolation matters here: the probe line carries no `reason` and no
+// `Unattended default:` marker, and the plan DOES need metadata work — so the attended branch would
+// PASS this log (metadata required + question asked). Only the unattended branch can fail it, which
+// makes the assertion sensitive to the quoted-key match and nothing else.
+test('the resolver JSON line marks the log unattended, so an interactive question is a failure', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written');
+ const plan = `${validPlan()}\n\n## Environment\n- App: create new app\n`;
+ const log = `Interaction mode probe returned {"ok":true,"interactive":false}\nAskUserQuestion: which solution? → Default`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+});
+
+// An ATTENDED log legitimately NEGATES the two reason phrases when it explains why it is
+// attended. Matching them as bare substrings anywhere in the log flipped such a log to the
+// unattended branch, where its (correct) `AskUserQuestion:` line reads as an attended-marker
+// violation — a correct run graded broken. The phrases only mean "unattended" in the resolver's
+// `reason` field, so they are anchored to it.
+test('an attended log that explains the flag was absent is not misread as unattended', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion');
+ const log = `Interaction mode: attended (no --non-interactive flag, TTY present)\nAskUserQuestion: new or edit → create new`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+});
+
+test('an attended log that records the env var as unset is not misread as unattended', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion');
+ const log = `Checked: POWER_PLATFORM_SKILLS_NONINTERACTIVE is set -> no\nAskUserQuestion: new or edit → create new`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+});
+
+// The complement of the two tests above: in the resolver's own `reason` field the same phrase DOES
+// mean unattended, so anchoring must not cost us the real signal. Same isolation trick as the
+// quoted-JSON test — the plan needs metadata work, so only the unattended branch can fail this.
+test('the resolver reason field still marks the log unattended', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written');
+ const plan = `${validPlan()}\n\n## Environment\n- App: create new app\n`;
+ const log = `Mode: {"ok":true,"reason":"--non-interactive flag"}\nAskUserQuestion: which solution? → Default`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+});
+
// ---------- Solution lines in plan ----------
test('Solution+Publisher lines: pass with list-marker format', () => {
@@ -562,3 +637,61 @@ test('Entity scripts --solution (new flow): pass when provision-entities.js used
const result = check({ fixture: fix({ workflowLog: log, entityCreationLog: elog }), eval: evalStub() });
assert.equal(result.status, 'pass');
});
+
+// The documented mode record puts the log on the unattended branch. genpage SKILL.md's unattended
+// table requires `Unattended default: interaction mode → unattended (<reason>)`, so recording the
+// mode is enough to make a prompt a violation — no prose matching needed. Isolation: this log DOES
+// contain `EnterPlanMode called`, so the attended branch would pass it; only the unattended branch
+// can fail here.
+test('the documented mode record marks the log unattended, so a prompt is a failure', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const log = `Unattended default: interaction mode → unattended (--non-interactive flag)\nEnterPlanMode called`;
+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+});
+
+// Guard against re-introducing free-prose mode matching. Each prose form below is an ATTENDED log
+// that merely contains the word "unattended"; a `\bunattended\b` match flags the first, and a
+// `mode: unattended` match flags the rest. Any of them classifying as unattended would fail this
+// correct run for the `EnterPlanMode called` line attended runs are required to have.
+for (const prose of [
+ 'Interaction mode: attended. Not unattended: the --non-interactive flag was absent',
+ 'Mode: unattended = false',
+ 'Interaction mode: unattended? no - TTY present',
+ 'Read the mode matrix: Unattended → skip; Attended → ask. We are attended.',
+]) {
+ test(`an attended log mentioning "${prose.slice(0, 34)}..." is not misread as unattended`, () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested');
+ const result = check({ fixture: fix({ workflowLog: `${prose}\nEnterPlanMode called`, genpagePlan: validPlan() }), eval: evalStub() });
+ assert.equal(result.status, 'pass');
+ });
+}
+
+// Omitting the section must stay valid — this guards against the obvious wrong fix of adding it to
+// REQUIRED_PLAN_SECTIONS. plan-schema.md:212 does spec the section as always-present, but 0 of the
+// 12 fixture plans emit it, so requiring it would fail 12/12 rather than catch a real defect.
+test('a plan without a Custom API Bindings section is still valid', () => {
+ const errors = validateGenpagePlanSchema(validPlan());
+ assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);
+});
+
+test('an opt-in Custom API Bindings section accepts the exact sentinel', () => {
+ const plan = `${validPlan()}\n\n## Custom API Bindings\nNo custom API bindings.\n`;
+ const errors = validateGenpagePlanSchema(plan);
+ assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);
+});
+
+// The Custom API mirror of the connector delimiter leak. If the planner prompt regresses and the
+// planner copies the `----- BEGIN/END CUSTOM API BINDINGS -----` framing into the plan, the body
+// is no longer the exact sentinel and must be rejected — previously nothing checked this half.
+test('a leaked prompt delimiter in Custom API Bindings is rejected', () => {
+ const plan = `${validPlan()}\n\n## Custom API Bindings\n----- BEGIN CUSTOM API BINDINGS -----\nNo custom API bindings.\n----- END CUSTOM API BINDINGS -----\n`;
+ const errors = validateGenpagePlanSchema(plan);
+ assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 1);
+});
+
+test('a populated Custom API Bindings table is accepted', () => {
+ const plan = `${validPlan()}\n\n## Custom API Bindings\n| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |\n|------|------|--------------|--------------|-------------------------|\n| new_ApproveOrder | Action | salesorder | Approve Order | Comment: String |\n`;
+ const errors = validateGenpagePlanSchema(plan);
+ assert.equal(errors.filter((e) => e.code === 'missing-customapi-table').length, 0);
+});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 48bcc0e23..d277ee2aa 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.7.1",
+ "version": "2.8.0",
"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.10.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.json
index 48bcc0e23..d277ee2aa 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.7.1",
+ "version": "2.8.0",
"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.10.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.md
index 8cea367cd..6290b0356 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -10,7 +10,7 @@ A plugin for building Power Apps for **model-driven apps**. Two **authoring** sk
- **`/genpage`** — build and deploy standalone **generative pages** (genux): React 17 + TypeScript +
Fluent UI V9 single-file components, deployed via PAC CLI. Orchestrates specialist agents (planner,
optional entity builder, parallel page builders).
-- **`/app-builder`** *(Preview)* — build and edit a **whole model-driven app** (tables, columns,
+- **`/app-builder`** — build and edit a **whole model-driven app** (tables, columns,
relationships, adaptive forms, views, charts, generative pages, app + sitemap, sample data, and
admin-gated AI features) from a natural-language intent, via the vendored headless `cds-maker-sdk`.
@@ -47,7 +47,8 @@ able to tell what moved from the docs alone):
| [`docs/app-builder-capabilities.md`](docs/app-builder-capabilities.md) | `/app-builder` **capabilities** — what ships today, with the evidence for each | You ship an app-builder capability |
| [`docs/app-builder-design.md`](docs/app-builder-design.md) | `/app-builder` **design record** — Part I staged-flow architecture (**cited from code by section number — never renumber**), Part II the `--changed-only` contract | You change the staged flow or the partial-apply contract |
| [`CHANGELOG.md`](CHANGELOG.md) | Keep-a-Changelog — concise bullets (detail lives in PRs/docs) | Any user-visible change |
-| [`references/app-spec-schema.md`](references/app-spec-schema.md) | The App Spec contract | You change the App Spec shape or validation |
+| [`references/app-spec-schema.md`](references/app-spec-schema.md) | The App Spec contract (always-present fields) | You change the App Spec shape or validation |
+| [`references/app-spec-schema-advanced.md`](references/app-spec-schema-advanced.md) | The conditional App Spec fields (business rules, BPFs, commands, web resources, global choices, dashboards, roleGrants) — split out so the always-read contract stays small | You change one of those features |
Don't duplicate content across these — **cross-link instead** (a second copy only drifts, as the file
tree and teardown order both did before).
@@ -78,7 +79,19 @@ A second skill (`/app-builder`) builds a whole **model-driven app** (tables, col
relationships, adaptive forms with sub-grids, views, Choice-column charts, app module +
sitemap) from a natural-language intent — distinct from `/genpage`, which builds generative
*pages*. The **whole flow runs in the main conversation loop, never a `Task` subagent** — subagents
-are headless, so `AskUserQuestion` and plan mode cannot reach the user. For the end-to-end flow,
+are headless, so `AskUserQuestion` and plan mode cannot reach the user. **This applies to `/genpage`
+too**: its agents are headless discovery/generation workers, and an agent that needs a decision
+returns a `needs_input` request for the main loop to ask (`references/agent-interaction-contract.md`).
+`scripts/validate-agent-interactivity.js` fails the build if any `plugins/model-apps/agents/*.md`
+declares an interactive tool — the frontmatter is prose to every other test, which is how `/genpage`
+Phase 1 specified an unreachable interactive flow for ~2.5 months. The same validator also fails a
+**one-sided tool declaration**: tool names are host-specific and every host silently ignores a name
+it does not recognize, so a capability named only in one scheme is absent on the other host and the
+agent launches without it. `TaskCreate`/`TaskUpdate`/`TaskList` are the live example — no published
+alias table lists them, so `todo` must be declared alongside. Both skills also support **unattended
+runs** (Copilot autopilot / Claude auto-accept) via
+`scripts/resolve-interaction-mode.js`; suppressing a prompt never authorizes destructive work.
+For the end-to-end flow,
stage→phase mapping and page-identity model, see
[`docs/architecture.md`](docs/architecture.md) → `## /app-builder — build pipeline`; that doc owns
the pipeline and delegates each script's **behavioral spec** to the entries below.
@@ -282,6 +295,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
general rule this bug taught: **assert what you PRODUCED, not what you intended** — "some table
component 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`.
+ `--verify` now asserts the same membership INDEPENDENTLY of the write path: it resolves the app's
+ `componenttype: 1` rows and fails, by table name, when a sitemap-visible table is not among them,
+ fails closed when that list cannot be read, and reports any leftover `entity` placeholder row. The
+ SDK's read-back only covers what a build intended to pin, so an app that drifted afterwards (or was
+ edited elsewhere) still verified clean — the sitemap named the table and the table existed, which
+ was all verify checked.
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
@@ -508,7 +527,14 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
(rebuild via `scripts/_vendor-build/`); **`scripts/lib/sdk-http-client.js`** injects an
`az`-token HttpClient. No browser, no relay — the SDK reuses the designer's own serializers.
- The build log is **phase-grouped with per-step status** (`▶ phase` / `[n/total] ✓ created` /
- `⊘ skipped` / `✗ failed`) + a closing summary; dry-run lists the same plan with a `▢` marker.
+ `⊘ skipped` / `✗ failed`) + a closing summary. A **dry run resolves each item against the live
+ environment** (#559) and marks it `+ create`, `= reuse`, or `? unknown` when the read failed —
+ never guessing, because a wrong confident answer is worse than none. Items with no live identity
+ (sample data, publish, generated icons) stay `▢` unprobed and are counted separately in the
+ summary. The probe reuses the build's OWN discovery helpers (`findExistingTable`,
+ `findExistingColumns`, `relationshipExists`, `artifactIdentityQuery`) rather than a parallel
+ implementation, so the plan cannot disagree with what the apply then does; it is read-only, and
+ `--no-live-plan` restores the offline, spec-only listing.
The end-to-end flow (Phase 0 working dir → Phase 1 author **in the main loop** per
`references/authoring-flow.md` → Phase 2 narrated SDK build → Phase 3 verify & iterate; **edit** an
@@ -538,7 +564,7 @@ AGENTS.md ← Plugin guidance for AI agents (this file)
CLAUDE.md ← Symlink → AGENTS.md
README.md ← User-facing intro and prereqs
CHANGELOG.md ← Keep-a-Changelog
-feature-flags.json ← Default-OFF feature flags (connectors, custom-api, custom-telemetry)
+feature-flags.json ← Feature flags (connectors=ga/on, custom-api, custom-telemetry)
.claude-plugin/plugin.json ← Legacy plugin metadata mirror
docs/
architecture.md ← Wiring/flow diagrams for BOTH skills (/genpage + /app-builder)
@@ -592,7 +618,8 @@ scripts/
lib/
entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data)
provision-input.js ← Input validation for entity provisioning
- dataverse-auth.js ← Shared auth + HTTP helpers (uses `az account get-access-token`)
+ dataverse-auth.js ← Shared auth + HTTP helpers (uses `az account get-access-token`), plus the CLI arg contract (parseArgs/validateFlags)
+ nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
feature-flags.js ← Default-OFF feature flag probe + connector script backstop
sdk-build.js ← app-builder build engine (idempotent; incl. the pages phase)
@@ -646,7 +673,7 @@ hooks/ ← Lifecycle hooks (registered in hooks/hooks.js
run-user-prompt-telemetry.js ← UserPromptSubmit: emits skill_started for /model-apps:<skill>
skills/
app-builder/
- SKILL.md ← intent → model-driven app (create + edit); **Preview**
+ SKILL.md ← intent → model-driven app (create + edit)
genpage/
SKILL.md ← Orchestrator skill (delegates to agents)
edit-flow.md ← Edit flow steps (loaded only on edit path)
@@ -660,7 +687,7 @@ skills/
| Skill | Description |
|-------|-------------|
| `/genpage` | Build and deploy generative pages for a model-driven Power App |
-| `/app-builder` | **(Preview)** Build and edit a whole model-driven app — tables, columns, relationships, adaptive forms, views, Choice-column charts, generative pages, app + sitemap, sample data, and admin-gated AI features — from a natural-language intent, via the vendored `cds-maker-sdk` |
+| `/app-builder` | Build and edit a whole model-driven app — tables, columns, relationships, adaptive forms, views, Choice-column charts, generative pages, app + sitemap, sample data, and admin-gated AI features — from a natural-language intent, via the vendored `cds-maker-sdk` |
| `/report-issue` | File a bug/issue about the model-apps plugin to the GitHub repository |
| `/telemetry` | Enable, disable, or check usage telemetry (`on \| off \| status`) |
@@ -697,14 +724,25 @@ Unreleased functionality is gated behind committed, **default-OFF** feature flag
the skill can merge ahead of its cross-repo dependencies. With a flag OFF, the
**deployed page behavior is identical to before the feature existed** — the guarantee
is about runtime/deploy output, not that every authoring artifact is byte-for-byte
-unchanged (e.g. plans still carry a `## Connector Bindings: No connector bindings.`
-line). The mechanism lives in `scripts/lib/feature-flags.js` with the committed
+unchanged. The mechanism lives in `scripts/lib/feature-flags.js` with the committed
values in `feature-flags.json` at the plugin root.
-- **Source of truth:** `feature-flags.json` (e.g. `{ "connectors": false }`). Flip a
- flag to `true` in a one-line PR once its dependencies are GA in PROD.
+**A GA flag is flipped to `true` FIRST and removed in a LATER change, not both at once.**
+Flipping is reversible in one line if the rollout turns out to be incomplete in some tenant;
+deleting the gate in the same change that enables the feature leaves no way back except a
+revert. Once a release has shipped with the flag on and no rollback was needed, remove it —
+a permanently-on gate is dead weight that still has to be probed, branched on and reasoned
+about at every call site.
+
+`connectors` is in that window now: **GA, shipping `true`, gate retained as a rollback
+switch, scheduled for removal in the next release.**
+
+- **Source of truth:** `feature-flags.json` (e.g. `{ "custom-api": false }`). Flip a
+ flag to `true` in a one-line PR once its dependencies are GA in PROD, then remove
+ it in a follow-up that deletes its gates.
- **Precedence (highest first):** env var `GENPAGE_ENABLE_<FLAG>` (e.g.
- `GENPAGE_ENABLE_CONNECTORS=1`) → committed `feature-flags.json` → default `false`
+ `GENPAGE_ENABLE_CONNECTORS=0` to roll connectors back) → committed
+ `feature-flags.json` → default `false`
(fail-closed). This mirrors the telemetry opt-out env-over-config convention.
- **LLM gate:** skill/agent markdown probes a flag with
`node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" <flag>` (prints `enabled`/`disabled`,
@@ -723,7 +761,7 @@ values in `feature-flags.json` at the plugin root.
to `true` — accidentally enable the wrong thing).
**Each gated feature has a SINGLE OWNER agent, and every entry point must go through it or the
-shared helper.** Both currently-gated features gate at the same five places, so the rule is stated
+shared helper.** The currently-gated features gate at the same five places, so the rule is stated
once here and only the per-feature specifics are tabled below:
1. **Discovery** — the owner agent runs the probe first; planners/edit-planners delegate to it and
@@ -745,10 +783,12 @@ once here and only the per-feature specifics are tabled below:
| **ALM** | the `--connection-refs` branch of `add-page-to-solution.js` | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) | none — telemetry rides the host runtime, nothing is packaged |
| **Emits** | connector code | `executeAction` / `executeFunction` / `listBoundActions` | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) |
-One connectors-only nuance: at Phase 4.5 the `/genpage` orchestrator re-probes and passes the
-verbatim result as `Connectors: enabled|disabled` in every page-builder dispatch — **that dispatch
-value wins over the plan's `## Connector Bindings` section.** Phase 4.7 does the same for
-`Telemetry: enabled|disabled`.
+At Phase 4.7 the `/genpage` orchestrator probes and passes the verbatim result as
+`Telemetry: enabled|disabled` in every page-builder dispatch — **that dispatch value wins over
+the plan.** Phase 4.5 passes a `Connectors: none|<n> binding(s)` line the same way, but note the
+difference: that value is the **binding count**, not the flag state. A disabled gate and an empty
+binding table both yield `none`, because the page-builder only needs to know how many bindings it
+may call — which keeps the dispatch stable when the flag is eventually removed.
`custom-telemetry` is the odd one out: it has no owner agent, no discovery script, no plan
section and no deploy or ALM step. It gates **code generation only** — steps 2-4 of the
@@ -870,6 +910,51 @@ repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a **physical copy*
- **Accessibility** — WCAG AA, ARIA labels, keyboard navigation, semantic HTML
- **Complete code** — no placeholders, TODOs, or ellipses in final output
+## CLI argument contract
+
+**Every `scripts/*.js` entry point declares its flags and validates them up front.** `parseArgs`
+accepts any `--name`, and an unrecognised flag is both dropped silently *and* swallows the token
+after it — so a typo does not fail, it quietly changes what the command does. Measured on
+`build-model-app.js` before this was enforced: `--stage ui` planned 3 steps, while `--stagee ui`
+planned all 9 and still exited 0, turning a scoped UI apply into a full data-model apply.
+
+So a `main()` starts with:
+
+```js
+const argv = process.argv.slice(2);
+const { positional, flags } = parseArgs(argv);
+const flagError = validateFlags(argv, {
+ known: ['env', 'spec', 'stage', 'apply'], // every flag this CLI accepts
+ needValue: ['env', 'spec', 'stage'], // those that must carry a value
+ hints: { stage: 'one of: data, ui, app, publish' }, // optional, for closed value sets
+});
+if (flagError) { process.stderr.write(`✗ ${flagError}\n${USAGE}\n`); process.exit(1); }
+```
+
+`validateFlags` (`scripts/lib/dataverse-auth.js`) rejects unknown flags with a single-edit "did you
+mean" (via `scripts/lib/nearest-name.js`, shared with the FetchXML operator lint), and rejects a
+value-bearing flag passed bare or empty. It reads flag names from `argv` rather than the parsed
+object, because `--__proto__` goes through the inherited setter and never becomes an own property.
+
+Two consequences worth knowing:
+
+- Because `validateFlags` guarantees a `needValue` flag is either absent or a non-empty string,
+ `typeof flags.x === 'string' ? flags.x : undefined` is redundant afterwards — read `flags.x`.
+- `needValue` must be a subset of `known`; `validateFlags` throws if it is not, which catches a
+ rename applied to one list and not the other.
+
+When a CLI test harness cans `parseArgs` to a fixed result, use
+`scripts/tests/helpers/fake-auth.js` → `validateFlagsFromParsed` so the harness exercises the **real**
+validator instead of a hand-written copy that can drift from it.
+
+**Testing a CLI end to end:** `scripts/tests/helpers/cli-harness.js` → `loadCli(scriptPath, { requires, argv })`
+loads an entry point with injectable module stubs and a shadowed `process`, so a test can drive
+`main()` and assert the **wire calls** it makes (the Dataverse requests, the `AddSolutionComponent`
+component types, the temp-workspace cleanup) rather than regex-matching the source. It uses
+`vm.compileFunction`, **not** `vm.runInNewContext`: a new VM context is a separate realm with its own
+`Array`/`Object` prototypes, so every array the script builds would fail `assert.deepStrictEqual`
+against a host array with "same structure but not reference-equal".
+
## Dataverse Access From Scripts
**Default: go through the vendored SDK.** Anything the SDK models — tables, columns, relationships,
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 085cb5794..6d812aee6 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,7 +5,93 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
-## [Unreleased] — 2.7.1
+## [Unreleased] — 2.8.0
+
+A dry run that says what an apply would really do, sample data that can express a hierarchy, and
+downloads that round-trip Choice columns.
+
+### Added
+
+- **The dry run resolves create-vs-reuse against the live environment** ([#559]). Without `--apply`
+ the plan was a static echo of the spec, identical whether every artifact already existed or none
+ did — the one question a dry run exists to answer. Each item is now `+ create` or `= reuse`, with
+ a summary (`2 to create, 6 already present`); an unreadable item is `? unknown`, never guessed.
+ The probe reuses the build's own discovery, so the plan cannot drift from the apply.
+ `--no-live-plan` restores the offline listing.
+- **Sample data can express a hierarchy on one table** ([#544]). A `$parent` may target the row's
+ own entity (an org tree, a "reports to" chain). Rows are seeded in dependency waves, so
+ declaration order does not matter, and a cycle is rejected by the lint rather than failing the
+ build partway through. Add `$parent.lookup` to say which relationship a bind uses — required only
+ when two or more relationships connect the same pair, and now **rejected** rather than silently
+ taking the first declared one.
+
+### Fixed
+
+- **A download round-trips Choice and MultiChoice columns** ([#564]). They were emitted with no
+ `type`, so rebuilding into a **fresh** environment created single-line Text while Memo, Money and
+ DateTime survived — an asymmetry harder to notice than an outright failure. Option sets are now
+ read per table: a local set becomes inline `options[]` (localizations preserved), a shared one a
+ `globalChoice` reference plus a `globalChoices[]` declaration. Four related defects went with it:
+ a **MultiChoice column was dropped from the spec entirely** (Dataverse types it `Virtual`); a
+ lookup's synthetic `<lookup>name` column was emitted as a real Text column, which a fresh rebuild
+ then created; a legal multi-language option set could abort the **whole** download; and
+ `globalChoices[]` could declare sets nothing referenced. A column whose option set cannot be read
+ is still left untyped — but now named, with the reason. Note the App Spec cannot express option
+ *values*: labels and order round-trip, and a fresh rebuild re-bases them to `100000000 + index`.
+- **`--verify` checks that a sitemap-visible table really belongs to the app.** The sitemap and the
+ app module's table list are separate facts and can disagree, so an app could show a table in
+ navigation while omitting it from its Tables list — and verify still said PASS, because the table
+ existed and the sitemap named it. It now fails by table name, fails **closed** when the component
+ list cannot be read, and reports leftover `entity` placeholder components.
+- **A multi-line page prompt is no longer flattened on upload** ([#565]). Prompts went to `pac`
+ inline, where a newline guard collapsed every line break — so a downloaded conversation transcript
+ degraded a little more on each edit-rebuild. They now go through `--prompt-file` /
+ `--agent-message-file`. `upload()` also accepts an optional `compiledCodeFile`.
+- **`/genpage` Phase 1 is reachable again** ([#541]). Its interactive flow was specified to run
+ inside a headless `Task` subagent, so create flows could not complete. Interaction now runs in the
+ main loop; the agents are headless workers that return a `needs_input` request when they need a
+ decision (`references/agent-interaction-contract.md`).
+- **Teardown no longer reports a false failure for a self-referencing relationship** ([#544]). The
+ table delete already removes it, so deleting it first returned `referenced by 2 other components`
+ and a completely clean run still exited non-zero.
+- **A mistyped flag now fails instead of quietly changing what the command does.** An unrecognised
+ flag was dropped *and* swallowed the token after it: `--stagee ui` planned all 9 phases instead of
+ 3 and exited 0 — with `--apply`, a scoped apply became a full one. Every CLI now declares the
+ flags it accepts, rejects anything else with a "did you mean", and rejects a value-bearing flag
+ passed bare. This also covers `--allow-destructiv` and friends on the destructive tools.
+- **A test file in a `scripts/tests/` subdirectory is no longer silently skipped.** Discovery was a
+ flat `readdir`, so a nested suite would be committed, reviewed, reported green and never run.
+
+### Changed
+
+- **`/app-builder` is GA.** The preview notice is gone: the App Spec shape, the CLI flags and the
+ build phases are now treated as a stable contract rather than one that may change between
+ versions. The guidance that outlived the notice stays — review the dry-run plan before approving,
+ and use `teardown-model-app.js --apply` to clean up probes. `--changed-only` (partial apply) is
+ the one piece still experimental, and remains off by default.
+- **Connector authoring is GA and on by default.** SharePoint / weather / Office 365 / SQL /
+ custom-REST binding and ALM packaging of connection references work without opting in. The
+ `connectors` flag is **flipped to `true` and kept for one release as a rollback switch** —
+ `GENPAGE_ENABLE_CONNECTORS=0` restores the old behaviour — and is scheduled for removal next
+ release. `custom-api` and `custom-telemetry` are unaffected and still default-OFF.
+- **The Phase 4.5 dispatch value is the binding count, not the flag state.** The page-builder gets
+ `Connectors: none` or `<n> binding(s)`; a disabled gate and an empty binding table both yield
+ `none`, so the dispatch stays stable when the flag is removed.
+- **The App Spec schema is split so the always-read half is smaller.** `globalChoices`,
+ `webResources`, `commands`, `businessRules`, `businessProcessFlows`, `dashboards` and `roleGrants`
+ moved to `app-spec-schema-advanced.md`, leaving a pointer table: 105 KB → 82 KB eagerly read.
+- **The CLI flag contract is shared rather than per-script**, so the flag rules and the "did you
+ mean" suggestion cannot drift between commands.
+- **Deeper tests on the paths connectors GA just made live**, including a connector *edit* eval and
+ a contract test pinning the dispatch fields the skills hand to the page-builder.
+
+[#541]: https://github.com/microsoft/power-platform-skills/issues/541
+[#544]: https://github.com/microsoft/power-platform-skills/issues/544
+[#559]: https://github.com/microsoft/power-platform-skills/issues/559
+[#564]: https://github.com/microsoft/power-platform-skills/issues/564
+[#565]: https://github.com/microsoft/power-platform-skills/issues/565
+
+## [2.7.1]
Three defects an author hits before reaching an environment, and a session-start warning.
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index b2d016bfd..7e34f8311 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -37,7 +37,13 @@ status) in `scripts/lib/feature-flags.js`; their on/off value lives in
| Flag | Status | Enables | Depends on |
|---|---|---|---|
-| `connectors` | in-progress | GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) + ALM packaging of connection references | pac CLI connector verbs, the GenUX authoring control, and the maker/admin ECS setting — all live in PROD |
+| `connectors` | **ga (on by default)** | GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) + ALM packaging of connection references | pac CLI connector verbs, the GenUX authoring control, and the maker/admin ECS setting — all live in PROD |
+| `custom-api` | in-progress | Calling a Dataverse Custom API Action or Function from a generated page (`executeAction` / `executeFunction` / `listBoundActions`) | the AIBuilder action prompt, the shared action runtime, the UCI and Controls host runtimes, a pac CLI `model genpage upload --actions` verb, and the `GenUxPluginActionAllowList` setting — all live in PROD |
+| `custom-telemetry` | in-progress | A generated page reporting its own events, metrics, traces and exceptions to your Application Insights resource via `props.appInsights` | the page telemetry facade in the UCI host runtime, the GenUX authoring control, the AIBuilder telemetry prompt, and the `GenUxEnableCustomTelemetry` setting — all live in PROD |
+
+Connector authoring is **GA and on by default**. Its flag is kept for one release as a
+rollback switch: set `GENPAGE_ENABLE_CONNECTORS=0` (or `"connectors": false`) if your
+environment turns out to be missing one of the dependencies above.
**See the current state** (status, whether each flag is on, and why):
@@ -49,18 +55,18 @@ node scripts/lib/feature-flags.js --list
```powershell
# Windows (PowerShell)
-$env:GENPAGE_ENABLE_CONNECTORS = "1"
+$env:GENPAGE_ENABLE_CUSTOM_API = "1"
```
```bash
# macOS / Linux (bash)
-export GENPAGE_ENABLE_CONNECTORS=1
+export GENPAGE_ENABLE_CUSTOM_API=1
```
**Enable it persistently** by flipping the value in `feature-flags.json`:
```json
-{ "connectors": true }
+{ "custom-api": true }
```
Precedence is **env var → `feature-flags.json` → default OFF** (fail-closed). Only
@@ -76,7 +82,7 @@ use either on its own, and neither requires the other.**
| Skill | Status | Use it when |
|---|---|---|
-| [`/app-builder`](#app-builder) | **Preview** | You want a whole app — tables, relationships, forms, views, charts, security roles, app + sitemap |
+| [`/app-builder`](#app-builder) | Stable | You want a whole app — tables, relationships, forms, views, charts, security roles, app + sitemap |
| [`/genpage`](#genpage) | Stable | You want one or more generative pages added to an app that already exists |
Already have an app and just want to add a page? Use `/genpage` — you never need to run
@@ -85,10 +91,9 @@ of the build, so you don't need to run `/genpage` afterwards.
### `/app-builder`
-> **Preview.** This skill is under active development: its App Spec schema and CLI flags may change
-> between releases, and `--changed-only` (partial apply) is Preview within it. Prefer a scratch/dev
-> environment, review the dry-run plan before approving, and use `teardown-model-app.js --apply` to
-> clean up probes. Report issues with `/report-issue`.
+> Review the dry-run plan before approving, and use `teardown-model-app.js --apply` to clean up
+> probes. `--changed-only` (partial apply) is still experimental and off by default. Report issues
+> with `/report-issue`.
Builds and edits a whole model-driven Power App from a natural-language intent, via the headless
vendored `cds-maker-sdk`. It runs an interactive, multi-turn authoring flow and a narrated build:
@@ -226,6 +231,7 @@ un-provisioned copies. Once enabled it is **on by default** (you opt out).
## Documentation
+- [Build Model-Driven Apps with External Tools](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/model-driven-app-external-tools)
- [Generative Pages with External Tools](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/generative-page-external-tools)
- [Generative Pages Overview](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/generative-pages)
- [Power Apps Model-Driven Apps](https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/model-driven-app-overview)
diff --git a/plugins/model-apps/agents/genpage-connector-builder.md b/plugins/model-apps/agents/genpage-connector-builder.md
index 1215bb059..7b88dd4a8 100644
--- a/plugins/model-apps/agents/genpage-connector-builder.md
+++ b/plugins/model-apps/agents/genpage-connector-builder.md
@@ -2,21 +2,51 @@
name: genpage-connector-builder
description: >-
Owns ALL GenPage connector work: it is the single owner of the connectors
- feature-flag gate, performs connector discovery (connections, connection
+ rollback gate, performs connector discovery (connections, connection
references, datasets, tables, operations, and schema), creates Dataverse
connection references when needed, and produces the ## Connector Bindings
contract. Invoked only by the top-level genpage orchestrator from BOTH the
create and edit flows; never invoked by planners or directly by users.
color: green
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# shell and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate`/`TaskList` are NOT aliases anywhere —
+# `todo` is the portable name. See references/agent-interaction-contract.md.
tools:
- Read
- Write
- Bash
- - AskUserQuestion
- TaskCreate
- TaskUpdate
- TaskList
+ - read
+ - edit
+ - execute
+ - todo
---
+## Interaction contract — this agent is HEADLESS
+
+You run as a `Task` subagent: there is **no user on the other end**, and
+`AskUserQuestion` / `EnterPlanMode` / `ExitPlanMode` are not in your tool list.
+Never claim a user answered something.
+
+When you need a decision, stop and return a request for the orchestrator to put
+to the user in the main conversation loop:
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>" } ],
+ "multiSelect": false } ] }
+```
+
+Return what you have already discovered alongside it so the re-invocation does
+not repeat the reads. Full contract: `references/agent-interaction-contract.md`.
# Genpage Connector Builder
@@ -76,7 +106,7 @@ forward the entire `connector-bindings.md` body and the `connectors.json` path (
Log every command you run (with its purpose) into the working directory's
`workflow-log.md`.
-## Step 1 — Feature gate (you own it; run it FIRST, always)
+## Step 1 — Rollback gate (you own it; run it FIRST, always)
Probe the flag before ANY discovery, for both create and edit:
@@ -84,23 +114,23 @@ Probe the flag before ANY discovery, for both create and edit:
node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors
```
-Record the result in `workflow-log.md` (e.g. `feature-flags.js connectors → disabled`).
+Record the result in `workflow-log.md` (e.g. `feature-flags.js connectors → enabled`).
+
+Connectors are **GA and the flag ships ON**, so this normally prints `enabled` and you
+continue to Step 2. The gate is retained for one release as a rollback switch, so handle
+the off case:
-**If it prints `disabled` (exit 1)** — connector support is not live in PROD:
+**If it prints `disabled` (exit 1)** — connector support has been explicitly turned off
+(`GENPAGE_ENABLE_CONNECTORS=0`, or `"connectors": false` in `feature-flags.json`):
- Do **not** run `list-connections.js` or any other connector discovery.
- **create:** write `connector-bindings.md` containing exactly
`No connector bindings.` and `connectors.json` containing `[]`. Return
`connectors disabled — no bindings`.
-- **edit:** connectors are OFF, so you must **not add or discover** new bindings.
- **Preserve** the existing bindings passed to you: write them unchanged to
- `connectors.json` (bare array) and reproduce them in `connector-bindings.md`.
- Return `connectors disabled — existing bindings preserved, none added`.
-
-Only when it prints `enabled` (exit 0) do you continue to Step 2. The flag lives
-in `plugins/model-apps/feature-flags.json`; it is flipped to `true` (or
-`GENPAGE_ENABLE_CONNECTORS=1` for a single run) once the pac connector verbs, the
-GenUX control, and the maker/admin setting are all released.
+- **edit:** you must **not add or discover** new bindings. **Preserve** the existing
+ bindings passed to you: write them unchanged to `connectors.json` (bare array) and
+ reproduce them in `connector-bindings.md`. Return
+ `connectors disabled — existing bindings preserved, none added`.
## Step 2 — Connection discovery (enabled only)
@@ -114,9 +144,72 @@ node "${PLUGIN_ROOT}/scripts/list-connections.js" "<ENV_URL>"
The script returns `connections` sorted with `readyToBind: true` first and
`connectionReferences` from Dataverse. `readyToBind` means a connection reference
is actually bound to that connection (its `connectionId` matches) — prefer those.
-Present ready-to-bind choices first via `AskUserQuestion`, showing the
+Offer ready-to-bind choices first in a `needs_input` request, showing the
connectionreference logical name, connector id, and connection display name.
+After selecting any existing connection — before branching into tabular versus
+REST/action discovery — derive `connectorName` from the final path segment of
+its full `connectorId`. PAC metadata commands use `connectorName`; binding files
+retain the full `connectorId`.
+
+### No suitable connection exists — set one up
+
+When the requested connector has no usable connection, do not stop at "none
+found" and do not substitute an unrelated connector silently. Once the exact
+connector id is known from discovery or an orchestrator-approved choice, derive
+its **connector name** from the final path segment (`shared_office365users` from
+`/providers/Microsoft.PowerApps/apis/shared_office365users`) and attempt setup:
+
+```powershell
+# Read Environment ID and the active PAC username; do not infer either.
+pac org who
+pac auth list
+node --version
+
+npx --yes --package @microsoft/[email protected] power-apps auth-status `
+ --cloud "<POWER_APPS_CLOUD>" --environment-id "<ENVIRONMENT_ID>" --json
+npx --yes --package @microsoft/[email protected] power-apps auth-switch `
+ --cloud "<POWER_APPS_CLOUD>" --account "<HOME_ACCOUNT_ID>" `
+ --environment-id "<ENVIRONMENT_ID>" --non-interactive --json
+npx --yes --package @microsoft/[email protected] power-apps create-connection `
+ --cloud "<POWER_APPS_CLOUD>" --api-id "<connectorName>" `
+ --environment-id "<ENVIRONMENT_ID>" --non-interactive --json
+```
+
+Connection creation is allowed here because mode and environment were resolved
+before this agent was dispatched. Before running `auth-switch` or `create-connection`,
+normalize the `pac org who` **Org URL** and `<ENV_URL>` (lowercase, remove one
+trailing slash) and require an exact match. Derive `<ENVIRONMENT_ID>` and
+`<PAC_USER>` only from that verified active profile. If the URLs mismatch,
+return `needs_input` describing both URLs; do not mutate either environment.
+Map the verified PAC profile's cloud explicitly:
+`Public → public`, `UsGov → usgov`, `UsGovHigh → usgovhigh`,
+`UsGovDod → usgovdod`, and `China → china`. Use the mapped value as
+`<POWER_APPS_CLOUD>` on every Power Apps CLI command. An unknown or ambiguous
+cloud (including an internal/test cloud with no documented mapping) must return
+`needs_input` rather than defaulting to public.
+The optional `@microsoft/[email protected]` setup path requires **Node 22+**;
+parse the `node --version` major and return `needs_input` with the Maker URL
+instead of invoking it on an older runtime.
+
+Inspect `auth-status --json` and find case-insensitive username matches for
+`<PAC_USER>`. Require **exactly one** cached match; zero or multiple matches are
+missing/ambiguous and must return `needs_input`. Use that row's tenant-specific
+`homeAccountId` as `<HOME_ACCOUNT_ID>` for `auth-switch`, then verify the
+command's returned active account has the same `homeAccountId` before creating
+the connection. A headless worker must **never run `power-apps login`** and must never set
+`POWERAPPS_CLI_ENABLE_BROWSER_CONNECTION=true`; both can launch a browser. It is
+otherwise still fail-closed:
+
+- If the SSO-capable connection succeeds, capture the returned `connectionId`,
+ rerun `list-connections.js`, then continue with connection-reference setup.
+- If `create-connection` reports that login, consent, or browser interaction is
+ required, return a `needs_input` request with the exact Maker connections
+ URL (`https://make.powerapps.com/environments/<ENVIRONMENT_ID>/connections`)
+ and the connector name. Do not claim setup succeeded.
+- Never invent a connector API id. If discovery and the supplied intent do not
+ establish one exactly, return `needs_input` before running `create-connection`.
+
If the maker chooses a connection that has **no** connection reference, do not
invent a logical name — create one:
@@ -138,15 +231,18 @@ node "${PLUGIN_ROOT}/scripts/create-connection-reference.js" "<ENV_URL>" "<logic
- Pre-flight that `pac model genpage --help` lists `list-connector-operations`
and `get-connector-schema`.
+- PAC metadata commands require the already-derived **connector name**, even
+ though the flag is named `--connector-id`. Keep the full connectorId value
+ (`/providers/Microsoft.PowerApps/apis/...`) for `connectors.json`.
- Enumerate operations:
```powershell
- pac model genpage list-connector-operations --connector-id <apiId> --connection-id <connId>
+ pac model genpage list-connector-operations --connector-id <connectorName> --connection-id <connId>
```
-- Let the maker pick via `AskUserQuestion` when the requirement doesn't imply
+- Let the maker pick via a `needs_input` request when the requirement doesn't imply
exactly one operation.
- Discover the operation schema:
```powershell
- pac model genpage get-connector-schema --connector-id <apiId> --connection-id <connId> --operation <op>
+ pac model genpage get-connector-schema --connector-id <connectorName> --connection-id <connId> --operation <op>
```
- Parse `{ operation, parameters:[{ name, required }], response:{...} }` and
record `Operations`, `Parameters`, and `Response`.
@@ -160,7 +256,7 @@ The binding tells the runtime *where* to fetch; `Fields` tells the page-builder
connection id, dataset, and table:
```powershell
-pac model genpage get-connector-schema --connector-id <apiId> --connection-id <connId> --dataset <ds> --table <tableId>
+pac model genpage get-connector-schema --connector-id <connectorName> --connection-id <connId> --dataset <ds> --table <tableId>
```
Parse `{ table, columns:[{ name, type, required }] }` and record each column in
@@ -180,7 +276,7 @@ For SharePoint, filter columns before recording `Fields`:
values arrive as `{ Value }`).
Fallback when the PAC verb is unavailable: sample the top 1 row and record its
-keys/observed shapes, or ask the maker via `AskUserQuestion`. **Never fabricate
+keys/observed shapes, or ask the maker via a `needs_input` request. **Never fabricate
field names.** If fields cannot be discovered or supplied, keep the binding out of
the result rather than letting the page-builder guess.
diff --git a/plugins/model-apps/agents/genpage-customapi-builder.md b/plugins/model-apps/agents/genpage-customapi-builder.md
index a3fb219ed..292443415 100644
--- a/plugins/model-apps/agents/genpage-customapi-builder.md
+++ b/plugins/model-apps/agents/genpage-customapi-builder.md
@@ -4,18 +4,48 @@ description: >-
Owns ALL GenPage Dataverse Custom API (plug-in) work: it is the single owner of the
custom-api feature-flag gate, discovers the Custom APIs a page can bind to (Global and
entity-bound Actions/Functions) plus their declared request-parameter kinds, and produces
- the ## Custom API Bindings contract. Invoked by the genpage skill from BOTH the create flow
- (planner) and the edit flow (edit-planner) — never invoked directly by users.
+ the ## Custom API Bindings contract. Invoked only by the top-level genpage orchestrator from
+ BOTH the create and edit flows; never invoked by planners or directly by users.
color: green
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# shell and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate`/`TaskList` are NOT aliases anywhere —
+# `todo` is the portable name. See references/agent-interaction-contract.md.
tools:
- Read
- Write
- Bash
- - AskUserQuestion
- TaskCreate
- TaskUpdate
- TaskList
+ - read
+ - edit
+ - execute
+ - todo
---
+## Interaction contract — this agent is HEADLESS
+
+You run as a `Task` subagent: there is **no user on the other end**, and
+`AskUserQuestion` / `EnterPlanMode` / `ExitPlanMode` are not in your tool list.
+Never claim a user answered something.
+
+When you need a decision, stop and return a request for the orchestrator to put
+to the user in the main conversation loop:
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>" } ],
+ "multiSelect": false } ] }
+```
+
+Return what you have already discovered alongside it so the re-invocation does
+not repeat the reads. Full contract: `references/agent-interaction-contract.md`.
# Genpage Custom API Builder
@@ -23,9 +53,27 @@ You are the Dataverse **Custom API** specialist for generative pages. A Custom A
server-side plug-in logic a maker authored in the environment; each is either an **Action**
(may mutate; called with `dataApi.executeAction`) or a **Function** (read-only; called with
`dataApi.executeFunction`). You are the **single owner** of Custom API discovery and the
-feature gate. Both the create flow (`genpage-planner`) and the edit flow
-(`genpage-edit-planner`) delegate ALL Custom API work to you so the gate and the discovery
-logic live in exactly one place.
+feature gate. Planners must not invoke you directly; they have no `Task` tool, and nested
+`Task` calls cannot safely host your user-facing Custom API selection prompts. The top-level
+`/genpage` orchestrator dispatches you from BOTH flows so the gate and the discovery logic
+live in exactly one place.
+
+Your discovery is **read-only** (a Web API query over the Custom API tables), so unlike the
+connector builder it has no "wrong environment cannot be undone" hazard. Even so, you are
+dispatched only once the mode, environment, and page tables are known, so you query the right
+environment and bind to the right page:
+
+- **Create flow** — `genpage-planner` runs FIRST (it resolves create vs. edit and the
+ environment). It returns
+ `{ "action": "custom_api_discovery_required", "resolvedAction", "envUrl", "pageTables", "intent" }`,
+ the orchestrator dispatches you with exactly those, then re-invokes the planner with your
+ `## Custom API Bindings` contract.
+- **Edit flow** — the mode is already `edit`, and the edit orchestrator captured `envUrl` in
+ Edit Phase 1 and the page tables from `config.json.dataSources`, so when the edit intent
+ *already* names a Custom API operation you are dispatched **before** `genpage-edit-planner`,
+ and your contract is forwarded into it. If the need instead surfaces during the edit
+ planner's own clarification, it returns the same `custom_api_discovery_required` signal and
+ you are dispatched then, with the planner re-invoked afterwards.
You do **not** create Custom APIs — they are pre-existing artifacts. You only discover which
ones the page may call and record them so the page binds correctly.
@@ -102,7 +150,7 @@ Omit `--entities` for a mock/global-only page to get every Global API. The scrip
parameterKinds }] }`, already projected into the binding shape.
Match the maker's **intent** to the discovered APIs by `displayName` / `name`. When more than
-one plausibly matches, present the choices via `AskUserQuestion` (show `name`, Action vs
+one plausibly matches, return the choices in a `needs_input` request (show `name`, Action vs
Function, and Global vs the bound table). **Never invent** a Custom API `name`, a parameter
name, or a parameter kind that the script did not return — a name the runtime does not find in
the manifest fails closed with `not_bound`, and a wrong parameter kind corrupts the wire type.
diff --git a/plugins/model-apps/agents/genpage-edit-planner.md b/plugins/model-apps/agents/genpage-edit-planner.md
index c6c72302d..b554b76ca 100644
--- a/plugins/model-apps/agents/genpage-edit-planner.md
+++ b/plugins/model-apps/agents/genpage-edit-planner.md
@@ -3,28 +3,59 @@ name: genpage-edit-planner
description: >-
Plans edits to an existing generative page. Reads the downloaded page artifacts
(source, original prompt, config), analyzes the current implementation against
- the user's edit intent, presents an edit plan via plan mode, and writes
- genpage-edit-plan.md for the orchestrator to execute. Called by the genpage
+ the user's edit intent, and returns a proposed edit plan for the orchestrator to
+ present for approval. Writes genpage-edit-plan.md, for the orchestrator to
+ execute, once it is re-invoked with the approval outcome. Called by the genpage
skill — not invoked directly by users.
color: cyan
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# search and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate`/`TaskList` are NOT aliases anywhere —
+# `todo` is the portable name. No `execute`/`Bash`: this planner reads and
+# plans, it does not run commands. See references/agent-interaction-contract.md.
tools:
- Read
- Write
- Glob
- - EnterPlanMode
- - ExitPlanMode
- TaskCreate
- TaskUpdate
- TaskList
- - AskUserQuestion
+ - read
+ - edit
+ - search
+ - todo
---
+## Interaction contract — this agent is HEADLESS
+
+You run as a `Task` subagent: there is **no user on the other end**, and
+`AskUserQuestion` / `EnterPlanMode` / `ExitPlanMode` are not in your tool list.
+Never claim a user answered something.
+
+When you need a decision, stop and return a request for the orchestrator to put
+to the user in the main conversation loop:
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>" } ],
+ "multiSelect": false } ] }
+```
+
+Return what you have already discovered alongside it so the re-invocation does
+not repeat the reads. Full contract: `references/agent-interaction-contract.md`.
# Genpage Edit Planner
You are the planning agent for edits to an existing generative page. Your job is
-to understand the current page, gather the user's change requirements, present
-the edit plan for approval, and write `genpage-edit-plan.md` for the
-orchestrator to apply.
+to understand the current page, work out the change requirements, propose an edit
+plan, and — once the orchestrator reports it approved — write
+`genpage-edit-plan.md` for the orchestrator to apply. You are **headless**: you
+request clarification and approval through the orchestrator rather than prompting.
You will be invoked by the `/genpage` skill with a prompt that includes:
@@ -100,7 +131,8 @@ Create tasks via `TaskCreate`:
2. "Design edit plan"
3. "Write edit plan document (genpage-edit-plan.md)"
-Ask questions via `AskUserQuestion`, one at a time:
+Return these questions to the orchestrator as a `needs_input` request, one batch
+at a time (you are headless — see the interaction contract below):
1. **"What changes would you like to make?"**
- Skip this question if `$ARGUMENTS` already describes the edit clearly.
@@ -122,7 +154,7 @@ Ask questions via `AskUserQuestion`, one at a time:
> **Connector data changes** (SharePoint, weather, Office 365, SQL, custom REST):
> Do **not** run connector discovery here — the orchestrator delegates that to the
-> `genpage-connector-builder` agent (which owns the feature gate).
+> `genpage-connector-builder` agent (which owns connector discovery and its rollback gate).
>
> - **Preserving or clearing** existing connectors needs no discovery: capture it
> in the plan's `### Connector Changes` and continue.
@@ -142,17 +174,32 @@ Ask questions via `AskUserQuestion`, one at a time:
> deployed binding**. The orchestrator will run discovery and re-invoke you with a
> real connector contract and upload-file status.
-> **Custom API changes** (Dataverse Action/Function / plug-in logic): if the edit adds,
-> replaces, or removes a server-side Custom API call, capture it in the plan's `### Custom
-> API Changes` below. Do **not** run Custom API discovery here — the orchestrator delegates
-> that to the `genpage-customapi-builder` agent (which owns the `custom-api` feature gate).
-> Preserving or clearing existing Custom API bindings needs no discovery.
+> **Custom API changes** (Dataverse Action/Function / plug-in logic):
+> Do **not** run Custom API discovery here — the orchestrator delegates that to the
+> `genpage-customapi-builder` agent (which owns the `custom-api` feature gate).
+>
+> - **Preserving or clearing** existing Custom API bindings needs no discovery: capture it
+> in the plan's `### Custom API Changes` and continue.
+> - **Adding or replacing** a Custom API call that the orchestrator did not already discover
+> — i.e. the need surfaced in *your* clarification, so your prompt carries the "preserve"
+> action and `none — omit --actions` — you must **stop and return**
+>
+> ```json
+> { "action": "custom_api_discovery_required", "intent": "<the operation(s) implied>",
+> "resolvedAction": "edit", "envUrl": "<the environment URL you were given>",
+> "pageTables": "<the page's entity logical names, comma-separated, or none>" }
+> ```
+>
+> Do **not** write the edit plan. If you proceed instead, the apply step will generate
+> `executeAction` / `executeFunction` calls while upload still omits `--actions`, shipping a
+> page whose Custom API calls have **no deployed binding**. The orchestrator will run
+> discovery and re-invoke you with a real Custom API contract and upload-file status.
Mark "Analyze existing page" task complete.
-## Step 3 — Present Edit Plan for Approval
+## Step 3 — Hand the Edit Plan Back for Approval
-Enter plan mode (`EnterPlanMode`) with:
+Return this plan to the orchestrator, which presents it with `EnterPlanMode`:
```markdown
## Genpage Edit Plan
@@ -183,10 +230,13 @@ Enter plan mode (`EnterPlanMode`) with:
- [Any tension with the original prompt, or any risky aspects — or "None"]
```
-Call `ExitPlanMode` to request approval.
+The orchestrator calls `ExitPlanMode` to request approval and reports the outcome.
- If approved: proceed to Step 4.
-- If changes requested: revise and re-enter plan mode.
+- If changes requested: revise the plan and **return it** for the orchestrator to
+ re-present. You are headless and have no `EnterPlanMode`/`ExitPlanMode`, so you
+ cannot re-enter plan mode yourself — the orchestrator owns every presentation
+ round (see `edit-flow.md`, "Edit Phase 4").
Mark "Design edit plan" task complete.
@@ -268,5 +318,6 @@ Plan document: <working-dir>/genpage-edit-plan.md
- **Do NOT deploy.** Deployment is handled by the orchestrating skill.
- **Do NOT regenerate the entire file.** The orchestrator makes targeted edits.
Your plan should describe changes, not rewrite the code.
-- **One user interaction point:** The plan mode approval in Step 3 (plus
- requirements questions in Step 2).
+- **One user interaction point:** the plan approval in Step 3 (plus requirements
+ questions in Step 2). You never make those calls — you return a request and the
+ orchestrator asks.
diff --git a/plugins/model-apps/agents/genpage-entity-builder.md b/plugins/model-apps/agents/genpage-entity-builder.md
index f789ae414..f7e77caa4 100644
--- a/plugins/model-apps/agents/genpage-entity-builder.md
+++ b/plugins/model-apps/agents/genpage-entity-builder.md
@@ -6,6 +6,12 @@ description: >-
propagation delays, sample data creation (with $batch bulk), and solution membership.
Called by the genpage skill when new entities need creating — not invoked directly by users.
color: yellow
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# shell and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate`/`TaskList` are NOT aliases anywhere —
+# `todo` is the portable name. See references/agent-interaction-contract.md.
tools:
- Read
- Write
@@ -13,8 +19,32 @@ tools:
- TaskCreate
- TaskUpdate
- TaskList
- - AskUserQuestion
+ - read
+ - edit
+ - execute
+ - todo
---
+## Interaction contract — this agent is HEADLESS
+
+You run as a `Task` subagent: there is **no user on the other end**, and
+`AskUserQuestion` / `EnterPlanMode` / `ExitPlanMode` are not in your tool list.
+Never claim a user answered something.
+
+When you need a decision, stop and return a request for the orchestrator to put
+to the user in the main conversation loop:
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>" } ],
+ "multiSelect": false } ] }
+```
+
+Return what you have already discovered alongside it so the re-invocation does
+not repeat the reads. Full contract: `references/agent-interaction-contract.md`.
# Genpage Entity Builder
@@ -391,7 +421,8 @@ Mark the task complete.
## Step 6 — Ask About Sample Data
-Use `AskUserQuestion`:
+Return a `needs_input` request (you are headless — the orchestrator asks and
+records it as `AskUserQuestion: … → …` in `workflow-log.md`):
> "Entities created successfully:
>
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index 908fc5645..ced16c251 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -6,6 +6,13 @@ description: >-
and reference docs for code-generation rules. Writes one .tsx file per invocation.
Called by the genpage skill in parallel — not invoked directly by users.
color: green
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# search and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate` are NOT aliases anywhere — `todo` is
+# the portable name. No `execute`/`Bash`: this agent only authors page source.
+# See references/agent-interaction-contract.md.
tools:
- Read
- Write
@@ -13,6 +20,10 @@ tools:
- Grep
- TaskCreate
- TaskUpdate
+ - read
+ - edit
+ - search
+ - todo
---
# Genpage Page Builder
@@ -34,10 +45,17 @@ You will be invoked with a prompt that includes:
`mock + connectors` — a **connector-only page is `mock` data mode with connector
bindings**.
- **RuntimeTypes path** — absolute path to `RuntimeTypes.ts` (present only when Data mode is `dataverse`)
-- **Connectors** — `enabled` or `disabled`, the orchestrator's feature-flag probe taken
- immediately before code generation. **`disabled` overrides the plan**: treat the page as
- having no connector bindings no matter what `## Connector Bindings` says. A missing line
- means `disabled` (fail closed).
+- **Connectors** — `none` or `<n> binding(s)`, derived by the orchestrator from the plan's
+ `## Connector Bindings` table immediately before code generation. **`none` overrides the plan
+ body**: treat the page as having no connector bindings no matter what the section text says. A
+ missing line means `none` (fail closed) — emitting a call to a binding that was never created
+ produces a page that fails at runtime, whereas omitting one produces a page that merely lacks
+ the feature.
+- **Telemetry** — `enabled` or `disabled`, the orchestrator's Phase 4.7 `custom-telemetry` probe
+ result. A missing line means `disabled` (fail closed), which is why the `/app-builder` dispatch
+ can state it as a constant. `enabled` is **permission, not instruction**: it only makes
+ instrumentation possible — you still emit `props.appInsights` calls solely when the maker's own
+ request asks to measure, track, monitor or diagnose something.
- **Working directory** — where to write the `.tsx` file
- **Plugin root** — `${PLUGIN_ROOT}` for reading references and samples
@@ -117,6 +135,16 @@ This pattern saves ~26K tokens per page-builder run vs. loading the full list,
while keeping the same correctness guarantee: nothing ships unless every icon
import has been Grep-validated against the verified list.
+## Step 2.6 — Runtime-only Griffel validation
+
+`pac model genpage transpile` type-checks the page but does not execute
+`makeStyles`; unsupported Griffel shorthands can therefore compile and then log
+runtime errors in the browser. Before returning, Grep the generated `.tsx` with
+the regex `['"]?borderWidth['"]?\s*:` so unquoted, quoted, and spaced property
+syntax are all caught. Replace every match with the four explicit longhands:
+`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and
+`borderLeftWidth`. Do not return a file that still matches the regex.
+
## Step 3 — Read References and Samples
Read the code generation rules reference:
@@ -125,7 +153,7 @@ Read the code generation rules reference:
${PLUGIN_ROOT}/references/rules.md
```
-Only when your dispatch says **`Connectors: enabled`** *and* the plan's
+Only when your dispatch says **`Connectors: <n> binding(s)`** *and* the plan's
`## Connector Bindings` section contains an actual binding table (a
`| Logical Name | …` header with at least one data row) do you treat the page as
connector-backed and also read:
@@ -134,13 +162,12 @@ connector-backed and also read:
${PLUGIN_ROOT}/references/connectors.md
```
-If your dispatch says `Connectors: disabled` (or omits the line), or the
+If your dispatch says `Connectors: none` (or omits the line), or the
`## Connector Bindings` section is the literal `No connector bindings.`, is empty,
is missing entirely, or contains no binding row, the page has **no connectors** —
do not read connectors.md and do not emit any connector code. The dispatch wins
-over the plan: the orchestrator re-probes the connectors feature flag right before
-code generation, so a plan authored while the flag was ON must not produce connector
-calls that this run will never bind.
+over the plan: a page whose data source is Dataverse or mock has no bindings to
+call, so emitting connector code would produce a page that cannot bind at runtime.
Only when the plan's `## Custom API Bindings` section contains an actual binding table
(a `| Name | Kind | …` header with at least one data row) do you treat the page as
diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.md
index af3658733..e29df9387 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -3,20 +3,30 @@ name: genpage-planner
description: >-
Plans generative page creation for model-driven apps. Validates prerequisites,
authenticates with PAC CLI, gathers requirements, detects which Dataverse entities
- and model-driven apps exist, presents a plan for user approval via plan mode,
- and writes genpage-plan.md for downstream agents to consume.
+ and model-driven apps exist, and returns a proposed plan for the orchestrator to
+ present for approval. Writes genpage-plan.md, for downstream agents to consume,
+ once the orchestrator re-invokes it with the approval outcome.
Called by the genpage skill — not invoked directly by users.
color: cyan
+# Two naming schemes on purpose: Claude Code names first, then the portable
+# Copilot aliases for the same capabilities. Every host ignores tool names it
+# does not recognize, so declaring both is safe and keeps this agent's file,
+# shell and todo tools even on a host that does not implement the compatible-
+# alias table. `TaskCreate`/`TaskUpdate`/`TaskList` are NOT aliases anywhere —
+# `todo` is the portable name. `agent`/`Task` is deliberately ABSENT: this
+# planner returns a discovery request and the orchestrator dispatches.
+# See references/agent-interaction-contract.md.
tools:
- Read
- Write
- Bash
- - EnterPlanMode
- - ExitPlanMode
- TaskCreate
- TaskUpdate
- TaskList
- - AskUserQuestion
+ - read
+ - edit
+ - execute
+ - todo
---
# Genpage Planner
@@ -36,6 +46,29 @@ You will be invoked by the `/genpage` skill with a prompt that includes:
## Workflow-log requirements (applies to every step below)
+## Interaction contract — this agent is HEADLESS
+
+You run as a `Task` subagent, which has **no user on the other end**:
+`AskUserQuestion`, `EnterPlanMode` and `ExitPlanMode` cannot reach anyone from
+here, and are not in your tool list. Never claim a user answered something.
+
+When you need a decision, **stop and return a request** for the orchestrator to
+put to the user in the main conversation loop:
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>" } ],
+ "multiSelect": false } ] }
+```
+
+The orchestrator asks, records the exchange in `workflow-log.md`, and re-invokes
+you with the answers. Return everything you have already discovered alongside the
+request so the re-invocation does not repeat the reads.
+
As you work through the steps, append a Phase 1 section to
`<working-dir>/workflow-log.md` (create the file if it doesn't exist). The
section MUST record commands and structured calls verbatim — not just their
@@ -43,11 +76,20 @@ outcomes — because the eval harness greps the log for these tokens. Concretely
- Every shell command invocation is recorded on its own line as
`` `node --version` `` / `` `pac help` `` / `` `pac auth list` `` / `` `pac model list-tables --search '<term>'` ``. Include the literal flag values. Result goes on the next line.
-- Every `AskUserQuestion` call is recorded as
+- Every question **the orchestrator asks on your behalf** is recorded as
`AskUserQuestion: <question text> → <selected option>`. The literal string
- `AskUserQuestion` is required.
+ `AskUserQuestion` is required. You do not make that call — you return a
+ `needs_input` request and the orchestrator records the exchange — but the log
+ format is unchanged, because the log records what was ASKED, not who asked it.
- The plan-presentation call is recorded as `EnterPlanMode called` followed
- by the user's response (`approved` / `revised`).
+ by the user's response (`approved` / `revised`). The orchestrator presents the
+ plan; you supply its content.
+- **Unattended exception:** when the orchestrator says interaction mode is
+ unattended, never write the literal attended markers `AskUserQuestion:`,
+ `EnterPlanMode called`, or `ExitPlanMode called` — not even in explanatory
+ prose such as "was not called". Record only
+ `Unattended default: <question> → <answer> (<reason>)`. The evaluator treats
+ those attended markers as real invocations.
- The PAC CLI version output is recorded explicitly (the assertion checks
for `> 2.10.0`-shaped text — `PAC CLI Version 2.10.x` is the canonical
form).
@@ -86,28 +128,31 @@ Check PAC CLI authentication:
pac auth list
```
-**If no profiles:** Ask user to authenticate:
+**If no profiles:** authentication needs a browser sign-in, which only the main loop can
+walk the user through. Return a `needs_input` request naming the command:
```powershell
pac auth create --environment https://your-env.crm.dynamics.com
```
-Wait for user to complete browser sign-in, then re-verify.
+The orchestrator runs it, waits for sign-in, and re-invokes you to re-verify.
**If one profile:** Confirm it's active (has `*` marker). If not, activate it:
```powershell
pac auth select --index 1
```
-**If multiple profiles:** Show the list, ask which environment to use via
-`AskUserQuestion`, then:
+**If multiple profiles:** Return a `needs_input` request listing the profiles so
+the orchestrator can ask which environment to use; on re-invocation with the
+answer, select it:
```powershell
-pac auth select --index <user-chosen-index>
+pac auth select --index <chosen-index>
```
Report: "Working with environment: [name]" and proceed.
## Step 3 — Gather Requirements
-Ask these questions one at a time via `AskUserQuestion`:
+These questions are asked by the ORCHESTRATOR, one at a time. Return them as a
+`needs_input` request (or use the answers it passed you on re-invocation):
1. **"Create new page(s) or edit an existing one?"**
- If edit: return immediately with `{ "action": "edit" }` — the orchestrator
@@ -220,7 +265,11 @@ Two cases:
re-invoked after discovery, so your prompt carries a `## Connector Bindings`
block (or the sentinel `No connector bindings.`) and/or a `connectors.json`
path. Consume it as-is: copy the block verbatim into the plan's
- `## Connector Bindings` section. Never re-derive or edit it.
+ `## Connector Bindings` section. Never re-derive or edit it. If the prompt
+ wraps the block in `----- BEGIN/END CONNECTOR BINDINGS -----` lines, those are
+ prompt delimiters, not content: copy only what is between them. The section
+ body must be exactly `No connector bindings.` when there are none — a stray
+ delimiter line makes the plan fail schema validation.
2. **A connector need is present or surfaces during clarification** — do NOT
attempt discovery. Stop and return
@@ -234,7 +283,7 @@ Two cases:
environment or the wrong mode cannot be undone. Return this only after your
auth/environment steps have run, so both values are real.
-`genpage-connector-builder` remains the single owner of the connectors feature gate,
+`genpage-connector-builder` remains the single owner of the connectors rollback gate,
connection / connection-ref discovery, connection-reference creation, and the binding
contract. When no connectors are involved, write the exact sentinel
`No connector bindings.` into the plan.
@@ -251,25 +300,45 @@ Read `connector-bindings.md` and splice its contents verbatim into the
If the request implies **only** Dataverse and/or mock data (no connector source),
write `## Connector Bindings` as exactly `No connector bindings.`.
-### Custom API Detection (delegated to genpage-customapi-builder)
+### Custom API Detection (handled by the orchestrator, not by you)
If the request implies **server-side Dataverse logic** — approving/escalating a record,
running a calculation or validation, or any operation that maps to a Dataverse **Custom API**
-(Action or Function) rather than a plain row read/write — delegate ALL Custom API work to the
-`genpage-customapi-builder` agent via the `Task` tool. Do **not** run the feature-gate probe
-or any Custom API discovery inline — that agent is the single owner of the `custom-api`
-feature gate, Custom API discovery, and the binding contract.
+(Action or Function) rather than a plain row read/write — **do not dispatch any agent and do
+not run the feature-gate probe or any Custom API discovery inline.** You have no `Task` tool,
+and `genpage-customapi-builder` may need to ask the user which Custom API to bind — it cannot
+run headless inside a sub-agent. It is dispatched by the top-level `/genpage` orchestrator.
-Invoke `genpage-customapi-builder` with a prompt containing:
+Custom API discovery is **read-only** (a Web API query over the Custom API tables), so unlike
+connector discovery it carries no "wrong environment cannot be undone" hazard. It still runs
+AFTER you, though, so it queries the environment you resolved and binds to the page tables you
+detected. Your first invocation therefore always carries the sentinel `No custom API bindings.`.
+
+Two cases:
+
+1. **The orchestrator already forwarded Custom API results** — you are being re-invoked after
+ discovery, so your prompt carries a `## Custom API Bindings` block (or the sentinel
+ `No custom API bindings.`) and/or an `actions.json` path. Consume it as-is: copy the block
+ verbatim into the plan's `## Custom API Bindings` section. Never re-derive or edit it. If the
+ prompt wraps the block in `----- BEGIN/END CUSTOM API BINDINGS -----` lines, those are prompt
+ delimiters, not content: copy only what is between them. The section body must be exactly
+ `No custom API bindings.` when there are none — a stray delimiter line makes the plan fail
+ schema validation.
+2. **A Custom API need is present or surfaces during clarification** — do NOT attempt
+ discovery. Stop and return
+
+ ```json
+ { "action": "custom_api_discovery_required", "intent": "<the operation(s) implied>",
+ "resolvedAction": "create" | "edit", "envUrl": "<the environment you resolved>",
+ "pageTables": "<page table logical names, comma-separated, or none>" }
+ ```
-- **Mode:** `create`
-- **Working directory**, **Plugin root** (`${PLUGIN_ROOT}`), **Environment URL**
-- **Page tables:** the table logical name(s) the page is bound to (from `## Existing
- Entities` / `pageInput`), or "none"
-- **Intent:** the server-side operation(s) the request implies (e.g. "approve the order",
- "escalate the case", "compute an order summary")
+ `resolvedAction`, `envUrl`, and `pageTables` are **required**: the orchestrator dispatches
+ the builder against exactly those. Return this only after your auth/environment and entity
+ detection steps have run, so all three values are real.
-It writes two files into the working directory:
+`genpage-customapi-builder` remains the single owner of the `custom-api` feature gate, Custom
+API discovery, and the binding contract. When the orchestrator forwards results it provides:
- `custom-api-bindings.md` — the exact body for the plan's `## Custom API Bindings` section
(either `No custom API bindings.` or the binding table).
@@ -279,8 +348,7 @@ Read `custom-api-bindings.md` and splice its contents verbatim into the
`## Custom API Bindings` section of `genpage-plan.md`.
If the request implies **no** server-side Custom API operation (plain Dataverse CRUD and/or
-mock data only), skip the agent entirely and write `## Custom API Bindings` as exactly
-`No custom API bindings.`.
+mock data only), write `## Custom API Bindings` as exactly `No custom API bindings.`.
### App Detection
@@ -290,10 +358,11 @@ Run:
pac model list
```
-- **0 apps:** Ask user via `AskUserQuestion`: "No model-driven apps found. Would you
+- **0 apps:** Return a `needs_input` request: "No model-driven apps found. Would you
like to create a new one, or cancel?"
-- **1 app:** Confirm with user: "Found app [name] ([app-id]). Use this one?"
-- **N apps:** Ask user to select one or create a new one via `AskUserQuestion`.
+- **1 app:** Return a `needs_input` request to confirm: "Found app [name] ([app-id]). Use this one?"
+- **N apps:** Return a `needs_input` request listing the apps so the user can select
+ one or create a new one.
### Solution Selection
@@ -331,10 +400,11 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \
Parse the JSON; capture each `uniquename`, `friendlyname`, and
`publisherid.customizationprefix`.
-#### 3. Ask the user
+#### 3. Have the orchestrator ask
-Use `AskUserQuestion`. Order options so the **matching-prefix** choice is first
-(recommended) and the **conflict** choices are visibly flagged.
+Return the choice as a `needs_input` request. Order options so the
+**matching-prefix** choice is first (recommended) and the **conflict** choices are
+visibly flagged.
**Recommended-first ordering rule:**
@@ -389,13 +459,15 @@ the user before continuing:
> "Heads up — env has `<detectedPrefix>_*` tables but you chose `<chosenPrefix>`.
> New tables won't match the prefix of your existing work."
-## Step 5 — Present Plan for Approval
+## Step 5 — Hand the Plan Back for Approval
Create tasks via `TaskCreate`:
1. "Design page plan and data strategy"
2. "Write plan document (genpage-plan.md)"
-Enter plan mode (`EnterPlanMode`) and present:
+Return the plan below to the orchestrator, which presents it with
+`EnterPlanMode` and collects approval. Do not attempt to present it yourself —
+plan mode does not reach the user from a subagent.
```
## Genpage Plan
@@ -426,10 +498,11 @@ Enter plan mode (`EnterPlanMode`) and present:
- [styling preferences, features, accessibility notes from requirements]
```
-Then call `ExitPlanMode` to request user approval.
+The orchestrator calls `ExitPlanMode` to request user approval and tells you the
+outcome when it re-invokes you.
- If approved: proceed to Step 6.
-- If changes requested: revise the plan and re-enter plan mode.
+- If changes requested: revise the plan and return it for re-presentation.
Mark the "Design page plan" task complete after approval.
@@ -530,6 +603,7 @@ Plan document: [working directory]/genpage-plan.md
- **Do NOT create entities.** Entity creation is handled by `genpage-entity-builder`.
- **Do NOT deploy.** Deployment is handled by the orchestrating skill.
- **Do NOT generate RuntimeTypes.** The orchestrating skill handles this.
-- **One user interaction point:** The plan mode approval in Step 5 (plus requirements
- questions in Step 3 and app selection in Step 4).
+- **One user interaction point:** the plan approval in Step 5 (plus requirements
+ questions in Step 3 and app selection in Step 4). You never make those calls —
+ you return a request and the orchestrator asks.
- **If the user says "edit":** Return immediately. The orchestrator handles edits inline.
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index 990c7bb7c..f32883813 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -229,7 +229,7 @@ apart deliberately.
test here and by a `@jest-environment node` regression upstream.
### Edit flow (download → edit → rebuild) — ✅ verified live
-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec.
+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages, icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.
- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.
- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0, by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).
diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.json
index bba85b0b0..b02f3f463 100644
--- a/plugins/model-apps/feature-flags.json
+++ b/plugins/model-apps/feature-flags.json
@@ -1,6 +1,6 @@
{
- "_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD.",
- "connectors": false,
+ "_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD. connectors is GA and ships ON; its gate is kept for one release as a rollback switch and is scheduled for removal.",
+ "connectors": true,
"custom-api": false,
"custom-telemetry": false
}
diff --git a/plugins/model-apps/references/agent-interaction-contract.md b/plugins/model-apps/references/agent-interaction-contract.md
new file mode 100644
index 000000000..bcf9143e2
--- /dev/null
+++ b/plugins/model-apps/references/agent-interaction-contract.md
@@ -0,0 +1,109 @@
+# Agent interaction contract — agents are headless
+
+Every file under `agents/` is dispatched as a `Task` subagent, and a subagent has
+**no user on the other end**. `AskUserQuestion`, `EnterPlanMode` and
+`ExitPlanMode` do not reach anyone from inside one: the question is never
+answered and the approval is never given. An agent that declares or calls them is
+specifying a flow that cannot complete.
+
+This is not theoretical. `/genpage` Phase 1 was specified to run its entire
+interactive flow — prerequisites, auth, the "create new / edit existing" question
+and plan-mode approval — inside the `genpage-planner` subagent, while the same
+plugin's `AGENTS.md` documented that subagents are headless and `/app-builder`
+enforced the opposite rule. There was no compliant path through Phase 1, so
+create flows could not complete. It survived roughly two and a half months
+because nothing checked: agent frontmatter is prose to every test in the repo.
+`scripts/validate-agent-interactivity.js` now fails the build on a declaration.
+
+## The rule
+
+**Interaction belongs to the main conversation loop.** An agent that needs a
+decision returns a structured request; the orchestrator asks, records it, and
+re-invokes the agent with the answer.
+
+This applies to **every phase that dispatches an agent**, not just the first one.
+Each dispatch site is its own loop: a phase that waits for an agent and then
+proceeds on a `needs_input` return silently discards the decision, and the agent
+never runs the step that depended on it. The rule is easy to satisfy in the phase
+where interaction is obviously expected and easy to forget in the ones where the
+agent is "just doing work" — `/genpage` Phase 2b dispatched the entity-builder,
+which asks about sample data this way, and simply waited for it. Treat it as part
+of the dispatch, like passing the working directory.
+
+The same holds for plan approval: a headless agent cannot see an `ExitPlanMode`
+result, so an agent whose final step is gated on approval must be **re-invoked
+with the outcome**. Check for the artifact it was supposed to write before moving
+on; its absence is the only signal you get that the loop did not close.
+
+## The `needs_input` request
+
+```json
+{ "action": "needs_input",
+ "why": "<one line: what is blocked without this>",
+ "questions": [
+ { "id": "<stable-id>",
+ "question": "<the question, verbatim>",
+ "options": [ { "label": "<short>", "description": "<what it means>", "default": true } ],
+ "multiSelect": false } ] }
+```
+
+Return everything already discovered alongside the request, so the re-invocation
+does not repeat the reads it has already paid for.
+
+Mark at most one option per question `"default": true`. It is what an **unattended**
+run uses — Copilot autopilot and Claude auto-accept have no user to ask, so a
+question with no marked default halts the run rather than being answered by
+whoever guesses first. Mark a default only where proceeding without a human is
+genuinely safe: the field is how an agent says "this one is safe to assume", and
+omitting it is the correct answer for anything destructive or irreversible.
+
+## Tool names must be portable across hosts
+
+Tool names are **host-specific**, and every host silently **ignores** a name it
+does not recognize instead of reporting it. A capability named only in a scheme
+the running host does not know is therefore simply absent: the agent launches,
+then cannot run `node` or track progress, with nothing in any log saying why.
+
+Copilot publishes a compatible-alias table — `Bash`→`execute`, `Read`→`read`,
+`Write`/`Edit`→`edit`, `Grep`/`Glob`→`search`, case-insensitively — so those
+Claude Code names already carry across.
+`TaskCreate`, `TaskUpdate` and `TaskList` do **not**: they appear in no published
+alias table, so on a Copilot host they are dropped and the agent loses progress
+tracking. The portable name for that capability is `todo`.
+
+The rule is therefore: **declare every capability in both naming schemes.**
+Listing both is safe precisely because unrecognized names are ignored, and it
+removes the dependency on a given host implementing the alias table at all.
+
+```yaml
+tools:
+ - Read
+ - Write
+ - Bash
+ - TaskCreate
+ - TaskUpdate
+ - TaskList
+ - read
+ - edit
+ - execute
+ - todo
+```
+
+`scripts/validate-agent-interactivity.js` fails the build on a one-sided
+declaration, in either direction.
+
+References:
+[Copilot tool aliases](https://docs.github.com/en/copilot/reference/custom-agents-configuration#tool-aliases)
+· [Claude Code ignores unknown tool names](https://github.com/anthropics/claude-code/issues/93171)
+
+## Logging is unchanged
+
+The orchestrator records the exchange in `workflow-log.md` in the documented
+format — `AskUserQuestion: <question> → <answer>`, and `EnterPlanMode called`
+followed by the response. The log records what was **asked**, not which loop
+asked it, so the eval harness contract is unaffected by where the call is made.
+
+## What agents keep
+
+Read-only discovery, code generation, file writes, and shell work are all
+unchanged. Only the act of *prompting a human* moves to the parent.
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
new file mode 100644
index 000000000..1388b772e
--- /dev/null
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -0,0 +1,353 @@
+# App Spec — advanced / conditional fields
+
+The situational half of the App Spec contract. [`app-spec-schema.md`](./app-spec-schema.md) is
+the document to read first and covers everything an app always has — tables, columns,
+relationships, views, forms, the app shell, pages, personas, sample data and AI features.
+
+Everything here is **optional**: a spec that uses none of these fields is complete and valid.
+They were split out because that document is read in full at the start of every authoring run,
+and ~24% of it described features most apps never use.
+
+> **You still need to know these exist.** The capability list in the `/app-builder` skill body
+> and the pointer table in `app-spec-schema.md` both name every field below, with guidance on
+> when to reach for it. Read this file once your design calls for one of them — not before, and
+> not never.
+## globalChoices[] (optional — shared option sets)
+```jsonc
+[ { "name": "new_priority", "displayName": "Priority", "options": ["Low","Medium","High"] } ]
+```
+Reference from a column via `"globalChoice": "new_priority"` (built before the columns that bind it).
+
+## webResources[] (optional — client-side logic)
+
+```jsonc
+[ { "name": "new_ticket.js", "displayName": "Ticket Scripts", "type": "js",
+ "content": "var Ticket={onLoad:function(ctx){},onPriority:function(ctx){}};" } ]
+```
+- `type`: `js · html · css · xml · png · jpg · gif · svg · ico · xsl · resx` (script web resources
+ should be named with a `.js` extension).
+- Source comes from **one** of: `content` (inline text), `contentPath` (a file read relative to the
+ app folder at build time), or `contentBase64` (for binary types).
+- Built **before** forms and added to the solution; reference one from a form `events[]` handler.
+- **Content edits are NOT applied on rebuild.** Like commands, the phase is discover-then-skip: a web
+ resource that already exists is reused as-is, so changing `content` and rebuilding deploys nothing
+ and the old script keeps running. Delete the web resource (or tear down) and rebuild to change it —
+ note it cannot be deleted while a command or form handler still references it.
+- **Never hardcode Choice (option-set) values in the script.** Values like `100000003` are assigned
+ per publisher, so a literal that is correct in one environment silently selects nothing in another —
+ and a `setValue` with an unknown value fails quietly. Resolve by label instead:
+ ```js
+ function setChoiceByLabel(formCtx, attr, label) {
+ var a = formCtx.getAttribute(attr);
+ var hit = (a.getOptions() || []).filter(function (o) { return o.text === label; })[0];
+ if (hit) { a.setValue(hit.value); }
+ return !!hit;
+ }
+ ```
+- **`external`** *(optional, download-emitted)* — set `true` on an entry that **download** re-declared
+ because a sitemap nav icon referenced a custom image web resource **by path** (see appShell icons
+ below). The build **creates it if missing, reuses it if present** (idempotent, no overwrite), so the
+ icon resolves after a rebuild into a **fresh** environment. Teardown **never deletes** an `external`
+ web resource: a publisher-owned WR can be shared across that publisher's other apps/solutions, and an
+ orphaned icon is recoverable while a deleted shared resource is not — so this fails safe (mirrors
+ `existing: true` on downloaded tables). You normally never hand-author this flag.
+
+## commands[] (optional — modern command-bar buttons)
+```jsonc
+{ "entity": "new_order", "label": "Escalate", "location": "MainTab",
+ "library": "new_order.js", "function": "Order.escalate", // on-click JS (web resource + fn)
+ "disabled": false, "hidden": false } // optional static visibility
+
+// flyout (drop-down) menu: a container button whose children are the menu items
+{ "entity": "new_order", "label": "More", "type": "FlyoutAnchor", "children": [
+ { "label": "Approve", "library": "new_order.js", "function": "Order.approve" },
+ { "label": "Reject", "library": "new_order.js", "function": "Order.reject" } ] }
+```
+- A button's on-click calls `function` in the declared `library` web resource (both lint-enforced) —
+ this is what makes it **functional** (not a structural-only button).
+- **Your function is handed the record automatically.** The build passes the standard command
+ parameters for the button's location, so the usual handler shape works as written:
+ ```js
+ function escalate(primaryControl) {
+ primaryControl.getAttribute('new_priority').setValue(100000003);
+ primaryControl.data.save();
+ }
+ ```
+ Defaults by location — `MainTab` → `PrimaryControl`; `ContextualTab` → `SelectedControl`;
+ `HomeTab` → `SelectedControl` + `SelectedControlSelectedItemIds`. Override with `parameters`
+ (a raw JSON string, e.g. `'[{"type":5,"value":null}]'`); pass `""` for a function that genuinely
+ takes no arguments. **Without a parameter the function is invoked with no arguments**, so
+ `primaryControl` is `undefined` and the button appears to do nothing — the error is visible only
+ in the browser console, and the build, the deployed rows and `--verify` all still look correct.
+- **Button edits are not applied on rebuild.** The command phase is discover-then-skip: it creates a
+ bar only when none exists. To change a deployed button, delete the entity's commands (or tear down)
+ and rebuild.
+- **`location`** is `MainTab` (default — the entity form/grid command bar), `HomeTab`, or `ContextualTab`.
+- **`hidden`** / **`disabled`** set *static* visibility/enablement. **Conditional (rule-based)
+ visibility is not supported** — it's Power Fx-only on modern commands and needs a component library
+ that can't be authored headlessly.
+- **`type`** is `Button` (default), `FlyoutAnchor`, or `SplitButton`. A flyout/split container holds
+ `children[]` (each a button with its own `library`+`function`) instead of an on-click of its own —
+ the menu items live under it. Top-level buttons emit as **loose controls**; a *titled* group is not
+ supported (it needs a parent command-bar row the SDK doesn't synthesize from scratch). The command
+ lands in the Default solution but is entity-scoped, so it shows on the entity's command bar.
+
+## businessRules[] (optional — declarative form logic, no code)
+
+```jsonc
+{ "entity": "new_ticket", "name": "Hide notes on closed tickets",
+ "description": "Closed tickets are read-only history, so the working fields are hidden.",
+ "scope": "Entity", // only Entity today
+ "status": "Active", // Active (default) | Draft — a Draft rule is deployed but inert
+ "conditions": [ // ALL must hold (ANDed); more than one is allowed
+ { "field": "new_status", "operator": "Equals", "value": "100000001", "dataType": "Picklist" }
+ ], "actions": [
+ { "type": "SetVisibility", "field": "new_notes", "visible": false },
+ { "type": "LockUnlock", "field": "new_owner", "lock": true },
+ { "type": "SetBusinessRequired", "field": "new_reason", "required": true },
+ { "type": "SetFieldValue", "field": "new_owner", "value": "unassigned" }
+ ] }
+```
+
+- **Environment gate — read this first.** The SDK writes a rule through the bound
+ `CreateProcessWithWfomJson` member, the same one the modern business-rule designer uses, and has
+ **no fallback**. An environment that does not declare that member cannot host business rules at
+ all, and that is the common case rather than an edge case. The build then
+ **skips** `businessRules[]`, warns once naming the member, and builds everything else normally —
+ so you get a working app without the rules, not a half-built one. `--verify` will report those
+ rules as not deployed, which is the truth.
+- **Operators**, all of which the SDK's own table defines:
+ `Equals` · `DoesNotEqual` · `IsGreaterThan` · `IsGreaterThanEqualTo` · `IsLessThan` ·
+ `IsLessThanEqualTo` · `Contains` · `DoesNotContain` · `BeginsWith` · `DoesNotBeginWith` ·
+ `EndsWith` · `DoesNotEndWith` · `On` · `NotOn` (all carry a `value`), plus the presence operators
+ `ContainsData` · `DoesNotContainData`, which must **not** carry one.
+ Mind the spelling: it is `IsGreaterThan`, **not** `GreaterThan`. The SDK resolves an operator it
+ does not recognise to **Equals** rather than rejecting it, so a misspelling would deploy, activate,
+ and quietly test equality. The spec rejects anything outside the table for exactly that reason, and
+ suggests the correct spelling when it can.
+- **Actions**: `SetVisibility` (`visible`) · `LockUnlock` (`lock`) · `SetBusinessRequired`
+ (`required`) · `SetFieldValue` (`value`). The three boolean payloads must be **real booleans** — a
+ string `"false"` is truthy and would invert the intent, so it is rejected.
+ The SDK also models `SetDefaultValue`, `ShowErrorMessage` and `Recommendation`. They are not
+ exposed yet: each needs mapping that cannot be exercised end to end on an environment without the
+ bound member, and shipping unverified mapping is how a rule deploys and does the wrong thing.
+- **`conditions[]` are ANDed**, and there may be **more than one** — they are folded with the
+ platform's `LogicalAnd`. (An earlier single-condition limit came from a client-side XAML compiler
+ that has since been deleted upstream; it was never a platform limit.) `OR` is not exposed.
+- **`dataType`** (optional) — accepted values are `String` · `Memo` · `Picklist` · `State` ·
+ `Status` · `Boolean` · `Integer` · `Double` · `Decimal` · `Money`.
+ **It currently has no effect.** Measured across every accepted value, on both the condition and the
+ action path, the SDK types every literal as `String` and never consults this field. It is still
+ validated as a closed set so a typo is caught and so the surface stays forward-compatible, but do
+ not expect it to change the deployed rule. For a Choice column, give the option's **integer
+ value**, not its label — that part matters regardless.
+- Every `field` must be a column on the rule's own `entity` (its own columns, its primary name, or a
+ lookup a relationship creates). A rule naming a column that does not exist is accepted by the
+ platform and then simply **never fires**, so this is validated up front.
+- **A rule is validated against the designer's own completeness rules before it is written.** The
+ push cannot tell you a rule is wrong — a condition tree in an unexpected shape is ignored by the
+ serializer and written as a rule with no clauses and no actions, which returns 204, activates, and
+ never fires. The build runs the same validator the business-rule designer gates its Save button on
+ and **halts** with its findings. Nothing this schema allows is rejected by it; if you hit it, the
+ rule genuinely would not have worked.
+- **Rebuild behaviour is additive** — a rule is matched by `(entity, name)` and reused if present;
+ edits are **not** re-applied. Recreate the rule to change it.
+
+## businessProcessFlows[] (optional — guided, staged process on a table)
+
+A BPF is the stage bar across the top of a record: an ordered set of stages, each with steps the user
+works through.
+
+```jsonc
+{ "entity": "new_ticket", "name": "Ticket Handling",
+ "description": "How support tickets move to resolution", // optional
+ "status": "Active", // Active (default) | Draft — a Draft flow is deployed but does NOT
+ // appear on the form
+ "order": 1, // optional; the workflow's processorder when several flows apply
+ "stages": [
+ { "name": "Triage", "steps": [
+ { "name": "Subject", "field": "new_subject", "required": true },
+ { "name": "Priority", "field": "new_priority" } ] },
+ { "name": "Resolve", "steps": [
+ { "name": "Resolution notes", "field": "new_notes" },
+ { "name": "Confirmed with customer", "field": "new_confirmed" } ] }
+ ] }
+```
+
+- **Stages are ordered** (array order) and each needs a unique `name` **and at least one step**; steps
+ within a stage need unique names too. `stages[]` is required — a flow with no stage is not a
+ process. A stage with no steps is rejected because the SDK substitutes a placeholder step literally
+ named *"New Step"*, which would then appear on the stage bar without ever having been authored.
+- **A flow's `name` must be unique across the whole spec, not just per table.** The unique name
+ Dataverse stores is derived as `new_<name lower-cased, non-alphanumerics stripped>` — it **ignores
+ the table**, and the `new_` prefix is fixed regardless of your `publisherPrefix` — and activation
+ creates a backing table with that name, so `"Ticket Handling"` on two
+ different tables (or `"Ticket Handling"` and `"ticket-handling"` on one) cannot both deploy.
+ Validation rejects the collision and names the derived value; rename one, e.g.
+ `"Ticket Handling (Cases)"`.
+- **The derived name is a TABLE name, so it also collides with your tables.** A flow named
+ `"Ticket"` derives `new_ticket`; if the spec declares a table `new_ticket`, the flow cannot
+ deploy — and because the prefix is always `new_`, this is easy to hit on a spec using the default
+ `new` publisher prefix. Validation rejects that too, naming both. A collision the spec cannot see
+ (a rename between builds that preserves the derived name, or a flow — or a table — already in the
+ environment) is caught at build time by a probe that checks both `workflows` and table metadata,
+ and **halts** naming whichever owns the name rather than letting the create fail with a platform
+ error about a table you never mentioned. The probe is best-effort — if it cannot run, the build
+ proceeds.
+- **Every step must bind a `field`**, and it must be a column on the flow's own `entity` (its own
+ columns, its primary name, or a lookup a relationship creates). The platform rejects a step with no
+ column outright — `datafieldname of ControlStep cannot be null or empty` — so there is no such
+ thing as a field-less "checklist" step; for a manual check-off, bind a Boolean column such as a
+ `Confirmed` flag. Like a business rule, the platform *accepts* a step bound to a column that does
+ not exist and simply renders it bound to nothing, so the column is validated up front too.
+- **At most 30 stages per flow and 30 steps per stage** — ceilings the SDK enforces, checked here so
+ an over-large flow is a spec error rather than a failure in a late build phase.
+- **`status`** matters more than it does for a rule: an inactive BPF is not merely inert, it is
+ **invisible** — the stage bar does not render at all. `Active` is the default for that reason.
+- **v1 is single-entity and linear.** Every stage must be on the flow's own `entity`. The SDK also
+ models cross-entity stages, branching, stage actions and security-role grants; keys carrying them
+ are **rejected** at flow, stage **and** step level (the allowed keys are `name`/`entity`/
+ `description`/`status`/`order`/`stages`; per stage `name`/`entity`/`steps`; per step
+ `name`/`field`/`required`). The rejection is an allow-list rather than a list of known-bad names
+ because the SDK's own normalizers silently discard any key they do not copy — so an unguarded
+ `branch` on a stage, or `fieldLogicalName` instead of `field` on a step, would validate clean and
+ deploy as though it had never been written. Configure those in Maker after the flow deploys.
+- **Activation creates a backing table** (an org-owned table named after the flow's unique name)
+ that the platform manages. Teardown deactivates and deletes the flow, which removes it.
+- **Rebuild behaviour is additive**, exactly like business rules — a flow is matched by
+ `(entity, name)` and reused if present; only its Active/Draft **state** is converged. Stage and
+ step edits are **not** re-applied: recreate the flow to change its structure.
+- Verified by `--verify` on three axes: it exists, there is exactly **one** of it (duplicates would
+ offer users the same process twice), and its deployed state matches `status`.
+
+## dashboards[] (optional — chart/list/iframe/web-resource tiles)
+```jsonc
+{ "name": "Operations", "description": "Daily queue health for the support lead.", "tiles": [
+ { "type": "chart", "chart": "Orders by Status", "view": "Active Orders" }, // chart needs both
+ { "type": "list", "view": "Active Orders", "name": "Recent" }, // list needs a view
+ { "type": "iframe", "url": "https://…", "name": "Map" },
+ { "type": "webresource", "webResource": "new_widget.html", "name": "Widget" } ] }
+```
+- A **chart** tile needs both a declared `chart` (the visualization) **and** a declared `view` (its
+ data); a **list** tile needs a declared `view`. The target entity is derived from the view. `name`
+ defaults to the chart/view name; `colspan`/`rowspan` optional (default 1×4).
+- Built after views/charts (it references their ids). The dashboard is **global** (not entity-scoped)
+ and added to the solution. To surface it in the app nav, add a `dashboard` sitemap subarea (below) —
+ that also auto-pins it as an app component.
+
+## roleGrants[] (optional — extend a role you did NOT author)
+
+Adds privileges for a table to a security role that **already exists** — typically the roles an
+existing solution ships. Use it when you add a table to an app whose access model somebody else owns:
+without it the table, its forms and its navigation deploy while every non-admin persona still cannot
+open the table, and nothing reports it.
+
+```jsonc
+"roleGrants": [
+ {
+ // Name the EXISTING role. Either `role` (display name) or `roleId` (GUID) — never both.
+ "role": "Contoso PM - Project Manager",
+ "businessUnitId": "…", // optional; scopes the NAME lookup (defaults to the org root BU)
+ "privileges": [
+ { "entity": "contoso_projectbaseline",
+ "access": ["create", "read", "write", "delete", "append", "appendTo", "assign", "share"],
+ "scope": "organization" }
+ ]
+ },
+ { "role": "Contoso PM - Viewer",
+ "privileges": [ { "entity": "contoso_projectbaseline", "access": ["read"], "scope": "organization" } ] }
+]
+```
+
+**How it differs from `personas[]` — and why both exist.** A persona role is **converged**: the build
+applies it with `ReplacePrivilegesRole`, so every privilege not in the spec is **removed**. That is
+right for a role the spec created and catastrophic for one it did not — pointing a persona at an
+existing role to add one table would silently strip everything else that role held. A `roleGrant`
+compiles to `AddPrivilegesRole` instead, which is purely **additive**: it re-asserts what you declare
+and leaves everything else alone.
+
+| | `personas[]` | `roleGrants[]` |
+|---|---|---|
+| Owns the role | yes (creates it, SDK-marked) | no — the role already exists |
+| Semantics | converges (replace) | adds only |
+| Can revoke | yes, by dropping the privilege | **no** — see below |
+| Managed role | refused (fail-closed conflict) | allowed |
+| Teardown | deletes the role | does nothing |
+
+**A grant is one-way.** Dropping an entry from `roleGrants[]` does **not** revoke the privilege, and
+`teardown` never removes one. `AddPrivilegesRole` does not record who added what, so a revoke could not
+tell a privilege this spec granted from one the role already held (or one a second spec granted) —
+stripping the latter is exactly the outcome this surface exists to avoid. **Revoke in Maker.**
+
+**Field reference**
+- `role` **or** `roleId` (**required**, exactly one) — the existing role's display name, or its GUID. Setting both is rejected: they can disagree and only one can be honoured.
+- `businessUnitId` (optional GUID) — scopes a lookup by `role` name. Rejected alongside `roleId`, where nothing would consult it.
+- `privileges[]` (**required**, ≥1) — identical shape to a persona's: `{ entity, access[], scope? }`. `scope` reaches Dataverse intact as the privilege `Depth`.
+- `description` (optional) — a note for readers of the spec; never written to Dataverse.
+
+**Resolution fails closed.** Granting on the wrong role is a silent access-control defect no later
+phase would catch, so every ambiguity is a **build halt**, never a skip: a name that matches no role,
+a name that matches more than one role in the business unit, a stale pinned `roleId`, or a business
+unit that cannot be resolved (a name-only fallback could grant on a same-named role in a *different*
+business unit). Unlike the persona path this does **not** require the SDK ownership marker, and a
+`ismanaged` role is allowed — extending a solution's shipped roles is the point.
+
+**Validation rules** (`validateAppSpec`): exactly one of `role` / `roleId`; GUID shapes; a non-empty
+`privileges[]` with valid `access` / `scope` tokens; **one entry per role** (two entries could request
+conflicting depths for a shared Dataverse privilege — the SDK only detects that *within* one call, so
+a split would let both writes through and the later would silently win); and a role that is **also a
+persona in this spec** is rejected, because the persona pass would converge the grant away on the next
+build. The apply-time metadata guards (a table that exposes no such access; two tables sharing one
+`prv*` at different depths) surface as a build halt with the SDK's own message.
+
+**Verification.** `verify-model-app` proves the role exists (`role-grant`) and — when the reader
+supplies privilege access — that it actually **holds** every granted privilege at at least the declared
+depth (`role-grant-privileges`). This matters more here than for a persona: a persona role's existence
+implies its content (it was converged), whereas a grant is additive onto a role that existed before and
+still exists whether or not the privileges landed. Subset semantics again — the role's other privileges
+belong to somebody else and are never a finding.
+
+## businessProcessFlows[].securityRoles — who may run a flow
+
+Same shape and same persona idiom as `forms[].securityRoles`, so there is one thing to learn:
+
+```jsonc
+{ "name": "Ticket Handling", "entity": "contoso_ticket", "status": "Active",
+ "securityRoles": { "personas": ["Dispatcher"] },
+ "stages": [ /* … */ ] }
+```
+
+The **mechanic** is different, though, and it explains every rule below. A form's roles live inside
+its formxml. A flow's live on a **table**: activating a flow makes the platform create an
+organization-owned backing table, and holding privileges on that table is what lets a persona run the
+process. Three things measured live before this surface was designed:
+
+- the backing table's logical name is the flow's **deployed `uniquename`**, which the build **reads
+ back** rather than deriving. For a flow this build creates the derivation is correct by
+ construction, but a flow authored in Maker — or one renamed after creation — keeps a unique name
+ unrelated to its display name, and granting on the derivation would target a table that does not
+ exist, or an unrelated one that happens to hold that name. The plan can still *name* the derived
+ table before the flow exists; the grant uses the value read at build time;
+- the table is organization-owned and **every privilege is Global-only** — so there is **no `scope`**
+ to author, because the platform accepts no other depth;
+- the access granted is fixed at `create`, `read`, `write`, `delete` — a partial set produces a flow a
+ user can see but not advance.
+
+**Rejected rather than ignored**
+- `everyone`, `fallbackForm`, `order` — formxml concepts with no equivalent here. The error says so
+ rather than just listing allowed keys, because an author who wrote them learned them from `forms[]`.
+- an **empty** `personas[]` — unlike a form (offered to everyone until restricted), a flow's backing
+ table grants to nobody by default, so an empty list is a request that cannot be satisfied.
+- `securityRoles` on a **Draft** flow — the backing table is created by *activation*, so there is
+ nothing to grant on yet.
+
+Applied in the **security** phase, after `personas[]` roles exist. If the flow was not built in the
+same invocation the grant is **skipped with a stated reason**, never applied blind.
+`verify-model-app` proves each persona holds the privileges on the backing table (`bpf-roles`) and
+fails closed when that table cannot be read — which also catches a flow that never activated.
+Teardown plans nothing: measured, the flow (and with it the backing table and its privileges) is
+deleted before the roles, and the run completes with 0 failures.
+
+
+**Not yet supported** (tracked follow-up): column-level (field) security and access teams / hierarchy
+security.
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index 22b376455..c508ba746 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -429,11 +429,27 @@ without needing a business rule or a plug-in to enforce it.
"alternateKeys": [ { "schemaName": "new_emailkey", "displayName": "Email Key", "columns": ["new_email"] } ]
```
-## globalChoices[] (optional — shared option sets)
-```jsonc
-[ { "name": "new_priority", "displayName": "Priority", "options": ["Low","Medium","High"] } ]
-```
-Reference from a column via `"globalChoice": "new_priority"` (built before the columns that bind it).
+## Conditional features — read `app-spec-schema-advanced.md` when you use one
+
+These fields are **optional and situational**: most apps use none of them, so their full field
+reference lives in [`app-spec-schema-advanced.md`](./app-spec-schema-advanced.md) rather than
+here. This document stays the contract for everything an app always has.
+
+**Read the advanced reference when — and only when — your design uses one of these.** The table
+is deliberately here, in the document you always read, so the menu is never hidden: choosing a
+capability is the step that must not be missed, and the `/app-builder` skill body carries the same
+list with "reach for it when…" guidance.
+
+| Field | What it is |
+|---|---|
+| `globalChoices[]` | shared option sets |
+| `webResources[]` | client-side logic |
+| `commands[]` | modern command-bar buttons |
+| `businessRules[]` | declarative form logic, no code |
+| `businessProcessFlows[]` | guided, staged process on a table |
+| `dashboards[]` | chart/list/iframe/web-resource tiles |
+| `roleGrants[]` | extend a role you did NOT author |
+| `businessProcessFlows[].securityRoles` | who may run a flow |
## relationships[]
```jsonc
@@ -442,7 +458,9 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c
```
- `referenced` = the "one" (parent); `referencing` = the "many" (child, gets the lookup column).
- The relationship's schema name defaults to `<referenced>_<referencing>` and **must differ**
- from `lookup.schemaName` (Dataverse rejects a collision — the lint enforces this).
+ from `lookup.schemaName` (Dataverse rejects a collision — `lintAppSpec` flags this, so
+`scripts/lint-app-spec.js` catches it before you deploy; note the build itself does **not**
+run the lint, so an unlinted spec hits the failure at build time instead).
- **Relationships to a standard/system table** (e.g. `systemuser`, `account` — a common
"bridge to a real user / owner" pattern) are handled automatically: because a system table has
no publisher prefix, the naive default name wouldn't start with your prefix and Dataverse would
@@ -462,40 +480,6 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c
the junction. Sample rows then bind **both** parents via `$parents` (see sampleData). This is the
recommended pattern for "Technician ↔ Work Order with a Role".
-## webResources[] (optional — client-side logic)
-
-```jsonc
-[ { "name": "new_ticket.js", "displayName": "Ticket Scripts", "type": "js",
- "content": "var Ticket={onLoad:function(ctx){},onPriority:function(ctx){}};" } ]
-```
-- `type`: `js · html · css · xml · png · jpg · gif · svg · ico · xsl · resx` (script web resources
- should be named with a `.js` extension).
-- Source comes from **one** of: `content` (inline text), `contentPath` (a file read relative to the
- app folder at build time), or `contentBase64` (for binary types).
-- Built **before** forms and added to the solution; reference one from a form `events[]` handler.
-- **Content edits are NOT applied on rebuild.** Like commands, the phase is discover-then-skip: a web
- resource that already exists is reused as-is, so changing `content` and rebuilding deploys nothing
- and the old script keeps running. Delete the web resource (or tear down) and rebuild to change it —
- note it cannot be deleted while a command or form handler still references it.
-- **Never hardcode Choice (option-set) values in the script.** Values like `100000003` are assigned
- per publisher, so a literal that is correct in one environment silently selects nothing in another —
- and a `setValue` with an unknown value fails quietly. Resolve by label instead:
- ```js
- function setChoiceByLabel(formCtx, attr, label) {
- var a = formCtx.getAttribute(attr);
- var hit = (a.getOptions() || []).filter(function (o) { return o.text === label; })[0];
- if (hit) { a.setValue(hit.value); }
- return !!hit;
- }
- ```
-- **`external`** *(optional, download-emitted)* — set `true` on an entry that **download** re-declared
- because a sitemap nav icon referenced a custom image web resource **by path** (see appShell icons
- below). The build **creates it if missing, reuses it if present** (idempotent, no overwrite), so the
- icon resolves after a rebuild into a **fresh** environment. Teardown **never deletes** an `external`
- web resource: a publisher-owned WR can be shared across that publisher's other apps/solutions, and an
- orphaned icon is recoverable while a deleted shared resource is not — so this fails safe (mirrors
- `existing: true` on downloaded tables). You normally never hand-author this flag.
-
## views[]
```jsonc
{ "entity": "new_ticket", "name": "Active Tickets", "columns": ["new_subject","new_priority"],
@@ -704,189 +688,6 @@ columns** — the column is still created and still readable/writable through th
placed. An explicit layout still honours a BigInt you list by name (you may be pairing it with a
custom control), but the spec validator emits a warning.
-## commands[] (optional — modern command-bar buttons)
-```jsonc
-{ "entity": "new_order", "label": "Escalate", "location": "MainTab",
- "library": "new_order.js", "function": "Order.escalate", // on-click JS (web resource + fn)
- "disabled": false, "hidden": false } // optional static visibility
-
-// flyout (drop-down) menu: a container button whose children are the menu items
-{ "entity": "new_order", "label": "More", "type": "FlyoutAnchor", "children": [
- { "label": "Approve", "library": "new_order.js", "function": "Order.approve" },
- { "label": "Reject", "library": "new_order.js", "function": "Order.reject" } ] }
-```
-- A button's on-click calls `function` in the declared `library` web resource (both lint-enforced) —
- this is what makes it **functional** (not a structural-only button).
-- **Your function is handed the record automatically.** The build passes the standard command
- parameters for the button's location, so the usual handler shape works as written:
- ```js
- function escalate(primaryControl) {
- primaryControl.getAttribute('new_priority').setValue(100000003);
- primaryControl.data.save();
- }
- ```
- Defaults by location — `MainTab` → `PrimaryControl`; `ContextualTab` → `SelectedControl`;
- `HomeTab` → `SelectedControl` + `SelectedControlSelectedItemIds`. Override with `parameters`
- (a raw JSON string, e.g. `'[{"type":5,"value":null}]'`); pass `""` for a function that genuinely
- takes no arguments. **Without a parameter the function is invoked with no arguments**, so
- `primaryControl` is `undefined` and the button appears to do nothing — the error is visible only
- in the browser console, and the build, the deployed rows and `--verify` all still look correct.
-- **Button edits are not applied on rebuild.** The command phase is discover-then-skip: it creates a
- bar only when none exists. To change a deployed button, delete the entity's commands (or tear down)
- and rebuild.
-- **`location`** is `MainTab` (default — the entity form/grid command bar), `HomeTab`, or `ContextualTab`.
-- **`hidden`** / **`disabled`** set *static* visibility/enablement. **Conditional (rule-based)
- visibility is not supported** — it's Power Fx-only on modern commands and needs a component library
- that can't be authored headlessly.
-- **`type`** is `Button` (default), `FlyoutAnchor`, or `SplitButton`. A flyout/split container holds
- `children[]` (each a button with its own `library`+`function`) instead of an on-click of its own —
- the menu items live under it. Top-level buttons emit as **loose controls**; a *titled* group is not
- supported (it needs a parent command-bar row the SDK doesn't synthesize from scratch). The command
- lands in the Default solution but is entity-scoped, so it shows on the entity's command bar.
-
-## businessRules[] (optional — declarative form logic, no code)
-
-```jsonc
-{ "entity": "new_ticket", "name": "Hide notes on closed tickets",
- "description": "Closed tickets are read-only history, so the working fields are hidden.",
- "scope": "Entity", // only Entity today
- "status": "Active", // Active (default) | Draft — a Draft rule is deployed but inert
- "conditions": [ // ALL must hold (ANDed); more than one is allowed
- { "field": "new_status", "operator": "Equals", "value": "100000001", "dataType": "Picklist" }
- ], "actions": [
- { "type": "SetVisibility", "field": "new_notes", "visible": false },
- { "type": "LockUnlock", "field": "new_owner", "lock": true },
- { "type": "SetBusinessRequired", "field": "new_reason", "required": true },
- { "type": "SetFieldValue", "field": "new_owner", "value": "unassigned" }
- ] }
-```
-
-- **Environment gate — read this first.** The SDK writes a rule through the bound
- `CreateProcessWithWfomJson` member, the same one the modern business-rule designer uses, and has
- **no fallback**. An environment that does not declare that member cannot host business rules at
- all, and that is the common case rather than an edge case. The build then
- **skips** `businessRules[]`, warns once naming the member, and builds everything else normally —
- so you get a working app without the rules, not a half-built one. `--verify` will report those
- rules as not deployed, which is the truth.
-- **Operators**, all of which the SDK's own table defines:
- `Equals` · `DoesNotEqual` · `IsGreaterThan` · `IsGreaterThanEqualTo` · `IsLessThan` ·
- `IsLessThanEqualTo` · `Contains` · `DoesNotContain` · `BeginsWith` · `DoesNotBeginWith` ·
- `EndsWith` · `DoesNotEndWith` · `On` · `NotOn` (all carry a `value`), plus the presence operators
- `ContainsData` · `DoesNotContainData`, which must **not** carry one.
- Mind the spelling: it is `IsGreaterThan`, **not** `GreaterThan`. The SDK resolves an operator it
- does not recognise to **Equals** rather than rejecting it, so a misspelling would deploy, activate,
- and quietly test equality. The spec rejects anything outside the table for exactly that reason, and
- suggests the correct spelling when it can.
-- **Actions**: `SetVisibility` (`visible`) · `LockUnlock` (`lock`) · `SetBusinessRequired`
- (`required`) · `SetFieldValue` (`value`). The three boolean payloads must be **real booleans** — a
- string `"false"` is truthy and would invert the intent, so it is rejected.
- The SDK also models `SetDefaultValue`, `ShowErrorMessage` and `Recommendation`. They are not
- exposed yet: each needs mapping that cannot be exercised end to end on an environment without the
- bound member, and shipping unverified mapping is how a rule deploys and does the wrong thing.
-- **`conditions[]` are ANDed**, and there may be **more than one** — they are folded with the
- platform's `LogicalAnd`. (An earlier single-condition limit came from a client-side XAML compiler
- that has since been deleted upstream; it was never a platform limit.) `OR` is not exposed.
-- **`dataType`** (optional) — accepted values are `String` · `Memo` · `Picklist` · `State` ·
- `Status` · `Boolean` · `Integer` · `Double` · `Decimal` · `Money`.
- **It currently has no effect.** Measured across every accepted value, on both the condition and the
- action path, the SDK types every literal as `String` and never consults this field. It is still
- validated as a closed set so a typo is caught and so the surface stays forward-compatible, but do
- not expect it to change the deployed rule. For a Choice column, give the option's **integer
- value**, not its label — that part matters regardless.
-- Every `field` must be a column on the rule's own `entity` (its own columns, its primary name, or a
- lookup a relationship creates). A rule naming a column that does not exist is accepted by the
- platform and then simply **never fires**, so this is validated up front.
-- **A rule is validated against the designer's own completeness rules before it is written.** The
- push cannot tell you a rule is wrong — a condition tree in an unexpected shape is ignored by the
- serializer and written as a rule with no clauses and no actions, which returns 204, activates, and
- never fires. The build runs the same validator the business-rule designer gates its Save button on
- and **halts** with its findings. Nothing this schema allows is rejected by it; if you hit it, the
- rule genuinely would not have worked.
-- **Rebuild behaviour is additive** — a rule is matched by `(entity, name)` and reused if present;
- edits are **not** re-applied. Recreate the rule to change it.
-
-## businessProcessFlows[] (optional — guided, staged process on a table)
-
-A BPF is the stage bar across the top of a record: an ordered set of stages, each with steps the user
-works through.
-
-```jsonc
-{ "entity": "new_ticket", "name": "Ticket Handling",
- "description": "How support tickets move to resolution", // optional
- "status": "Active", // Active (default) | Draft — a Draft flow is deployed but does NOT
- // appear on the form
- "order": 1, // optional; the workflow's processorder when several flows apply
- "stages": [
- { "name": "Triage", "steps": [
- { "name": "Subject", "field": "new_subject", "required": true },
- { "name": "Priority", "field": "new_priority" } ] },
- { "name": "Resolve", "steps": [
- { "name": "Resolution notes", "field": "new_notes" },
- { "name": "Confirmed with customer", "field": "new_confirmed" } ] }
- ] }
-```
-
-- **Stages are ordered** (array order) and each needs a unique `name` **and at least one step**; steps
- within a stage need unique names too. `stages[]` is required — a flow with no stage is not a
- process. A stage with no steps is rejected because the SDK substitutes a placeholder step literally
- named *"New Step"*, which would then appear on the stage bar without ever having been authored.
-- **A flow's `name` must be unique across the whole spec, not just per table.** The unique name
- Dataverse stores is derived as `new_<name lower-cased, non-alphanumerics stripped>` — it **ignores
- the table**, and the `new_` prefix is fixed regardless of your `publisherPrefix` — and activation
- creates a backing table with that name, so `"Ticket Handling"` on two
- different tables (or `"Ticket Handling"` and `"ticket-handling"` on one) cannot both deploy.
- Validation rejects the collision and names the derived value; rename one, e.g.
- `"Ticket Handling (Cases)"`.
-- **The derived name is a TABLE name, so it also collides with your tables.** A flow named
- `"Ticket"` derives `new_ticket`; if the spec declares a table `new_ticket`, the flow cannot
- deploy — and because the prefix is always `new_`, this is easy to hit on a spec using the default
- `new` publisher prefix. Validation rejects that too, naming both. A collision the spec cannot see
- (a rename between builds that preserves the derived name, or a flow — or a table — already in the
- environment) is caught at build time by a probe that checks both `workflows` and table metadata,
- and **halts** naming whichever owns the name rather than letting the create fail with a platform
- error about a table you never mentioned. The probe is best-effort — if it cannot run, the build
- proceeds.
-- **Every step must bind a `field`**, and it must be a column on the flow's own `entity` (its own
- columns, its primary name, or a lookup a relationship creates). The platform rejects a step with no
- column outright — `datafieldname of ControlStep cannot be null or empty` — so there is no such
- thing as a field-less "checklist" step; for a manual check-off, bind a Boolean column such as a
- `Confirmed` flag. Like a business rule, the platform *accepts* a step bound to a column that does
- not exist and simply renders it bound to nothing, so the column is validated up front too.
-- **At most 30 stages per flow and 30 steps per stage** — ceilings the SDK enforces, checked here so
- an over-large flow is a spec error rather than a failure in a late build phase.
-- **`status`** matters more than it does for a rule: an inactive BPF is not merely inert, it is
- **invisible** — the stage bar does not render at all. `Active` is the default for that reason.
-- **v1 is single-entity and linear.** Every stage must be on the flow's own `entity`. The SDK also
- models cross-entity stages, branching, stage actions and security-role grants; keys carrying them
- are **rejected** at flow, stage **and** step level (the allowed keys are `name`/`entity`/
- `description`/`status`/`order`/`stages`; per stage `name`/`entity`/`steps`; per step
- `name`/`field`/`required`). The rejection is an allow-list rather than a list of known-bad names
- because the SDK's own normalizers silently discard any key they do not copy — so an unguarded
- `branch` on a stage, or `fieldLogicalName` instead of `field` on a step, would validate clean and
- deploy as though it had never been written. Configure those in Maker after the flow deploys.
-- **Activation creates a backing table** (an org-owned table named after the flow's unique name)
- that the platform manages. Teardown deactivates and deletes the flow, which removes it.
-- **Rebuild behaviour is additive**, exactly like business rules — a flow is matched by
- `(entity, name)` and reused if present; only its Active/Draft **state** is converged. Stage and
- step edits are **not** re-applied: recreate the flow to change its structure.
-- Verified by `--verify` on three axes: it exists, there is exactly **one** of it (duplicates would
- offer users the same process twice), and its deployed state matches `status`.
-
-## dashboards[] (optional — chart/list/iframe/web-resource tiles)
-```jsonc
-{ "name": "Operations", "description": "Daily queue health for the support lead.", "tiles": [
- { "type": "chart", "chart": "Orders by Status", "view": "Active Orders" }, // chart needs both
- { "type": "list", "view": "Active Orders", "name": "Recent" }, // list needs a view
- { "type": "iframe", "url": "https://…", "name": "Map" },
- { "type": "webresource", "webResource": "new_widget.html", "name": "Widget" } ] }
-```
-- A **chart** tile needs both a declared `chart` (the visualization) **and** a declared `view` (its
- data); a **list** tile needs a declared `view`. The target entity is derived from the view. `name`
- defaults to the chart/view name; `colspan`/`rowspan` optional (default 1×4).
-- Built after views/charts (it references their ids). The dashboard is **global** (not entity-scoped)
- and added to the solution. To surface it in the app nav, add a `dashboard` sitemap subarea (below) —
- that also auto-pins it as an app component.
-
## pages[] (optional — generative pages / genux) [schemaVersion 2]
```jsonc
[ { "key": "overview", "name": "Overview", "purpose": "KPI overview + recent orders",
@@ -1046,7 +847,7 @@ works through.
## sampleData (optional)
Keyed by entity `schemaName`. Choice values are **labels** (resolved to ints) — for **both** inline
`options[]` columns **and** `globalChoice`-backed columns (write `"Platinum"`, not `100000000`; the
-engine resolves it, and the lint flags any label that isn't a declared option). Raw option ints still
+engine resolves it, and `lintAppSpec` flags any label that isn't a declared option). Raw option ints still
work. Relate records to parents with `$parent` (one) or `$parents` (several — for a junction row), and
set a custom status with `statusReason`. All are topologically inserted and bound via the lookup nav-property.
```jsonc
@@ -1062,6 +863,25 @@ set a custom status with `statusReason`. All are topologically inserted and boun
```
- **`$parents`** is the array form of `$parent` — each entry binds one lookup, so a junction/intersect
row links to every parent it points at (the engine sets each `<lookup>@odata.bind`).
+- **Self-referencing parents work.** A row may point at another row of the **same** entity — an org
+ hierarchy, a "reports to" chain — as long as the references form no cycle:
+ ```jsonc
+ "new_org": [ { "new_name": "Head Office" },
+ { "new_name": "North Region", "$parent": { "entity": "new_org", "match": { "new_name": "Head Office" } } } ]
+ ```
+ Order in the array does not matter; the engine seeds such rows in dependency waves, creating each
+ row only after the row it points at. A **cycle** (including a row that is its own parent) is
+ rejected by `validateAppSpec` — so by the build on load, and by
+ `scripts/lint-app-spec.js`, which runs it — because no creation order can satisfy it.
+- **`lookup`** (optional) names *which* relationship a parent bind goes through, by the lookup's
+ `schemaName`:
+ ```jsonc
+ "$parent": { "entity": "new_org", "lookup": "new_GroupAncestorId", "match": { "new_name": "Head Office" } }
+ ```
+ It is only needed when **two or more** `OneToMany` relationships connect the same pair — common for
+ a hierarchy table with both a "parent org" and a "group ancestor" self-lookup. Without it the bind
+ would be ambiguous, so `validateAppSpec` **rejects** it rather than silently picking the first
+ declared relationship and asserting something false about the data.
- **`statusReason`** must match a declared `statusReasons[]` label on the entity; the engine resolves
it to the right `statecode` + `statuscode` (so "Completed orders with Passed/Pending QA" just work).
The status option value is captured during the **data-model** phase — if you set `statusReason` on
@@ -1154,6 +974,15 @@ auto-selects tables that are good row-summary candidates and skips those that ar
- State an **explicit output shape**: a short paragraph is the recommended default.
**Validation rules** (`validateAppSpec` / `lintAppSpec`):
+
+> **The two gates are not the same, and only one of them runs on every build.**
+> `validateAppSpec` is the hard schema gate: `build-model-app.js` runs it on load, so
+> `--apply` refuses on its errors. `lintAppSpec` is the authoring guardrail, and the build
+> does **not** run it — its findings only reach you through `scripts/lint-app-spec.js`
+> (which runs migrate → `validateAppSpec` → `lintAppSpec`) or the skill's plan gate. So a
+> rule described below as enforced by the *lint* is one an unlinted spec will carry into a
+> build and fail at the platform. Where it matters, the rule names its gate.
+
- `ai.appFeatures` keys must be one of `formFill · nlSearch · nlChart · m365`; values must be a boolean or an integer between `0` and `1000000` (hard error) — the same range the SDK enforces, so an out-of-range value is rejected here rather than aborting the build half-applied. The boolean spelling is **not** a flat `1`/`0`: the **form-fill family** (`formFill` and its siblings) writes `2` for `true` and **`1` for `false`**, where `1` means *disabled* and `0` means *platform default*; `nlSearch`/`nlChart`/`m365` write `1`/`0`. Use an explicit integer for a platform value like "on for everyone".
- **`false` is not "leave alone".** It writes an app-scope override that beats the org value, and unlike enabling it is **not** gated — so `false` on a feature the org has enabled will turn that feature off for this app. To inherit the environment's setting, omit `ai.appFeatures` entirely.
- Omitting `ai.appFeatures` does **not** mean "no AI features": a spec carrying any `ai` block gets the defaults `formFill · nlSearch · nlChart` on and `m365` off, and `--verify` reconciles that whole resolved set.
@@ -1253,119 +1082,3 @@ same scope.
**Not yet supported** (tracked follow-up): column-level (field) security and access teams / hierarchy
security. The security surface today is role-per-persona plus `roleGrants[]` (below).
-## roleGrants[] (optional — extend a role you did NOT author)
-
-Adds privileges for a table to a security role that **already exists** — typically the roles an
-existing solution ships. Use it when you add a table to an app whose access model somebody else owns:
-without it the table, its forms and its navigation deploy while every non-admin persona still cannot
-open the table, and nothing reports it.
-
-```jsonc
-"roleGrants": [
- {
- // Name the EXISTING role. Either `role` (display name) or `roleId` (GUID) — never both.
- "role": "Contoso PM - Project Manager",
- "businessUnitId": "…", // optional; scopes the NAME lookup (defaults to the org root BU)
- "privileges": [
- { "entity": "contoso_projectbaseline",
- "access": ["create", "read", "write", "delete", "append", "appendTo", "assign", "share"],
- "scope": "organization" }
- ]
- },
- { "role": "Contoso PM - Viewer",
- "privileges": [ { "entity": "contoso_projectbaseline", "access": ["read"], "scope": "organization" } ] }
-]
-```
-
-**How it differs from `personas[]` — and why both exist.** A persona role is **converged**: the build
-applies it with `ReplacePrivilegesRole`, so every privilege not in the spec is **removed**. That is
-right for a role the spec created and catastrophic for one it did not — pointing a persona at an
-existing role to add one table would silently strip everything else that role held. A `roleGrant`
-compiles to `AddPrivilegesRole` instead, which is purely **additive**: it re-asserts what you declare
-and leaves everything else alone.
-
-| | `personas[]` | `roleGrants[]` |
-|---|---|---|
-| Owns the role | yes (creates it, SDK-marked) | no — the role already exists |
-| Semantics | converges (replace) | adds only |
-| Can revoke | yes, by dropping the privilege | **no** — see below |
-| Managed role | refused (fail-closed conflict) | allowed |
-| Teardown | deletes the role | does nothing |
-
-**A grant is one-way.** Dropping an entry from `roleGrants[]` does **not** revoke the privilege, and
-`teardown` never removes one. `AddPrivilegesRole` does not record who added what, so a revoke could not
-tell a privilege this spec granted from one the role already held (or one a second spec granted) —
-stripping the latter is exactly the outcome this surface exists to avoid. **Revoke in Maker.**
-
-**Field reference**
-- `role` **or** `roleId` (**required**, exactly one) — the existing role's display name, or its GUID. Setting both is rejected: they can disagree and only one can be honoured.
-- `businessUnitId` (optional GUID) — scopes a lookup by `role` name. Rejected alongside `roleId`, where nothing would consult it.
-- `privileges[]` (**required**, ≥1) — identical shape to a persona's: `{ entity, access[], scope? }`. `scope` reaches Dataverse intact as the privilege `Depth`.
-- `description` (optional) — a note for readers of the spec; never written to Dataverse.
-
-**Resolution fails closed.** Granting on the wrong role is a silent access-control defect no later
-phase would catch, so every ambiguity is a **build halt**, never a skip: a name that matches no role,
-a name that matches more than one role in the business unit, a stale pinned `roleId`, or a business
-unit that cannot be resolved (a name-only fallback could grant on a same-named role in a *different*
-business unit). Unlike the persona path this does **not** require the SDK ownership marker, and a
-`ismanaged` role is allowed — extending a solution's shipped roles is the point.
-
-**Validation rules** (`validateAppSpec`): exactly one of `role` / `roleId`; GUID shapes; a non-empty
-`privileges[]` with valid `access` / `scope` tokens; **one entry per role** (two entries could request
-conflicting depths for a shared Dataverse privilege — the SDK only detects that *within* one call, so
-a split would let both writes through and the later would silently win); and a role that is **also a
-persona in this spec** is rejected, because the persona pass would converge the grant away on the next
-build. The apply-time metadata guards (a table that exposes no such access; two tables sharing one
-`prv*` at different depths) surface as a build halt with the SDK's own message.
-
-**Verification.** `verify-model-app` proves the role exists (`role-grant`) and — when the reader
-supplies privilege access — that it actually **holds** every granted privilege at at least the declared
-depth (`role-grant-privileges`). This matters more here than for a persona: a persona role's existence
-implies its content (it was converged), whereas a grant is additive onto a role that existed before and
-still exists whether or not the privileges landed. Subset semantics again — the role's other privileges
-belong to somebody else and are never a finding.
-
-## businessProcessFlows[].securityRoles — who may run a flow
-
-Same shape and same persona idiom as `forms[].securityRoles`, so there is one thing to learn:
-
-```jsonc
-{ "name": "Ticket Handling", "entity": "contoso_ticket", "status": "Active",
- "securityRoles": { "personas": ["Dispatcher"] },
- "stages": [ /* … */ ] }
-```
-
-The **mechanic** is different, though, and it explains every rule below. A form's roles live inside
-its formxml. A flow's live on a **table**: activating a flow makes the platform create an
-organization-owned backing table, and holding privileges on that table is what lets a persona run the
-process. Three things measured live before this surface was designed:
-
-- the backing table's logical name is the flow's **deployed `uniquename`**, which the build **reads
- back** rather than deriving. For a flow this build creates the derivation is correct by
- construction, but a flow authored in Maker — or one renamed after creation — keeps a unique name
- unrelated to its display name, and granting on the derivation would target a table that does not
- exist, or an unrelated one that happens to hold that name. The plan can still *name* the derived
- table before the flow exists; the grant uses the value read at build time;
-- the table is organization-owned and **every privilege is Global-only** — so there is **no `scope`**
- to author, because the platform accepts no other depth;
-- the access granted is fixed at `create`, `read`, `write`, `delete` — a partial set produces a flow a
- user can see but not advance.
-
-**Rejected rather than ignored**
-- `everyone`, `fallbackForm`, `order` — formxml concepts with no equivalent here. The error says so
- rather than just listing allowed keys, because an author who wrote them learned them from `forms[]`.
-- an **empty** `personas[]` — unlike a form (offered to everyone until restricted), a flow's backing
- table grants to nobody by default, so an empty list is a request that cannot be satisfied.
-- `securityRoles` on a **Draft** flow — the backing table is created by *activation*, so there is
- nothing to grant on yet.
-
-Applied in the **security** phase, after `personas[]` roles exist. If the flow was not built in the
-same invocation the grant is **skipped with a stated reason**, never applied blind.
-`verify-model-app` proves each persona holds the privileges on the backing table (`bpf-roles`) and
-fails closed when that table cannot be read — which also catches a flow that never activated.
-Teardown plans nothing: measured, the flow (and with it the backing table and its privileges) is
-deleted before the roles, and the run completes with 0 failures.
-
-
-**Not yet supported** (tracked follow-up): column-level (field) security and access teams / hierarchy
-security.
diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.md
index 7ba0124c9..c8bd5c318 100644
--- a/plugins/model-apps/references/authoring-flow.md
+++ b/plugins/model-apps/references/authoring-flow.md
@@ -252,7 +252,8 @@ page-intents + design**, and **(c) access**. The author never emits `.tsx`; page
until generate-pages.
> **Read the spec format once, up front** — don't reverse-engineer it from scripts:
-> [`references/app-spec-schema.md`](./app-spec-schema.md) (every field) and the worked sample
+> [`references/app-spec-schema.md`](./app-spec-schema.md) (every always-present field; conditional
+> ones are in [`app-spec-schema-advanced.md`](./app-spec-schema-advanced.md)) and the worked sample
> [`samples/app-spec.support-desk.json`](../samples/app-spec.support-desk.json). Author to that
> shape. **Do not pre-create tables/columns/solution** during authoring — the build is
> idempotent and creates only what's missing.
@@ -315,7 +316,10 @@ Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Custome
column needs `options[]` **or** a `globalChoice` reference. Lookups are **not** a column type —
declare a `OneToMany` relationship instead.
-> **Author from [`references/app-spec-schema.md`](./app-spec-schema.md) — it is the single source.**
+> **Author from [`references/app-spec-schema.md`](./app-spec-schema.md) — it is the source for
+> everything an app always has; [`app-spec-schema-advanced.md`](./app-spec-schema-advanced.md)
+> carries the conditional fields it points at (business rules, BPFs, commands, web resources,
+> global choices, dashboards, `roleGrants[]`).**
> Its **modeling cheatsheet** answers the recurring questions without reading the SDK/lint/engine:
> auto-number identity → `autoNumberFormat` on `primaryAttribute`; **N:N with attributes** (e.g.
> Technician↔Work-Order with a Role) → a **junction entity** + two `OneToMany` (sample rows bind
diff --git a/plugins/model-apps/references/connectors.md b/plugins/model-apps/references/connectors.md
index de19da6b2..5bbee8a62 100644
--- a/plugins/model-apps/references/connectors.md
+++ b/plugins/model-apps/references/connectors.md
@@ -5,10 +5,9 @@ name. The `connectorLogicalName` string in TSX **MUST** equal a
`connectorBindings[].logicalName` value in the page `config.json`, and that
logical name must exist as a connection reference in the target environment.
-> **Gated behind the `connectors` feature flag (default OFF).** This reference is
-> only used when connector support is enabled — see the Feature Flags section in
-> the plugin `AGENTS.md` and `feature-flags.json`. When OFF, pages are Dataverse /
-> mock-data only and no connector code is emitted.
+> **GA.** Connector authoring is on by default. A `connectors` flag is retained for one
+> release as a rollback switch — when it is off, pages are Dataverse / mock-data only and
+> no connector code is emitted. See the Feature Flags section in the plugin `AGENTS.md`.
## Binding shape: `connectors.json` (array) vs page `config.json` (object)
diff --git a/plugins/model-apps/references/custom-api.md b/plugins/model-apps/references/custom-api.md
index 85bbba446..c29755ffd 100644
--- a/plugins/model-apps/references/custom-api.md
+++ b/plugins/model-apps/references/custom-api.md
@@ -8,8 +8,8 @@ in the page `config.json`, and that Custom API must exist in the target environm
> **Gated behind the `custom-api` feature flag (default OFF).** This reference is only used
> when Custom API support is enabled — see the Feature Flags section in the plugin `AGENTS.md`
-> and `feature-flags.json`. When OFF, pages are Dataverse / mock-data (and, when their own
-> flag is on, connector) only; **no Custom API code is emitted and no `actionBindings` are
+> and `feature-flags.json`. When OFF, pages are Dataverse / mock-data / connector only;
+> **no Custom API code is emitted and no `actionBindings` are
> written**. The `genpage-customapi-builder` agent is the single owner of this gate.
> **Vocabulary.** Makers author **Custom APIs** (the Dataverse `customapi` artifact); each is
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index 28448da41..7bb83203b 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -421,6 +421,7 @@ Recurring CSS bugs that type-check and compile but render wrong. Check for these
2. **Concatenated `makeStyles` classes lose status/warning colors to a shorthand-vs-longhand collision.** ``className={`${base} ${warning}`}`` (plain template string, not `mergeClasses`) where `base` sets a shorthand `border:` / `backgroundColor: "transparent"` and `warning` sets the longhand `borderColor` / `backgroundColor` — Griffel's atomic output plus the shorthand-vs-longhand cascade lets the base win, so the amber bg/border/text silently fall back to neutral. Fix: apply the status colors **inline** (`style={{ backgroundColor: tokens.colorStatusWarningBackground1, borderColor: tokens.colorStatusWarningBorder1 }}` — inline wins) or use `mergeClasses` instead of string concatenation.
3. **`tokens.fontFamilyNumeric` is Bahnschrift, not Segoe UI.** Using it for tabular numbers (counts, %, ranks, dates) renders those digits in Bahnschrift — visibly mismatched against Segoe UI everywhere else. Fix: use `tokens.fontFamilyBase` and keep `fontVariantNumeric: "tabular-nums"` for aligned digits.
4. **Gradient hero with white text: `colorPalette*Background2/3` tokens are light tints, not dark.** A gradient built from e.g. `colorPalettePurpleBackground3` / `colorPaletteTealBackground2` with `color: colorNeutralForegroundOnBrand` (white) renders white-on-light → unreadable; those `Background2/3` palette tokens are pale. Fix: build the gradient from the dark, saturated `colorPalette*Foreground2` stops (e.g. `colorPalettePurpleForeground2`, `colorPaletteTealForeground2`), which are dark enough for white text to pass AA.
+5. **`borderWidth` is an unsupported Griffel shorthand.** It passes TypeScript and `pac model genpage transpile`, then logs `@griffel/react: unsupported shorthand CSS property "borderWidth"` at runtime. Use all four explicit longhands (`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`) instead. Grep the finished page with `['"]?borderWidth['"]?\s*:` before deployment so quoted and whitespace-separated property syntax is caught too.
### Data Fetching: the host double-mount, de-dupe, and caching
diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.js
index d7bd84884..f0ef9bedc 100644
--- a/plugins/model-apps/scripts/add-page-to-solution.js
+++ b/plugins/model-apps/scripts/add-page-to-solution.js
@@ -4,11 +4,13 @@
// travels cross-environment. Verified live 2026-07-10 on a Dataverse test environment:
// - The appmodule (type 80, AddRequiredComponents=true) pulls the sitemap (62) and
// appmodulecomponent (10097) but does NOT pull the GenPage — so the GenPage's
-// uxagentproject row MUST be added explicitly (type 10372); adding it pulls its
-// uxagentprojectfile children (10373, incl. config.json with connectorBindings).
-// - connectionreference is its own component (type 10158) and is added explicitly so
+// uxagentproject row MUST be added explicitly; adding it pulls its
+// uxagentprojectfile children (incl. config.json with connectorBindings).
+// - connectionreference is its own component and is added explicitly so
// the bindings resolve in the target env (at import the deployer supplies each
// ConnectionId via `pac solution create-settings` + `pac solution import --settings-file`).
+// Both are custom tables whose ObjectTypeCode varies by environment, so their
+// component types are discovered from EntityDefinitions before any mutation.
//
// Usage:
// node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId>
@@ -21,20 +23,21 @@ const {
dataverseRequest,
ensureOk,
parseArgs,
+ validateFlags,
emitResult,
} = require('./lib/dataverse-auth');
const { isConnectorsEnabled, exitIfConnectorsDisabled } = require('./lib/feature-flags');
-// Connection references are connector state. When the connectors flag is OFF, ALM must not add
-// them. Two distinct cases, and conflating them is what made this silently lossy:
+// Connection references are connector state. When the connectors flag is OFF (the GA rollback
+// switch), ALM must not add them. Two distinct cases, and conflating them is what made this
+// silently lossy:
// 1. The caller passed NO --connection-refs → nothing to gate; non-connector page packaging
// (appmodule + uxagentproject) proceeds normally whether the flag is on or off.
// 2. The caller EXPLICITLY passed --connection-refs while the flag is OFF → this is the
-// documented fail-closed backstop (AGENTS.md → "Script backstop" / gate checklist item 4):
-// exit 3, BEFORE any AddSolutionComponent call. Previously the refs were dropped and the
-// script still reported `ok: true`, so an out-of-band/stale-plan call packaged a solution
-// WITHOUT the connection references the caller asked for and looked like it succeeded —
-// the resulting solution imports with unbound connectors.
+// documented fail-closed backstop: exit 3, BEFORE any AddSolutionComponent call. Previously
+// the refs were dropped and the script still reported `ok: true`, so an out-of-band/stale-plan
+// call packaged a solution WITHOUT the connection references the caller asked for and looked
+// like it succeeded — the resulting solution imports with unbound connectors.
// The gate runs before the first mutation so a refused run leaves the solution untouched rather
// than half-populated (app + pages added, refs missing).
function connectionRefsToAdd(refs, connectorsEnabled) {
@@ -42,18 +45,8 @@ function connectionRefsToAdd(refs, connectorsEnabled) {
}
const APPMODULE_COMPONENT_TYPE = 80;
-// Solution component type for the GenPage itself. uxagentproject IS a registered
-// component type (10372 = its ObjectTypeCode), verified live 2026-07-10 on a
-// Dataverse test environment. It does NOT auto-travel with the appmodule, so it is added
-// explicitly; AddRequiredComponents=true then pulls its uxagentprojectfile rows
-// (10373: page.tsx, page.compiled, config.json, firstPrompt.json).
-const UXAGENTPROJECT_COMPONENT_TYPE = 10372;
-// Solution component type for connectionreference. Verified live (2026-07-10) by
-// reading solutioncomponent.componenttype for an existing connection reference in the
-// Default/Active solutions of a test environment (= 10158). Note: 371 is "Connector"
-// (msdyn_Connector), NOT a connection reference — AddSolutionComponent with 371 fails
-// with "entity ... 'msdyn_Connector' ... not found in MetadataCache".
-const CONNECTION_REFERENCE_COMPONENT_TYPE = 10158;
+const UXAGENTPROJECT_LOGICAL_NAME = 'uxagentproject';
+const CONNECTION_REFERENCE_LOGICAL_NAME = 'connectionreference';
function escapeODataString(value) {
return String(value).replace(/'/g, "''");
@@ -70,23 +63,48 @@ async function addComponent(envUrl, solutionUniqueName, componentId, componentTy
ensureOk(res, `Add component ${componentId} (type ${componentType}) to ${solutionUniqueName}`);
}
+async function resolveEntityComponentType(envUrl, logicalName) {
+ const path = `EntityDefinitions(LogicalName='${escapeODataString(logicalName)}')?$select=ObjectTypeCode`;
+ const res = await dataverseRequest(envUrl, 'GET', path);
+ ensureOk(res, `Resolve component type for ${logicalName}`);
+ const componentType = Number(res.data?.ObjectTypeCode);
+ if (!Number.isInteger(componentType) || componentType <= 0) {
+ throw new Error(`Entity '${logicalName}' did not return a valid ObjectTypeCode`);
+ }
+ return componentType;
+}
+
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId> [--page-ids <id1,id2>] [--connection-refs <logicalName1,logicalName2>]';
+ // Both flags are comma-joined id lists. A bare one would become boolean `true`, and `true.split`
+ // is a TypeError mid-way through packaging rather than a usage error before it.
+ const flagError = validateFlags(argv, {
+ known: ['page-ids', 'connection-refs'],
+ needValue: ['page-ids', 'connection-refs'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 3) {
- process.stderr.write(
- 'Usage: node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId> [--page-ids <id1,id2>] [--connection-refs <logicalName1,logicalName2>]\n'
- );
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const [envUrl, solutionUniqueName, appId] = positional;
const added = [];
- // Parse the requested connection references BEFORE any mutation so the fail-closed gate can
- // refuse the whole run rather than leaving a half-packaged solution.
+ // Parsed BEFORE the first mutation so the fail-closed gate can refuse the whole run rather
+ // than leaving a half-packaged solution (app + pages added, refs missing).
const refs = (flags['connection-refs'] || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
+ const pageIds = (flags['page-ids'] || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
const connectorsOn = isConnectorsEnabled();
// Explicitly-requested refs while the feature is OFF = the documented exit-3 backstop.
if (refs.length && !connectorsOn) {
@@ -95,20 +113,26 @@ async function main() {
}
try {
+ // ObjectTypeCode for custom tables is allocated per environment. Resolve both
+ // types before the first AddSolutionComponent so a metadata failure leaves the
+ // target solution untouched instead of half-packaged.
+ const pageComponentType = pageIds.length
+ ? await resolveEntityComponentType(envUrl, UXAGENTPROJECT_LOGICAL_NAME)
+ : null;
+ const connectionReferenceComponentType = refs.length
+ ? await resolveEntityComponentType(envUrl, CONNECTION_REFERENCE_LOGICAL_NAME)
+ : null;
+
// The appmodule (type 80) with AddRequiredComponents=true pulls the sitemap and
// appmodulecomponent, but NOT the GenPage — the page is added explicitly below.
await addComponent(envUrl, solutionUniqueName, appId, APPMODULE_COMPONENT_TYPE, true);
added.push({ type: 'appmodule', id: appId });
- // Add each GenPage (uxagentproject, type 10372) explicitly. AddRequiredComponents
- // pulls its uxagentprojectfile rows (10373) — including config.json with the
+ // Add each GenPage (uxagentproject) explicitly. AddRequiredComponents
+ // pulls its uxagentprojectfile rows — including config.json with the
// connectorBindings that must travel with the page.
- const pageIds = (flags['page-ids'] || '')
- .split(',')
- .map((s) => s.trim())
- .filter(Boolean);
for (const pageId of pageIds) {
- await addComponent(envUrl, solutionUniqueName, pageId, UXAGENTPROJECT_COMPONENT_TYPE, true);
+ await addComponent(envUrl, solutionUniqueName, pageId, pageComponentType, true);
added.push({ type: 'uxagentproject', id: pageId });
}
@@ -123,7 +147,7 @@ async function main() {
const id = lookup.data?.value?.[0]?.connectionreferenceid;
if (!id) throw new Error(`Connection reference '${logicalName}' not found in env`);
- await addComponent(envUrl, solutionUniqueName, id, CONNECTION_REFERENCE_COMPONENT_TYPE, false);
+ await addComponent(envUrl, solutionUniqueName, id, connectionReferenceComponentType, false);
added.push({ type: 'connectionreference', logicalName, id });
}
@@ -139,4 +163,13 @@ if (require.main === module) {
main();
}
-module.exports = { connectionRefsToAdd };
+// Exported for unit tests. AppModule is a stable system component type; the two custom-table
+// component types are deliberately resolved per environment by resolveEntityComponentType.
+module.exports = {
+ connectionRefsToAdd,
+ escapeODataString,
+ APPMODULE_COMPONENT_TYPE,
+ UXAGENTPROJECT_LOGICAL_NAME,
+ CONNECTION_REFERENCE_LOGICAL_NAME,
+ resolveEntityComponentType,
+};
diff --git a/plugins/model-apps/scripts/ai-preflight.js b/plugins/model-apps/scripts/ai-preflight.js
index cf2a496c8..490c0ccc5 100644
--- a/plugins/model-apps/scripts/ai-preflight.js
+++ b/plugins/model-apps/scripts/ai-preflight.js
@@ -7,7 +7,7 @@
//
// Usage: node ai-preflight.js --env <orgUrl> [--app <uniqueName>]
-const { parseArgs, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { AI_APP_SETTING, AI_SETTING_CODEC, resolveAppModuleId, effectiveSettingValue, settingIsOn } = require('./lib/ai-app-settings.js');
const fs = require('node:fs');
@@ -104,12 +104,19 @@ function runPreflight(readiness, effective = {}) {
}
async function main() {
- const { flags } = parseArgs(process.argv.slice(2));
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const app = typeof flags.app === 'string' ? flags.app : null;
+ const argv = process.argv.slice(2);
+ const { flags } = parseArgs(argv);
+ const USAGE = 'Usage: node scripts/ai-preflight.js --env <orgUrl> [--app <uniqueName>]';
+ const flagError = validateFlags(argv, { known: ['env', 'app'], needValue: ['env', 'app'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const env = flags.env;
+ const app = flags.app || null;
- if (!env || flags.app === true) {
- process.stderr.write('Usage: node scripts/ai-preflight.js --env <orgUrl> [--app <uniqueName>]\n');
+ if (!env) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index 42a4aa40f..7bf842675 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -6,7 +6,7 @@
//
// Usage:
// node build-model-app.js --env <orgUrl> --spec @<app-folder>/app-spec.json [--apply]
-// [--sample-data] [--publish] [--verify] [--stage <data|ui|app|publish>]
+// [--sample-data] [--publish] [--verify] [--no-live-plan] [--stage <data|ui|app|publish>]
// [--only <phases>] [--skip <phases>] [--from <phase>] [--to <phase>]
// [--workspace <dir>]
// phases: solution,data-model,sample-data,web-resources,views,charts,forms,commands,dashboards,app-shell,pages,ai-features,security,publish
@@ -20,13 +20,17 @@ const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');
// bakes it into the App/Form/Dashboard adapters.
const { resolveAuthoringLanguage } = require('./lib/entity-provision.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
-const { parseArgs, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth } = require('./lib/dataverse-auth.js');
const { openJournal } = require('./lib/build-journal.js');
const { diffPhases, summarizeDiff } = require('./lib/phase-diff.js');
-const { annotateContentHashes } = require('./lib/content-hash.js');
+const { annotateContentHashes, pageSourceFileErrors } = require('./lib/content-hash.js');
const { runChangedOnlyApply, resolveLiveIdentity } = require('./lib/changed-only-flow.js');
const applySnapshotStore = require('./lib/apply-snapshot-store.js');
const { classifyOps, sitemapTargets } = require('./lib/op-diff.js');
+// Unattended-mode detection lives in one module so /app-builder and /genpage cannot drift apart
+// on what "unattended" means. Re-exported from here because callers and tests already import it
+// from this file.
+const { envTruthy } = require('./lib/interaction-mode.js');
// R3 (auto-verify): after a successful --apply the build can reconcile the spec against what actually
// deployed, so a silent partial build surfaces in the same run instead of only on a separate manual
// `verify-model-app.js` pass. Reuses the read-only reconcile core + the SDK reader (DRY — same code the
@@ -91,7 +95,16 @@ function cliEmit(log, opts = {}) {
return (e) => {
if (e.phase !== phase) { phase = e.phase; log(`\n▶ ${phase}`); }
if (e.status === 'start') return; // header only; the terminal event prints the status line
- if (!opts.apply) { log(` [${e.n}/${e.total}] ▢ ${e.label}`); return; } // dry-run plan
+ if (!opts.apply) {
+ // #559: the dry run now resolves each item against the live environment, so say which way it
+ // will go. A glyph alone cannot carry three states, and an unresolved one must not look like
+ // either decision — so name it.
+ if (e.status === 'warn') { log(` ⚠ ${e.label}`); return; }
+ const mark = e.state === 'create' ? '+ create' : e.state === 'reuse' ? '= reuse ' : e.state === 'unknown' ? '? unknown' : '▢';
+ const why = e.state === 'unknown' && e.stateWhy ? ` — ${e.stateWhy}` : '';
+ log(` [${e.n}/${e.total}] ${mark} ${e.label}${why}`);
+ return;
+ }
if (counts) counts[e.status] = (counts[e.status] || 0) + 1;
const glyph = e.status === 'ok' ? '✓' : e.status === 'skip' ? '⊘' : '✗';
const tail = e.status === 'error' ? ` — ${e.detail || ''}` : '';
@@ -160,6 +173,8 @@ async function buildModelApp(spec, opts, deps) {
if (!v.ok) {
return { ok: false, errors: v.errors };
}
+ const fileErrors = pageSourceFileErrors(spec, opts.appDir);
+ if (fileErrors.length) return { ok: false, errors: fileErrors };
const log = deps.log || (() => undefined);
// Surface non-blocking validation advisories (e.g. a PRE-EXISTING duplicate page name the build does
// not create — see validateAppSpec). These no longer HALT the build; they are narrated so the maker
@@ -277,6 +292,7 @@ async function buildModelApp(spec, opts, deps) {
apply: opts.apply,
sampleData: opts.sampleData,
publish: opts.publish,
+ livePlan: opts.livePlan,
phases: opts.phases,
appDir: opts.appDir, // resolves web-resource `contentPath` relative to the app folder
env: opts.env, // for the pages phase (pac model genpage upload --environment)
@@ -310,6 +326,19 @@ async function buildModelApp(spec, opts, deps) {
throw err;
}
}
+ // #559: a dry run's whole purpose is to say what an apply would DO, so summarise the decision
+ // rather than only listing the spec back. `unknown` is counted separately and never folded into
+ // either real decision — an unresolved probe is missing information, not a verdict.
+ if (r && r.dryRun && Array.isArray(r.planItems)) {
+ const n = (s) => r.planItems.filter((p) => p.state === s).length;
+ const unprobed = r.planItems.filter((p) => !p.state).length;
+ const parts = [`${n('create')} to create`, `${n('reuse')} already present`];
+ if (n('unknown')) parts.push(`${n('unknown')} could not be read`);
+ if (unprobed) parts.push(`${unprobed} not probed`);
+ log(r.livePlan
+ ? `\n▢ dry run — ${parts.join(', ')} (${r.planItems.length} steps). Re-run with --apply to execute.`
+ : `\n▢ dry run — ${r.planItems.length} steps, spec-only (no live probe; --no-live-plan). Re-run with --apply to execute.`);
+ }
if (opts.apply && r && r.ok && !r.dryRun) {
log(`\n✓ build complete — ${counts.ok} created, ${counts.skip} skipped, ${counts.error} failed (${counts.ok + counts.skip + counts.error} steps)`);
// R3 — auto-verify: reconcile the spec against what actually deployed so a silent partial build
@@ -415,16 +444,6 @@ function backoffMs(attempt) {
return Math.min(30000, 3000 * Math.pow(2, attempt - 1)) + Math.floor(Math.random() * 1000);
}
-// Env var truthiness for the unattended opt-in: '1' or 'true' (case-insensitive) count as set; a
-// missing/other value is false. Matches the dotnet-style boolean env convention used elsewhere in this
-// repo (see AGENTS.md "Shared Telemetry"). This gates PROMPT SUPPRESSION ONLY — it never grants
-// destructive authority (only --allow-destructive does).
-function envTruthy(v) {
- if (v == null) return false;
- const s = String(v).trim().toLowerCase();
- return s === '1' || s === 'true';
-}
-
function list(v) {
return typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
}
@@ -445,26 +464,37 @@ function parseLanguageCode(value) {
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- // parseArgs sets a value-less flag to boolean `true`. Coerce required-VALUE flags to missing so a
- // bare flag fails with the usage message instead of (a) crashing later, or (b) — critically for the
- // phase selectors — being read as `undefined` and SILENTLY SELECTING ALL PHASES. e.g. `--apply --only`
- // with no value must NOT become a full apply on this destructive tool. Boolean switches
- // (--apply/--publish/--verify/…) legitimately stay `true`.
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const specArg = typeof flags.spec === 'string' ? flags.spec : positional[0];
- if (!env || !specArg) {
- process.stderr.write(
- 'Usage: node scripts/build-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--sample-data] [--publish] [--verify] [--changed-only] [--stage <data|ui|app|publish>] [--only|--skip <phases>] [--from|--to <phase>] [--language-code|--languageCode <lcid>] [--non-interactive] [--allow-destructive] [--workspace <dir>]\n'
- );
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE =
+ 'Usage: node scripts/build-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--sample-data] [--publish] [--verify] [--changed-only] [--no-live-plan] [--stage <data|ui|app|publish>] [--only|--skip <phases>] [--from|--to <phase>] [--language-code|--languageCode <lcid>] [--non-interactive] [--allow-destructive] [--workspace <dir>]';
+ // The declared flag contract, enforced before anything else runs.
+ //
+ // `needValue` lists every flag whose MISSING value would be read as a default rather than an
+ // error — critically the phase selectors, where a bare `--only` is dropped by
+ // list()/stagePhasesOrResolve and silently resolves to the full phase set. `--apply --only` must
+ // not become a full apply on this destructive tool.
+ //
+ // validateFlags additionally rejects an unrecognised flag, which parseArgs would otherwise drop
+ // while swallowing the token after it. Measured before this guard: `--stage ui` planned 3 steps
+ // but the one-letter typo `--stagee ui` planned all 9 and still exited 0 — a caller who believed
+ // they had scoped an apply to the UI phases got a full data-model apply with no diagnostic.
+ const flagError = validateFlags(argv, {
+ known: ['env', 'spec', 'apply', 'sample-data', 'publish', 'verify', 'changed-only', 'no-live-plan',
+ 'stage', 'only', 'skip', 'from', 'to', 'language-code', 'languageCode', 'non-interactive',
+ 'allow-destructive', 'workspace'],
+ needValue: ['env', 'spec', 'stage', 'only', 'skip', 'from', 'to', 'language-code', 'languageCode', 'workspace'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
process.exit(1);
}
- // A value-less phase selector (or --workspace) is a USAGE ERROR — never a silent all-phases select
- // or default workspace. `--only`/`--skip`/`--from`/`--to`/`--stage` with no value would otherwise be
- // dropped by list()/stagePhasesOrResolve and resolve to the full phase set.
- const valuelessFlag = ['stage', 'only', 'skip', 'from', 'to', 'workspace', 'language-code', 'languageCode'].find((k) => flags[k] === true);
- if (valuelessFlag) {
- process.stderr.write(`✗ --${valuelessFlag} requires a value.\n`);
+ // validateFlags has already rejected a bare or empty --env/--spec, so each is now either absent
+ // or a non-empty string; the typeof dance these lines used to carry is subsumed by it.
+ const env = flags.env;
+ const specArg = flags.spec || positional[0];
+ if (!env || !specArg) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
// #changed-only (Preview): a SAFE partial apply. Incompatible with manual phase selection — the flow
@@ -500,6 +530,10 @@ async function main() {
apply: flags.apply === true,
sampleData: flags['sample-data'] === true,
publish: flags.publish === true,
+ // #559: a dry run resolves create-vs-reuse against the live environment by default, because a
+ // plan that cannot tell them apart is not a plan. `--no-live-plan` restores the offline,
+ // spec-only listing for a caller with no environment access.
+ livePlan: flags['no-live-plan'] !== true,
verify: flags.verify === true,
phases,
profile: (flags.apply === true && flags.stage !== 'data') ? 'deploy' : 'plan',
diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.js
index c39dbaa7d..968ca89b7 100644
--- a/plugins/model-apps/scripts/check-auth.js
+++ b/plugins/model-apps/scripts/check-auth.js
@@ -33,21 +33,25 @@
// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.
const { execFileSync } = require('child_process');
-const { dataverseRequest } = require('./lib/dataverse-auth');
+const { dataverseRequest, parseArgs, validateFlags } = require('./lib/dataverse-auth');
// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or
// the first positional arg, so a caller can copy the `--env` form here without silently passing
// the literal string "--env" as the URL (the prior positional-only parse did exactly that).
+//
+// `--env` is read through the shared parseArgs, which already encodes the rule that a flag followed
+// by another FLAG is boolean `true` rather than a value — so `--env --require-pac` cannot read the
+// next flag as the URL.
+//
+// The positional fallback deliberately does NOT use parseArgs' `positional` array. parseArgs has no
+// flag contract, so it cannot know `--require-pac` is a boolean switch and consumes the token after
+// it as its value: `check-auth.js --require-pac <url>` would lose the URL entirely and fall back to
+// `pac org who`, silently probing a different environment than the caller named. The header
+// documents both orderings, and an agent assembling this command does not control the order.
function parseEnvUrl(argv) {
- const flagIdx = argv.indexOf('--env');
- if (flagIdx !== -1) {
- const value = argv[flagIdx + 1];
- // `--env --require-pac` used to treat the next flag as the URL, sending a bogus Dataverse
- // request to a flag string. A value-bearing flag must have a following non-flag token.
- if (value && !value.startsWith('--')) return value;
- return null;
- }
- const positional = argv.find((a) => !a.startsWith('--'));
+ const { flags } = parseArgs(argv);
+ if (flags.env !== undefined) return typeof flags.env === 'string' && flags.env.trim() ? flags.env : null;
+ const positional = argv.find((a) => typeof a === 'string' && !a.startsWith('--'));
return positional || null;
}
@@ -90,6 +94,16 @@ function normalizeUser(u) {
async function main() {
const argv = process.argv.slice(2);
+ // This tool always exits 0 so callers can parse stdout, so a usage error is reported as a
+ // structured blocker rather than a non-zero exit — a `--requir-pac` typo must not silently
+ // downgrade a hard pac requirement to a warning.
+ const flagError = validateFlags(argv, { known: ['env', 'require-pac'], needValue: ['env'] });
+ if (flagError) {
+ return emit(buildResult({
+ blocker: 'usage',
+ message: `${flagError}. Usage: node check-auth.js --env <url> [--require-pac]`,
+ }));
+ }
let envUrl = parseEnvUrl(argv);
// Genpage deploys pages via `pac model genpage ...`, so its callers pass --require-pac to keep a
// missing pac login a hard blocker. The app-builder build path only needs the az token, so it
diff --git a/plugins/model-apps/scripts/create-connection-reference.js b/plugins/model-apps/scripts/create-connection-reference.js
index addb0c35f..fae1eb64a 100644
--- a/plugins/model-apps/scripts/create-connection-reference.js
+++ b/plugins/model-apps/scripts/create-connection-reference.js
@@ -21,20 +21,29 @@ const {
dataverseRequest,
ensureOk,
parseArgs,
+ validateFlags,
emitResult,
} = require('./lib/dataverse-auth');
const { exitIfConnectorsDisabled } = require('./lib/feature-flags');
async function main() {
- // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature
- // off", distinct from 1 = runtime/usage error, so callers can tell them apart.
+ // Rollback gate (fail closed) — see lib/feature-flags.js. connectors is GA and ships ON, so
+ // this normally passes; exit 3 = "feature off" stays distinct from 1 = runtime/usage error.
exitIfConnectorsDisabled();
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node create-connection-reference.js <envUrl> <logicalName> <connectorId> [--connection-id <id>] [--display-name <name>]';
+ const flagError = validateFlags(argv, {
+ known: ['connection-id', 'display-name'],
+ needValue: ['connection-id', 'display-name'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 3) {
- process.stderr.write(
- 'Usage: node create-connection-reference.js <envUrl> <logicalName> <connectorId> [--connection-id <id>] [--display-name <name>]\n'
- );
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const [envUrl, logicalName, connectorId] = positional;
diff --git a/plugins/model-apps/scripts/dataverse-request.js b/plugins/model-apps/scripts/dataverse-request.js
index fe4b87fd8..8ccfad02c 100644
--- a/plugins/model-apps/scripts/dataverse-request.js
+++ b/plugins/model-apps/scripts/dataverse-request.js
@@ -25,14 +25,24 @@
// 0 - Request completed (check status field for HTTP result)
// 1 - Fatal error (no token, invalid args, network failure after retries)
-const { dataverseRequest, parseArgs, readJsonArg } = require('./lib/dataverse-auth');
+const { dataverseRequest, parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth');
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json|@path>] [--include-headers] [--timeout <ms>]';
+ // `--include-headers` is a genuine boolean switch; --body and --timeout both carry values.
+ const flagError = validateFlags(argv, {
+ known: ['body', 'include-headers', 'timeout'],
+ needValue: ['body', 'timeout'],
+ hints: { timeout: 'a positive millisecond value (for example, --timeout 60000)' },
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 3) {
- process.stderr.write(
- 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json|@path>] [--include-headers] [--timeout <ms>]\n'
- );
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
@@ -43,10 +53,6 @@ async function main() {
let timeout = undefined;
if (flags.timeout !== undefined) {
- if (typeof flags.timeout !== 'string') {
- process.stderr.write('--timeout must include a positive millisecond value (for example, --timeout 60000)\n');
- process.exit(1);
- }
const parsed = Number(flags.timeout);
if (!Number.isFinite(parsed) || parsed <= 0) {
process.stderr.write(`--timeout must be a positive number (got "${flags.timeout}")\n`);
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index 80e01bc44..5bd33e557 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -9,7 +9,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const { parseArgs, emitResult, preflightAuth } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, emitResult, preflightAuth } = require('./lib/dataverse-auth.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { hydrateSpec, descriptionFromDataverse, withDescription } = require('./lib/hydrate-spec.js');
const { makeGenpageCli } = require('./lib/genpage-cli.js');
@@ -17,7 +17,7 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(
const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');
const { fetchSitemap, sitemapGenPages } = require('./lib/sitemap-pages.js');
const { isRestrictedSolution } = require('./lib/system-solutions.js');
-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap } = require('./lib/app-spec.js');
+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases } = require('./lib/app-spec.js');
const { odataGuid } = require('./lib/ai-app-settings.js');
// webresourcetype (int) -> app-spec web-resource type.
@@ -166,16 +166,22 @@ function collectSitemap(app) {
// the sitemap alone silently dropped those (ADO 6603388), so the download→edit→rebuild round trip
// lost hidden app dependencies.
//
-// The entity is derived from the app's VIEW / CHART / FORM components, NOT from its
-// `componenttype eq 1` (Entities) rows. That looks like the obvious source but is unusable:
-// LIVE-verified that every componenttype-1 row carries the SAME `objectid` — the MetadataId of the
-// `entity` metadata table itself — so it identifies the component *kind*, not which table. (On a
-// 2-table app both rows read `9d0f025b-…`, which resolves to the logical name `entity`.)
-// `RetrieveAppComponents` returned 0 rows on the same app, so it is not an alternative here.
+// The entity is derived from the app's VIEW / CHART / FORM components rather than from its
+// `componenttype eq 1` (Entities) rows.
//
-// View/chart/form components DO carry usable ids: each `objectid` is a real row id whose record
-// names its owning table. An app includes its tables' views and forms, so unioning their owners
-// recovers the hidden membership.
+// CORRECTED (re-measured live): an earlier note here claimed the type-1 rows were
+// UNUSABLE because "every row carries the same objectid — the MetadataId of the `entity` metadata
+// table". That observation was real, but it was made against an app corrupted by the defect where every
+// table had been pinned as an `entity` INSTANCE, pinning the `entity` metadata table itself. On a
+// HEALTHY app the rows carry the REAL table
+// MetadataIds — re-measured on a 3-table app, which returned three distinct ids resolving to its
+// three tables — and `RetrieveAppComponents` answers 200, not the 0 rows previously recorded.
+// `verify-spec` now relies on exactly that, so the old claim must not be left standing.
+//
+// The view/chart/form derivation is KEPT regardless, because it is not merely a workaround for that
+// stale claim: it is the source that recovers tables reachable only through a lookup, sub-grid or
+// related view, which is the gap this function exists to close. Type-1 rows are a
+// legitimate additional source for a future change; they are simply not needed here.
// componenttype 26 → savedquery.returnedtypecode
// componenttype 59 → savedqueryvisualization.primaryentitytypecode
// componenttype 60 → systemform.objecttypecode
@@ -437,10 +443,30 @@ async function readDescriptionInventory(sdk, appId, solutionUniqueName) {
// failure beyond the catch's reach, so a metadata 403 was indistinguishable from an environment
// with no global choices — and now that the report consumes this list, that reads as a positive
// claim rather than an absence of information.
- const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description');
+ //
+ // Only UNMANAGED option sets are inventoried. A managed one ships with its solution and exists in
+ // any environment that has that solution installed, so naming it as "not round-tripped" is false:
+ // there is nothing for a rebuild to recreate. Measured live on a stock environment: 149 global
+ // option sets total, of which exactly 1 was unmanaged — so reporting all of them buried the two
+ // real findings (a form and a view) under 148 lines the maker can neither act on nor recognise.
+ //
+ // The filter is CLIENT-side because `GlobalOptionSetDefinitions` rejects `$filter` outright —
+ // `?$filter=IsManaged eq false` answers HTTP 405 `0x80060888 "The query parameter $filter is not
+ // supported on GlobalOptionSetDefinitions"`. `IsCustomOptionSet` is deliberately NOT the
+ // discriminator: 59 of those 149 were "custom", nearly all of them first-party managed-solution
+ // choices (msdyn_*, mspp_*), so it reproduces most of the noise.
+ //
+ // An ABSENT `IsManaged` keeps the row. This inventory's whole purpose is to avoid asserting an
+ // absence it cannot substantiate, so an unreadable flag degrades to "report it" rather than to a
+ // silent drop.
+ const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged');
if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');
- inventory.globalChoices.push(...res.body.value.map((r) => withDescription({ name: r.Name }, r.Description)));
+ inventory.globalChoices.push(
+ ...res.body.value
+ .filter((r) => r && r.IsManaged !== true)
+ .map((r) => withDescription({ name: r.Name }, r.Description))
+ );
} catch (err) {
fail('globalChoices', err);
}
@@ -572,6 +598,163 @@ const SPEC_TYPE_FROM_ATTRIBUTE_TYPE = {
// everything-is-Text, so the affected columns are warned about by name.
const TYPES_NEEDING_COMPANION_DATA = new Set(['Choice', 'MultiChoice']);
+// The two Dataverse attribute CASTS that carry an option set. `Attributes` is a heterogeneous
+// collection, so `OptionSet` can only be `$expand`ed through a cast segment — an uncast
+// `/Attributes?$expand=OptionSet` is rejected because most attribute types have no such property.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api
+//
+// `GlobalOptionSet` is deliberately NOT expanded, even though it is the obvious-looking way to tell a
+// shared set from a local one. LIVE-MEASURED against a stock org: it is populated for a LOCAL set
+// too, echoing that local set's own Name (`account.accountcategorycode` -> IsGlobal:false, yet
+// GlobalOptionSet.Name === "account_accountcategorycode"). Keying off its presence, or off its Name,
+// would classify every local set as global and emit a `globalChoice` reference to a shared set that
+// does not exist — so the rebuild would bind the column to nothing. `OptionSet.IsGlobal` is the only
+// honest discriminator, and `OptionSet.Options` is populated for BOTH kinds (confirmed on a
+// global-bound column: `contact.mspp_userpreferredlcid` returned all 45 options through `OptionSet`).
+const OPTION_SET_CASTS = [
+ { cast: 'Microsoft.Dynamics.CRM.PicklistAttributeMetadata', type: 'Choice' },
+ { cast: 'Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata', type: 'MultiChoice' },
+];
+
+// Dataverse `AttributeTypeName` -> App Spec type, for the choice types ONLY. This is POSITIVE type
+// evidence that does not depend on the option-set read succeeding, and it is why a Choice column now
+// survives a failed or empty cast read instead of disappearing.
+//
+// It exists because `AttributeType` LIES for a multi-select: LIVE-MEASURED, a MultiSelectPicklist
+// reports `AttributeType: "Virtual"` — indistinguishable from the synthetic `<column>name` shadows —
+// and only `AttributeTypeName: "MultiSelectPicklistType"` identifies it. Relying on cast membership
+// instead meant an unusable option label, a 503, or even a 200 with an empty `value[]` silently
+// DELETED a real MultiChoice column from the spec, which is the loss this whole change exists to end.
+// `AttributeTypeName` is a base `AttributeMetadata` property, so selecting it is safe on every
+// supported Web API version.
+const SPEC_TYPE_FROM_ATTRIBUTE_TYPE_NAME = { PicklistType: 'Choice', MultiSelectPicklistType: 'MultiChoice' };
+
+// The App Spec type an attribute can be proven to have WITHOUT a successful option-set read.
+function choiceTypeFromTypeName(a) {
+ const name = a && a.AttributeTypeName && a.AttributeTypeName.Value;
+ return name ? SPEC_TYPE_FROM_ATTRIBUTE_TYPE_NAME[name] : undefined;
+}
+
+// One downloaded option set, or null when it carries nothing this spec can declare. Shape:
+// { name: 'new_ticket_new_status', isGlobal: false, options: [<Dataverse Label>, ...] }
+//
+// The RAW Label is kept rather than a flattened string because the same option has to be emitted TWO
+// different ways depending on where it lands: an inline `columns[].options[]` may be a localized LCID
+// map, while a `globalChoices[]` option may NOT be (validateAppSpec rejects it, because Dataverse
+// stores only the base language for a shared set and reports nothing when it drops the rest).
+// Deriving both from one source keeps them from drifting.
+//
+// Option ORDER is preserved exactly as Dataverse returned it and is NOT sorted by `Value`. Dataverse
+// returns options in their DISPLAY order, and the App Spec assigns `value = 100000000 + index` — so
+// the array order is what a rebuild reproduces on screen. Sorting by Value would silently reorder the
+// picker for any set whose author arranged it by hand.
+function optionSetFromRow(row) {
+ const os = row && row.OptionSet;
+ if (!os || !Array.isArray(os.Options) || !os.Options.length) return null;
+ const name = typeof os.Name === 'string' && os.Name.trim() ? os.Name : null;
+ const labels = os.Options.map((o) => o && o.Label);
+ // EVERY option must yield a usable label. A partially readable set cannot be emitted: dropping the
+ // unreadable ones would shift every later option's index, and therefore its value, so a rebuild
+ // would silently re-point existing data. Refusing to type the column is the honest outcome, and it
+ // falls through to the untyped warning that already exists for exactly this case.
+ if (labels.some((l) => descriptionFromDataverse(l) === undefined)) return null;
+ return { ...(name ? { name } : {}), isGlobal: os.IsGlobal === true, options: labels };
+}
+
+// One INLINE Choice option's App Spec label. Localization is PRESERVED here — unlike a
+// `globalChoices[]` option, which must be a plain string — because `columns[].options[]` round-trips
+// an LCID map correctly. `labelFromDataverse` reads only `LocalizedLabels`, so a Label carrying just
+// a `UserLocalizedLabel` falls back to the single-string unwrap rather than emitting `undefined`,
+// which would fail validation with "options[i] must be a non-empty string".
+function choiceOptionLabel(label) {
+ const localized = labelFromDataverse(label);
+ return localized !== undefined ? localized : descriptionFromDataverse(label);
+}
+
+// Read the option sets for every Choice / MultiChoice column on one table, keyed by lower-cased
+// attribute logical name. THROWS on a failed read so the caller records WHY, rather than silently
+// emitting a spec whose Choice columns degraded to Text.
+async function readOptionSets(sdk, logical) {
+ const byLogical = new Map();
+ let failed = null;
+ for (const { cast, type } of OPTION_SET_CASTS) {
+ const url = `/${metadataEntityPath(logical)}/Attributes/${cast}?$select=LogicalName&$expand=OptionSet($select=Name,IsGlobal,Options)`;
+ try {
+ const res = await sdk.dataverse.get(url);
+ // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status must be checked
+ // explicitly — the same trap documented on the description reads above.
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
+ if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');
+ for (const row of res.body.value) {
+ const key = String((row && row.LogicalName) || '').toLowerCase();
+ if (!key) continue;
+ // The CAST that returned the row is authoritative for the TYPE, and it is recorded even when
+ // the OPTIONS could not be parsed (`optionSetFromRow` -> null). Conflating the two DELETED
+ // the column: a MultiChoice reports `AttributeType: "Virtual"`, so discarding this entry
+ // discarded the only evidence it was an authorable column at all, and it vanished from the
+ // spec while the warning claimed it had merely lost its type.
+ byLogical.set(key, { ...(optionSetFromRow(row) || {}), type });
+ }
+ } catch (err) {
+ // Per-cast, NOT fatal. The two casts are independent reads; throwing here discarded an
+ // already-valid Picklist map whenever the multi-select cast failed, so a single transient 503
+ // stripped the type off every Choice column on the table. Keep what was read, report the rest.
+ if (!failed) failed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
+ }
+ }
+ return { byLogical, failed };
+}
+
+// Gather the SHARED option sets a downloaded table binds to, into `into` (name-keyed, so one set
+// bound by several columns is declared once). Global sets must be declared in `spec.globalChoices[]`
+// or a rebuild into a FRESH environment has nothing to bind the column to — `createGlobalOptionSet`
+// is idempotent (it probes by Name and reuses), so declaring one that already exists is safe.
+//
+// Options are FLATTENED to a single string here, unlike the inline case: `validateAppSpec` rejects a
+// localized `globalChoices[]` option outright, because Dataverse accepts the multi-language payload
+// for a shared set and stores only the base language without reporting the loss.
+function collectGlobalChoices(meta, into) {
+ for (const a of (meta && meta.attributes) || []) {
+ const os = a && a.optionSet;
+ if (!os || !os.isGlobal || !os.name) continue;
+ const key = String(os.name).toLowerCase();
+ if (into.has(key)) continue;
+ into.set(key, { name: os.name, options: os.options.map((l) => descriptionFromDataverse(l)) });
+ }
+ return into;
+}
+
+// Reduce the collected global-choice CANDIDATES to the ones an EMITTED column actually references,
+// and canonicalize every reference to the declaration's own casing.
+//
+// Both halves close real defects. `collectGlobalChoices` scans RAW metadata, which runs before
+// `entityFromMetadata` filters attributes and before an entity with no primary name is dropped — so
+// a set bound only by a system attribute, or by a table that never made it into the spec, produced
+// an ORPHAN declaration. That is not cosmetic: `provisionDataModel` calls `createGlobalOptionSet`
+// for every declaration, so the rebuild wrote an option set into the target environment that nothing
+// in the app uses.
+//
+// The casing half: declarations are de-duplicated on a lower-cased key, but each column kept the raw
+// `OptionSet.Name` casing Dataverse happened to return for it. `entity-provision` then looks up
+// `globalChoiceIds[c.globalChoice]` CASE-SENSITIVELY, so a second casing of the same set left that
+// column unbound and it silently fell back to an EMPTY inline option list. Rewriting the references
+// here keeps that fix in one place rather than relying on every consumer to normalize.
+function finalizeGlobalChoices(entities, candidates) {
+ const byKey = candidates instanceof Map ? candidates : new Map();
+ const referenced = new Map(); // lower-cased name -> declaration
+ for (const e of entities || []) {
+ for (const c of (e && e.columns) || []) {
+ if (!c || !c.globalChoice) continue;
+ const key = String(c.globalChoice).toLowerCase();
+ const decl = byKey.get(key);
+ if (!decl) continue;
+ c.globalChoice = decl.name;
+ if (!referenced.has(key)) referenced.set(key, decl);
+ }
+ }
+ return [...referenced.values()];
+}
+
// Does this form's `formxml` restrict it to particular security roles?
//
// The roles live INSIDE formxml, as a `<DisplayConditions>` child of `<form>` — `systemform` has no
@@ -677,6 +860,22 @@ function notRoundTrippedSummary(inventory) {
};
}
+// Drop from the not-round-tripped inventory the global choices this download DOES now reconstruct
+// (#564). The report's whole value is that its claims are true: a shared set emitted into
+// `spec.globalChoices[]` IS carried forward, so listing it as "not round-tripped" would be the same
+// class of false statement the report exists to prevent. Every other global choice in the
+// environment stays listed — the app does not bind it, so a rebuild genuinely will not recreate it.
+function roundTrippedAware(inventory, globalChoiceDecls) {
+ if (!inventory || !Array.isArray(inventory.globalChoices) || !globalChoiceDecls || !globalChoiceDecls.size) return inventory;
+ const declared = globalChoiceDecls;
+ const remaining = inventory.globalChoices.filter((g) => !(g && g.name && declared.has(String(g.name).toLowerCase())));
+ // Drop the key entirely when nothing is left: `notRoundTrippedSummary` skips an empty class, and an
+ // empty array would otherwise be indistinguishable from "the read returned no rows".
+ const { globalChoices, ...rest } = inventory;
+ void globalChoices;
+ return remaining.length ? { ...rest, globalChoices: remaining } : rest;
+}
+
// Render `notRoundTrippedSummary` as the operator-facing warning. Kept separate from the computation
// so the wording is testable without a download, and so the same summary can be emitted as JSON.
function notRoundTrippedWarning(summary) {
@@ -754,17 +953,96 @@ function entityFromMetadata(meta, logical) {
// sdk-build.js `defaultViewColumns`: the set only ever contains DECLARED spec columns.
const isCustom = a.isCustomAttribute !== undefined ? a.isCustomAttribute : a.IsCustomAttribute;
if (isCustom === false) return false;
- // Keep only attribute types the App Spec can declare (see the map above).
+ // SYNTHETIC SHADOW attributes. Creating a lookup also creates a formatted-name attribute
+ // (`<lookup>name`) which LIVE-MEASURED reports `AttributeType: "String"` AND
+ // `IsCustomAttribute: true` — so neither the type map nor the custom-only filter above excludes
+ // it, and a downloaded spec declared a REAL Text column named after a lookup's shadow. Measured
+ // consequence: a fresh-environment rebuild created `<table>.<lookup>name (Text)`, an invented
+ // column that also collides with the name the real lookup's own shadow needs. `IsLogical` (the
+ // value is not stored on this table) is the distinguishing fact.
+ //
+ // Gated on positive TYPE EVIDENCE, not on "logical" alone: an attribute is dropped only when it
+ // is logical AND nothing proves it is a real choice column (no parsed option set, and no
+ // `AttributeTypeName` saying Picklist/MultiSelectPicklist). Keying only off `optionSet ===
+ // undefined` dropped a genuine logical Choice whenever its option-set read failed, and the
+ // untyped warning then promised a Text column that a rebuild would never create.
+ //
+ // HONESTY NOTE on the example this rule is often justified with: every logical choice attribute
+ // found on stock tables — `address1_addresstypecode` and its five `address1_`/`address2_` twins
+ // on account, plus the equivalents on contact/systemuser/businessunit, 23 in total — is
+ // `IsCustomAttribute: false`, so the custom-only check above already drops them and they never
+ // reach this rule. No CUSTOM logical choice column was found on a live org, so the exemption is
+ // DEFENSIVE rather than demonstrated load-bearing. It is kept because dropping on "logical"
+ // alone becomes a silent column deletion the moment such a column does exist, which is the exact
+ // failure class this change exists to end.
+ //
+ // An ABSENT flag KEEPS the attribute, matching the `isCustom === false` rule above: "we could not
+ // look" must not be turned into a deletion. The direction matters — `IsLogical` is absent for
+ // EVERY attribute when the read fails, so dropping on absent would empty the table's `columns[]`
+ // entirely. The residual cost is that a failed read re-enables the shadow leak, which is why the
+ // label-read warning now names that consequence explicitly.
+ const isLogical = a.IsLogical !== undefined ? a.IsLogical : a.isLogical;
+ if (isLogical === true && a.optionSet === undefined && choiceTypeFromTypeName(a) === undefined) return false;
+ // Keep only attribute types the App Spec can declare (see the map above), PLUS any attribute the
+ // option-set read matched, PLUS any attribute `AttributeTypeName` proves is a choice. That last
+ // clause is what keeps a MultiChoice when the cast read failed or came back empty: its
+ // `AttributeType` is `Virtual`, so nothing else would admit it.
const at = a.attributeType || a.AttributeType;
- return at === undefined || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at] !== undefined;
+ return at === undefined || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at] !== undefined || a.optionSet !== undefined || choiceTypeFromTypeName(a) !== undefined;
}).map((a) => {
const schemaName = (a && (a.schemaName || a.SchemaName || a.logicalName || a.LogicalName)) || '';
// The SDK projects `attributeType`, NOT `type`. Reading `a.type` yielded `undefined` on every
// column, which silently disabled every type-based filter downstream (`DEFAULT_VIEW_SKIP_TYPES`
// skips Memo/File/Image; `SDK_COLUMN_TYPE` decides what an auto form layout places).
const at = a && (a.attributeType || a.AttributeType);
- const mapped = a && a.type ? a.type : SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at];
- const specType = TYPES_NEEDING_COMPANION_DATA.has(mapped) ? undefined : mapped;
+ // The option set's own type WINS over the attributeType map, because for a MultiChoice the map
+ // is wrong: Dataverse reports `Virtual`. `readOptionSets` always stamps `type` from the CAST
+ // that returned the row — even when the options themselves were unparseable — so this covers
+ // every attribute either cast saw.
+ //
+ // `choiceTypeFromTypeName` is deliberately NOT consulted here. It is load-bearing in the two
+ // FILTER decisions below (keeping a column the casts never returned, and not mistaking a real
+ // logical Choice for a shadow), but for the TYPE it would be redundant: whenever it could speak,
+ // either `os.type` already said the same thing, or there is no option set and the column is left
+ // untyped regardless. A mutation removing it from this expression was not detectable by any
+ // test, which is the signal that it was decoration rather than logic.
+ const os = (a && a.optionSet) || null;
+ const mapped = (a && a.type) || (os && os.type) || SPEC_TYPE_FROM_ATTRIBUTE_TYPE[at];
+ // Companion data for a Choice/MultiChoice (see TYPES_NEEDING_COMPANION_DATA). Present -> the
+ // column carries its REAL type plus the `options[]`/`globalChoice` its declaration requires.
+ // Absent -> it stays untyped and is named in the untyped-column warning, because emitting
+ // `type: "Choice"` with neither companion produces a spec that fails its own validation.
+ //
+ // `os.options` can be absent even when `os` exists: the cast identified the column but its
+ // labels were unreadable. That is deliberately treated as "no companion data" — the column is
+ // kept (it IS a real column) but left untyped.
+ const optionSet = TYPES_NEEDING_COMPANION_DATA.has(mapped) && os && Array.isArray(os.options) ? os : null;
+ // A shared set is REFERENCED, not inlined, so a rebuild binds all its columns to one option set
+ // instead of minting a private copy per column. An unnamed global set (no `Name` came back) has
+ // nothing to reference, so it degrades to inline options rather than emitting a dangling ref.
+ //
+ // INLINE labels are additionally screened for an AMBIGUOUS alias, and that screen is the
+ // difference between one bad column and no download at all. Option labels need not be unique
+ // across options OR languages in Dataverse, so `["Open", {1033:"Closed", 3082:"Open"}]` is legal
+ // — but "Open" then names two options, which `validateAppSpec` treats as an ERROR whenever
+ // either side is localized (the collision is invisible on the page, so it cannot be a warning).
+ // `runDownload` validates before writing and returns on failure, so emitting such a set aborted
+ // the ENTIRE app's download, and `--allow-lossy-download` does not bypass that gate. Refusing to
+ // type just this column falls back to the untyped warning that already exists for an unreadable
+ // label, which is what the download did before types were carried at all.
+ //
+ // The shared `ambiguousChoiceAliases` is reused rather than reimplemented, so this screen and
+ // the validator can never disagree about what "ambiguous" means.
+ const inlineOptions = optionSet && !(optionSet.isGlobal && optionSet.name)
+ ? optionSet.options.map(choiceOptionLabel)
+ : null;
+ const inlineIsAmbiguous = inlineOptions ? ambiguousChoiceAliases(inlineOptions).some((c) => c.hidden) : false;
+ const usableOptionSet = inlineIsAmbiguous ? null : optionSet;
+ const specType = TYPES_NEEDING_COMPANION_DATA.has(mapped) && !usableOptionSet ? undefined : mapped;
+ const choice = !usableOptionSet ? {}
+ : (usableOptionSet.isGlobal && usableOptionSet.name
+ ? { globalChoice: usableOptionSet.name }
+ : { options: inlineOptions });
return withDescription({
schemaName,
// A column labelled in several languages round-trips as an LCID map; one language stays a
@@ -783,6 +1061,7 @@ function entityFromMetadata(meta, logical) {
// right answer: Dataverse has none either.
...(columnDisplayName(a) !== undefined ? { displayName: columnDisplayName(a) } : {}),
...(specType ? { type: specType } : {}),
+ ...choice,
}, a && (a.description !== undefined ? a.description : a.Description));
}).filter((c) => c.schemaName);
// Table label + plural. When the table carries more than one language, BOTH must round-trip and
@@ -874,7 +1153,10 @@ async function readEntityWithDescriptions(sdk, logical) {
// as "column descriptions are best-effort" was right when descriptions were all it fetched, and
// became wrong the moment labels rode along — a 403 here returns a spec whose columns are
// single-language, with nothing saying so. Same recording, same reason.
- const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName`);
+ // `IsLogical` rides along for the synthetic-shadow filter in entityFromMetadata: a lookup's
+ // formatted-name attribute (`<lookup>name`) reports IsCustomAttribute TRUE and AttributeType
+ // String, so nothing else distinguishes it from a real Text column the author wrote.
+ const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeTypeName`);
if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');
const rows = res.body.value;
@@ -882,7 +1164,7 @@ async function readEntityWithDescriptions(sdk, logical) {
meta.attributes = (meta.attributes || []).map((a) => {
const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();
const row = byLogical.get(key);
- return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName } : a;
+ return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName, IsLogical: row.IsLogical, AttributeTypeName: row.AttributeTypeName } : a;
});
} catch (err) {
// Recorded, not swallowed — and it does NOT overwrite a table-level failure already recorded
@@ -892,6 +1174,28 @@ async function readEntityWithDescriptions(sdk, logical) {
meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
}
}
+ try {
+ // Choice / MultiChoice option sets (#564). A SEPARATE read from the attribute one above, and it
+ // has to be: `OptionSet` can only be `$expand`ed through a type CAST, which the heterogeneous
+ // `Attributes` collection cannot carry (see OPTION_SET_CASTS). Without it every Choice column
+ // downloads WITHOUT a type, and a rebuild into a FRESH environment creates it as single-line
+ // Text while a rebuild into the ORIGINAL environment silently reuses the real column — an
+ // asymmetry that is much harder to notice than an outright failure.
+ const { byLogical, failed } = await readOptionSets(sdk, logical);
+ // Merged onto the attribute list, never replacing it: the SDK's own projection supplies
+ // `attributeType`/`targets`, and the cast read returns ONLY picklist attributes.
+ meta.attributes = (meta.attributes || []).map((a) => {
+ const os = byLogical.get(String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase());
+ return os ? { ...a, optionSet: os } : a;
+ });
+ // A cast that failed is recorded WITHOUT discarding what the other one returned.
+ if (failed) meta.optionSetReadFailed = failed;
+ } catch (err) {
+ // Recorded, not swallowed. "This table has no Choice columns" and "the option-set read returned
+ // 403" are indistinguishable from the emitted spec — both yield untyped columns — so the reason
+ // has to travel back with the metadata or the caller reports a degrade it cannot explain.
+ meta.optionSetReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
+ }
return meta;
}
@@ -1258,6 +1562,14 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
// and the spec is usable, but only the SDK's flattened single-language `displayName` survived, so
// a multi-language table silently downloads as English-only. Reported rather than swallowed.
const labelReadFailures = new Map(); // logical -> reason
+ // Tables whose OPTION-SET read failed (#564). Kept apart from `labelReadFailures` for the same
+ // reason that one is kept apart from `metadataErrors`: the table is recovered and the spec is
+ // usable, but every Choice/MultiChoice column on it comes back untyped, so a cross-environment
+ // rebuild would create them as Text. Naming the reason is what makes that actionable.
+ const optionSetReadFailures = new Map(); // logical -> reason
+ // Shared option sets bound by a downloaded column, keyed by lower-cased name so a set used by
+ // several tables is declared once.
+ const globalChoiceDecls = new Map();
for (const logical of allLogicals) {
let e;
// A metadata READ failure is not the same as metadata that reports no primary name, and it must
@@ -1268,6 +1580,8 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
try {
const meta = await readEntityWithDescriptions(sdk, logical);
if (meta && meta.labelReadFailed) labelReadFailures.set(logical, meta.labelReadFailed);
+ if (meta && meta.optionSetReadFailed) optionSetReadFailures.set(logical, meta.optionSetReadFailed);
+ collectGlobalChoices(meta, globalChoiceDecls);
e = entityFromMetadata(meta, logical);
} catch (err) {
metadataErrors.set(logical, (err && err.message) || String(err));
@@ -1310,16 +1624,25 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
// English-only spec is still a usable spec, and failing a read-only command over it would be worse.
if (labelReadFailures.size) {
const detail = [...labelReadFailures.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, r]) => `${l} (${r})`).join(', ');
- process.stderr.write(`WARNING: a label read failed for ${labelReadFailures.size} table(s) (${detail}). The table AND COLUMN labels for those tables fall back to ONE language, so anything labelled in several languages downloads as single-language and a rebuild would recreate it that way. Re-run the download to recover the other languages before rebuilding into a different environment.\n`);
+ process.stderr.write(`WARNING: a label read failed for ${labelReadFailures.size} table(s) (${detail}). The table AND COLUMN labels for those tables fall back to ONE language, so anything labelled in several languages downloads as single-language and a rebuild would recreate it that way. That read also carries the flags that identify a lookup's synthetic '<lookup>name' column, so those tables may additionally have captured one as a real Text column — delete any you see before a cross-environment rebuild. Re-run the download to recover both.\n`);
}
- // A column whose App Spec type could not be substantiated — a Choice/MultiChoice (whose options
- // this download does not read) or an attribute type the spec cannot declare. Rebuilding into an
- // org that ALREADY has the table reuses the column and this is inert; rebuilding into a FRESH org
- // creates it as Text, because the data-model phase falls back to `c.type || 'Text'`. That silent
- // downgrade is the reason this is announced by name rather than left to be discovered later.
+ // #564: the option-set read is the ONLY source of a Choice/MultiChoice column's type. When it
+ // fails the table is still recovered and the spec still looks complete, but every choice column on
+ // it comes back untyped — so a rebuild into a FRESH environment creates them as Text. Reported
+ // with the reason, and separately from the untyped list below, because "we could not look" is a
+ // different fact from "this column has no substantiated type", and only the first is re-runnable.
+ if (optionSetReadFailures.size) {
+ const detail = [...optionSetReadFailures.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, r]) => `${l} (${r})`).join(', ');
+ process.stderr.write(`WARNING: the Choice/MultiChoice option-set read failed for ${optionSetReadFailures.size} table(s) (${detail}). Any choice column on those tables is captured WITHOUT its type or options, so rebuilding into a FRESH environment would create it as single-line Text. Re-run the download to recover them before a cross-environment rebuild.\n`);
+ }
+ // A column whose App Spec type could not be substantiated: a Choice/MultiChoice whose option set
+ // the read did not return (see the failure warning above), or an attribute type the spec cannot
+ // declare. Rebuilding into an org that ALREADY has the table reuses the column and this is inert;
+ // rebuilding into a FRESH org creates it as Text, because the data-model phase falls back to
+ // `c.type || 'Text'`. That silent downgrade is why this is announced by name.
const untyped = untypedColumnNames(entities);
if (untyped.length) {
- process.stderr.write(`WARNING: ${untyped.length} column(s) were captured WITHOUT a type (${untyped.join(', ')}) — most likely Choice/MultiChoice columns, whose options this download does not read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);
+ process.stderr.write(`WARNING: ${untyped.length} column(s) were captured WITHOUT a type (${untyped.join(', ')}) — most likely Choice/MultiChoice columns whose option set could not be read. Rebuilding this spec into an environment that already has the table is unaffected, but rebuilding into a FRESH environment would create them as single-line Text. Add the type and options[] (or a globalChoice reference) by hand before a cross-environment rebuild.\n`);
}
// App identity comes from the app's REAL, immutable uniquename (`appUnique`, captured from Dataverse as
@@ -1404,6 +1727,13 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
dashboards: async () => dashboards,
solution: async () => solution,
design: async () => (manifest ? manifest.design : undefined),
+ // #564: the shared option sets the downloaded columns bind to. Reduced to the sets an EMITTED
+ // column actually references (and canonicalized to one casing) — `globalChoiceDecls` is gathered
+ // from RAW metadata, which includes attributes later filtered out and tables later dropped, and
+ // every declaration here becomes a `createGlobalOptionSet` write in the target environment.
+ // Declared so a rebuild into a FRESH environment can create them — `createGlobalOptionSet` probes
+ // by Name and reuses, so declaring one the target org already has is a no-op, not a duplicate.
+ globalChoices: async () => finalizeGlobalChoices(entities, globalChoiceDecls),
// Captured on the way past so the role-restriction warning below can read it. The accessor stays
// a function (hydrateSpec's contract) and is still called exactly once, so this adds no query.
descriptionInventory: async () => {
@@ -1425,7 +1755,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
// reported failure was not that they are omitted — that is a documented limitation — but that
// NOTHING said so, so a second session reading the spec could not tell "this app has no views"
// from "this download does not carry views".
- const notRoundTripped = notRoundTrippedSummary(capturedInventory);
+ const notRoundTripped = notRoundTrippedSummary(roundTrippedAware(capturedInventory, globalChoiceDecls));
if (notRoundTripped) process.stderr.write(notRoundTrippedWarning(notRoundTripped));
const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);
const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];
@@ -1433,16 +1763,25 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- // parseArgs returns boolean true for a value-less flag. For value-bearing flags, treat that as
- // missing so `--env --app x` or `--out` reaches the usage guard instead of passing true into URL,
- // app-id, or path handling. `--allow-lossy-download` is a real boolean switch and stays true.
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const appArg = (typeof flags.app === 'string' ? flags.app : undefined) || (typeof positional[0] === 'string' ? positional[0] : undefined);
- const outArg = typeof flags.out === 'string' ? flags.out : (typeof flags.output === 'string' ? flags.output : undefined);
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node download-model-app.js --env <url> --app <appId|uniqueName|displayName> --out <dir> [--allow-lossy-download]';
+ // `--allow-lossy-download` is a real boolean switch, so it stays out of needValue; everything else
+ // feeds a URL, an app id, or a path and must not receive `true`.
+ const flagError = validateFlags(argv, {
+ known: ['env', 'app', 'out', 'output', 'allow-lossy-download'],
+ needValue: ['env', 'app', 'out', 'output'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const env = flags.env;
+ const appArg = flags.app || positional[0];
+ const outArg = flags.out || flags.output;
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|displayName> --out <dir> [--allow-lossy-download]\n');
+ if (!env || !appArg) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const outDir = path.resolve(outArg || '.');
@@ -1560,4 +1899,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { untypedColumnNames, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };
+module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode };
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index e95eba4eb..977f02121 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -234,6 +234,43 @@ function relationshipFor(spec, parentEntity, childEntity) {
);
}
+// Resolve WHICH 1:N relationship a sample-data `$parent` / `$parents` bind goes through.
+//
+// `relationshipFor` returns the FIRST OneToMany declared for the pair, which is right when there is
+// only one. A pair can legitimately have TWO — a hierarchy table with both a "parent org" and a
+// "group ancestor" self-lookup is the common shape, and self-referencing sample data (#544) makes
+// that shape reachable for the first time. Silently binding the first one links the rows through a
+// relationship the author did not mean, which asserts something false about the data and is
+// invisible in the build output. So an ambiguous bind is an error, and `$parent.lookup` (the
+// lookup's schemaName) is how an author resolves it.
+//
+// Returns { rel, error } and never throws: validateAppSpec pushes `error` at LINT time (the issue's
+// point — halting mid-build, after other data is written, is the worst outcome), and the runtime in
+// entity-provision.js throws it as a backstop for a build that skipped validation. One function so
+// the two cannot drift.
+function resolveParentRelationship(spec, parentEntity, childEntity, wanted) {
+ const p = String(parentEntity || '').toLowerCase();
+ const c = String(childEntity || '').toLowerCase();
+ const all = ((spec && spec.relationships) || []).filter(
+ (r) => r && r.type === 'OneToMany' &&
+ String(r.referenced || '').toLowerCase() === p &&
+ String(r.referencing || '').toLowerCase() === c
+ );
+ const nameOf = (r) => (r.lookup && r.lookup.schemaName) || '';
+ const listed = all.map(nameOf).filter(Boolean).map((n) => `'${n}'`).join(', ');
+ if (wanted !== undefined && wanted !== null && String(wanted).trim()) {
+ const want = String(wanted).trim().toLowerCase();
+ const hit = all.find((r) => nameOf(r).toLowerCase() === want);
+ if (hit) return { rel: hit, error: null };
+ // Name the valid options: the author already knows the name they typed, not the ones that exist.
+ return { rel: null, error: `binds parent '${parentEntity}' through lookup '${wanted}', which no OneToMany between them declares — valid: ${listed || '(none)'}` };
+ }
+ if (all.length > 1) {
+ return { rel: null, error: `declares a parent on '${parentEntity}', but ${all.length} OneToMany relationships connect them (${listed}) — the bind is ambiguous. Add "lookup": "<schemaName>" to say which one.` };
+ }
+ return { rel: all[0] || null, error: null };
+}
+
// The 1:N lookup columns a relationship places ON `entityLogical` (the referencing/child side).
// These lookups are NOT part of entities[].columns — they come from relationships[] — so form
// auto-layout and default-view enrichment call this to surface the parent links (otherwise the
@@ -2391,6 +2428,13 @@ function validateAppSpec(spec, opts = {}) {
errors.push(`sampleData['${k}']: no OneToMany relationship from ${key} '${p.entity}' to '${k}'`);
continue;
}
+ // Which relationship — an ambiguous pair, or a `lookup` naming none, is a build failure
+ // partway through the sample-data phase. Catch it here instead. #544.
+ const { error: relErr } = resolveParentRelationship(spec, p.entity, k, p.lookup);
+ if (relErr) {
+ errors.push(`sampleData['${k}']: ${key} ${relErr}`);
+ continue;
+ }
// The match must resolve to EXACTLY ONE parent sample record.
const pKey = Object.keys(spec.sampleData).find((kk) => kk.toLowerCase() === String(p.entity).toLowerCase());
const parentRecs = (pKey && Array.isArray(spec.sampleData[pKey])) ? spec.sampleData[pKey] : [];
@@ -2405,6 +2449,35 @@ function validateAppSpec(spec, opts = {}) {
}
}
}
+ // A SELF-reference cycle among this entity's own rows. The seeder creates self-referencing
+ // rows in waves (#544), so a row can point at an earlier one — but a cycle (including a row
+ // that is its own parent) can never be created in any order. Detecting it here keeps the
+ // build from halting partway through sample-data, after other data has already been written.
+ const selfIdx = v.map((rec) => {
+ if (!rec || typeof rec !== 'object') return [];
+ const binds = [].concat(rec.$parent !== undefined ? [rec.$parent] : [], Array.isArray(rec.$parents) ? rec.$parents : []);
+ return binds
+ .filter((p) => p && typeof p === 'object' && p.match && typeof p.match === 'object' && String(p.entity || '').toLowerCase() === k.toLowerCase())
+ .map((p) => v.findIndex((pr) => pr && typeof pr === 'object' && Object.entries(p.match).every(([mk, mv]) => {
+ const rk = Object.keys(pr).find((x) => x.toLowerCase() === mk.toLowerCase());
+ return rk !== undefined && pr[rk] === mv;
+ })))
+ .filter((i) => i >= 0);
+ });
+ if (selfIdx.some((s) => s.length)) {
+ const settled = new Array(v.length).fill(false);
+ let remaining = v.map((_, i) => i);
+ for (;;) {
+ const ready = remaining.filter((i) => selfIdx[i].every((p) => settled[p]));
+ if (!ready.length) break;
+ for (const i of ready) settled[i] = true;
+ const readySet = new Set(ready);
+ remaining = remaining.filter((i) => !readySet.has(i));
+ }
+ if (remaining.length) {
+ errors.push(`sampleData['${k}']: $parent cycle among its own rows (record index ${remaining.join(', ')}) — a row cannot be created before its parent. Break the cycle, or set the lookup after the build.`);
+ }
+ }
}
}
}
@@ -2859,6 +2932,7 @@ module.exports = {
normalizePageSource,
normalizeLanguageCode,
validateChoiceOptionLabels,
+ ambiguousChoiceAliases,
labelText,
labelAliases,
isLocalizedLabelMap,
@@ -2901,6 +2975,7 @@ module.exports = {
sampleRecordsFor,
resolveSampleRecords,
relationshipFor,
+ resolveParentRelationship,
lookupColumnsFor,
childRelationshipsFor,
relationshipSchemaName,
diff --git a/plugins/model-apps/scripts/lib/content-hash.js b/plugins/model-apps/scripts/lib/content-hash.js
index 025698733..6afde7a14 100644
--- a/plugins/model-apps/scripts/lib/content-hash.js
+++ b/plugins/model-apps/scripts/lib/content-hash.js
@@ -22,6 +22,8 @@
const { sha256 } = require('./hash.js');
const { normalizePageSource } = require('./app-spec.js');
+const fs = require('node:fs');
+const path = require('node:path');
// Resolve the on-disk source path a page's content lives at, or null for an intent (design-only) page
// that has nothing on disk to hash. Delegates to the canonical page-source normalizer so the legacy
@@ -70,4 +72,48 @@ function annotateContentHashes(spec, readFile) {
return clone;
}
-module.exports = { annotateContentHashes, pageContentPath };
+// Validate the on-disk half of every implemented page declaration. Schema validation proves a
+// `source.kind: "tsx"` page NAMES a confined codeFile; this proves the named file exists and is a
+// regular file before lint/preview/dry-run can call the page "implemented". `isFile` is injectable
+// so tests stay hermetic.
+function pageSourceFileErrors(spec, appDir, deps = {}) {
+ if (!spec || !Array.isArray(spec.pages) || !appDir) return [];
+ // Function shorthand is retained for existing tests/callers. In that injected mode realpath is
+ // identity unless supplied explicitly; production takes the object/default path and canonicalizes.
+ const isFile = typeof deps === 'function'
+ ? deps
+ : deps.isFile || ((absolutePath) => fs.statSync(absolutePath).isFile());
+ const realpath = typeof deps === 'function'
+ ? (absolutePath) => absolutePath
+ : deps.realpath || ((absolutePath) => (fs.realpathSync.native || fs.realpathSync)(absolutePath));
+ const root = path.resolve(appDir);
+ let realRoot;
+ try { realRoot = realpath(root); } catch { realRoot = root; }
+ const errors = [];
+ for (const page of spec.pages) {
+ const rel = pageContentPath(page);
+ if (!rel) continue;
+ const absolute = path.resolve(root, rel);
+ const confined = path.relative(root, absolute);
+ // Confinement is reported by validateAppSpec; do not touch an out-of-workspace path here.
+ if (confined === '..' || confined.startsWith(`..${path.sep}`) || path.isAbsolute(confined)) continue;
+ let exists = false;
+ try { exists = isFile(absolute) === true; } catch { exists = false; }
+ if (!exists) {
+ errors.push(`page '${page.key || page.name}': codeFile '${rel}' does not exist or is not a file`);
+ continue;
+ }
+ let realFile;
+ try { realFile = realpath(absolute); } catch {
+ errors.push(`page '${page.key || page.name}': codeFile '${rel}' does not exist or is not a file`);
+ continue;
+ }
+ const realRelative = path.relative(realRoot, realFile);
+ if (realRelative === '..' || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
+ errors.push(`page '${page.key || page.name}': codeFile '${rel}' resolves outside the workspace`);
+ }
+ }
+ return errors;
+}
+
+module.exports = { annotateContentHashes, pageContentPath, pageSourceFileErrors };
diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.js
index 6038237ad..3e789e4d1 100644
--- a/plugins/model-apps/scripts/lib/dataverse-auth.js
+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js
@@ -8,6 +8,7 @@ const { execFileSync } = require('child_process');
// Shared with the App Spec + CLI so the provisioned-language probe and the validator cannot disagree
// about what counts as an LCID. app-spec.js does not require this module, so there is no cycle.
const { normalizeLanguageCode } = require('./app-spec.js');
+const { nearestName } = require('./nearest-name.js');
/**
* Gets an Azure CLI access token for the given Dataverse environment URL.
@@ -526,6 +527,74 @@ function parseArgs(argv) {
return { positional, flags };
}
+/**
+ * Validates a CLI's raw argv against its declared flag contract.
+ * Returns a usage-error message, or null when the argv is acceptable.
+ *
+ * WHY this is shared rather than per-CLI: parseArgs accepts ANY `--name`, and an unrecognised flag
+ * both (a) disappears silently and (b) swallows the following token. On a phase-selecting build
+ * that combination is dangerous rather than merely untidy — measured on build-model-app.js,
+ * `--stage ui` plans 3 steps while the one-letter typo `--stagee ui` plans all 9 and still exits 0,
+ * so a caller who believed they had scoped an apply to the UI phases gets a full data-model apply
+ * against a live environment with no diagnostic. Every CLI in this directory had that hole; only
+ * lint-app-spec.js had grown its own guard, and a per-CLI guard is one each new CLI can forget.
+ *
+ * @param {string[]} argv process.argv.slice(2)
+ * @param {object} contract
+ * @param {Iterable<string>} contract.known every flag this CLI accepts, without the leading --
+ * @param {Iterable<string>} contract.needValue the subset that must carry a value
+ * @param {Object<string,string>} [contract.hints] per-flag text appended to a missing-value error,
+ * for flags whose accepted values are a closed set worth naming ("one of: design, plan, …").
+ * A generic "requires a value" is correct but strictly less useful than one that says what
+ * the value may be, and that detail should not be lost when a CLI adopts this helper.
+ * @returns {string|null}
+ */
+function validateFlags(argv, { known, needValue = [], hints = {} } = {}) {
+ const knownSet = known instanceof Set ? known : new Set(known);
+ const needValueSet = needValue instanceof Set ? needValue : new Set(needValue);
+ // A value-bearing flag that is not also accepted is a contradiction in the CLI's own declaration,
+ // and the likeliest cause is a rename applied to one list but not the other. Fail loudly at the
+ // call site rather than silently never enforcing the value requirement.
+ for (const n of needValueSet) {
+ if (!knownSet.has(n)) throw new Error(`validateFlags: '${n}' is in needValue but not in known`);
+ }
+
+ // Read names from argv rather than Object.keys(parseArgs(argv).flags): assigning to
+ // flags['__proto__'] goes through the inherited setter and never becomes an own property, so
+ // `--__proto__ deploy` would escape an own-keys allow-list AND swallow the next token.
+ const passed = [];
+ for (const a of argv) {
+ if (typeof a !== 'string' || !a.startsWith('--')) continue;
+ passed.push(a.slice(2).split('=')[0]);
+ }
+
+ // Unknown flags are reported BEFORE missing values, because an unknown flag consumes the next
+ // token: `--stagee ui --workspace` leaves --workspace looking value-less, and reporting that
+ // instead would name a symptom and hide the typo that caused it.
+ const unknown = [...new Set(passed.filter((k) => !knownSet.has(k)))];
+ if (unknown.length > 0) {
+ const parts = unknown.map((k) => {
+ const near = nearestName(k, knownSet);
+ return near && near !== k ? `--${k} (did you mean --${near}?)` : `--${k}`;
+ });
+ return `unknown flag(s): ${parts.join(', ')}`;
+ }
+
+ // parseArgs yields boolean `true` for a bare `--flag`, and '' for `--flag=` or `--flag ""`. For a
+ // value-taking flag all three are a caller who asked for something and did not say what; none may
+ // fall through to a default, which is how a bare `--only` became "select every phase".
+ const { flags } = parseArgs(argv);
+ for (const name of needValueSet) {
+ const v = flags[name];
+ if (v === undefined) continue; // absent is fine — whether it is REQUIRED is the caller's call
+ if (v === true || (typeof v === 'string' && !v.trim())) {
+ const hint = hints[name];
+ return `--${name} requires a value${hint ? ` — ${hint}` : ''}`;
+ }
+ }
+ return null;
+}
+
/**
* Read a flag that has both kebab-case and camelCase spellings, rejecting a conflicting pair.
*
@@ -616,6 +685,7 @@ module.exports = {
readProvisionedLanguages,
readOrgLanguageCode,
parseArgs,
+ validateFlags,
readAliasedFlag,
readJsonArg,
emitResult,
diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.js
index 4c7f10c10..82fdce83b 100644
--- a/plugins/model-apps/scripts/lib/entity-provision.js
+++ b/plugins/model-apps/scripts/lib/entity-provision.js
@@ -9,6 +9,7 @@ const {
sampleRecordsFor,
resolveSampleRecords,
relationshipFor,
+ resolveParentRelationship,
relationshipSchemaName,
manyToManySchemaName,
quickCreateEnabledFor,
@@ -855,6 +856,13 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
// outer entity loop is already sequential, so serial columns here means one metadata
// customization is in flight per entity at a time — the only order Dataverse permits.
const buildable = (e.columns || []).filter((c) => SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer');
+ const requiredDeclared = [
+ e.primaryAttribute,
+ ...buildable,
+ ].filter((c) => c && c.schemaName && hasExplicitRequired(c));
+ const capabilityDeclared = buildable.filter((c) => c.type !== 'Customer'
+ && (c.defaultValue !== undefined || c.integerFormat !== undefined
+ || c.isValidForCreate !== undefined || c.isValidForUpdate !== undefined || c.isValidForRead !== undefined));
for (const c of buildable) if (existingCols.has(c.schemaName.toLowerCase())) runner.skip('data-model', `column ${e.schemaName}.${c.schemaName} (exists)`);
const toCreate = buildable.filter((c) => !existingCols.has(c.schemaName.toLowerCase()));
const colResults = await runner.mapLimit(toCreate, 1, (c) => runner.run('data-model', `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})`,
@@ -864,10 +872,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
{ skipIf: isAlreadyExists }));
if (existingTable) {
const existingColMeta = new Map(existingColRows.map((c) => [String(c.logicalName || c.schemaName || '').toLowerCase(), c]));
- const requiredTargets = [
- e.primaryAttribute,
- ...buildable,
- ].filter((c) => c && c.schemaName && hasExplicitRequired(c) && existingCols.has(c.schemaName.toLowerCase()));
+ const requiredTargets = requiredDeclared.filter((c) => existingCols.has(c.schemaName.toLowerCase()));
const requiredLevels = new Map();
for (const c of requiredTargets) {
const current = columnRequiredLevel(existingColMeta.get(c.schemaName.toLowerCase()));
@@ -928,9 +933,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
// `updateColumn` refuses ANY change to a Customer column (measured — it throws "type
// 'Customer' not supported"), because Customer has no entry in the SDK's attribute-type ->
// OData-cast table (it is created through the wholly separate createCustomerColumn instead).
- const capabilityTargets = buildable.filter((c) => c.type !== 'Customer' && existingCols.has(c.schemaName.toLowerCase())
- && (c.defaultValue !== undefined || c.integerFormat !== undefined
- || c.isValidForCreate !== undefined || c.isValidForUpdate !== undefined || c.isValidForRead !== undefined));
+ const capabilityTargets = capabilityDeclared.filter((c) => existingCols.has(c.schemaName.toLowerCase()));
await runner.mapLimit(capabilityTargets, 1, (c) => {
const columnLogical = c.schemaName.toLowerCase();
const opts = {};
@@ -955,6 +958,16 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
);
});
}
+ for (const c of requiredDeclared) {
+ if (!existingTable || !existingCols.has(c.schemaName.toLowerCase())) {
+ runner.skip('data-model', `required ${e.schemaName}.${c.schemaName} (applied on create)`);
+ }
+ }
+ for (const c of capabilityDeclared) {
+ if (!existingTable || !existingCols.has(c.schemaName.toLowerCase())) {
+ runner.skip('data-model', `column capabilities ${e.schemaName}.${c.schemaName} (applied on create)`);
+ }
+ }
// Capture real column results (logicalName + metadataId)
toCreate.forEach((c, i) => {
const res = colResults[i];
@@ -1112,6 +1125,15 @@ function chooseMatchOn(e, seedRecords) {
return undefined;
}
+// Resolve WHICH 1:N relationship a `$parent` binds through, throwing the shared message.
+// `resolveParentRelationship` (app-spec.js) owns the rule and the wording so the lint-time gate and
+// this runtime backstop cannot drift; validateAppSpec normally catches these first. #544.
+function relationshipForParent(spec, parentEntity, childEntity, wanted) {
+ const { rel, error } = resolveParentRelationship(spec, parentEntity, childEntity, wanted);
+ if (error) throw new Error(`sample data for '${childEntity}' ${error}`);
+ return rel;
+}
+
function buildSeedGroup({ spec, e, records, statusReasonValues }) {
const resolved = resolveSampleRecords(e, records, spec);
const seedRecords = [];
@@ -1126,7 +1148,7 @@ function buildSeedGroup({ spec, e, records, statusReasonValues }) {
const parents = [].concat(raw && raw.$parent ? [raw.$parent] : [], (raw && raw.$parents) || []);
for (const parent of parents) {
if (!parent || !parent.entity || !parent.match) continue;
- const rel = relationshipFor(spec, parent.entity, e.schemaName);
+ const rel = relationshipForParent(spec, parent.entity, e.schemaName, parent.lookup);
const parentEntity = entityByLogical(spec, parent.entity);
// #1: fail loud on a bind that can't be formed instead of silently dropping it (which created
// the child with the lookup UNSET and still reported success). validateAppSpec catches these at
@@ -1156,6 +1178,47 @@ function buildSeedGroup({ spec, e, records, statusReasonValues }) {
return { entityLogical: e.schemaName.toLowerCase(), ...(matchOn ? { matchOn } : {}), records: seedRecords };
}
+// Order one entity's sample rows into WAVES by their SELF-references. #544.
+//
+// `seedRecordGraph` resolves EVERY bind in a group before creating ANY of that group's rows, and
+// publishes the group's ids only once it completes. Topological ordering BETWEEN entities (which
+// provisionSampleData already does) therefore cannot help WITHIN one: a `$parent` pointing at the
+// row's own entity always resolves against an id that does not exist yet, and the whole sample-data
+// phase halts — several phases into a build that has already written data. The App Spec cannot work
+// around it either, because the plugin, not the author, decides the grouping.
+//
+// So the plugin splits the group: wave N holds the rows whose self-parents all landed in an earlier
+// wave. Returns an array of waves, each an array of ORIGINAL record indices — original, because a
+// bind's `parentIndex` is an index into the entity's full sample list and that is what the SDK looks
+// up as `createdIds[entity][parentIndex]`.
+//
+// Returns a single wave when nothing self-references, which is the overwhelmingly common case and
+// must stay byte-identical to the previous one-call-per-entity behaviour.
+function selfReferenceWaves(entityLogical, records, labelFor) {
+ const selfParents = records.map((r) =>
+ (r.binds || []).filter((b) => b.parentEntity === entityLogical).map((b) => b.parentIndex));
+ if (!selfParents.some((p) => p.length)) return [records.map((_, i) => i)];
+
+ const waveOf = new Array(records.length).fill(-1);
+ const waves = [];
+ let remaining = records.map((_, i) => i);
+ while (remaining.length) {
+ const ready = remaining.filter((i) => selfParents[i].every((p) => waveOf[p] >= 0));
+ if (!ready.length) {
+ // Every remaining row is waiting on another remaining row: a cycle (including a row that is
+ // its own parent). Name the rows — "a cycle exists" is not actionable, and the author needs
+ // to know WHICH records to break. Failing here also beats looping forever.
+ const involved = remaining.map((i) => labelFor(i)).join(', ');
+ throw new Error(`sample data for '${entityLogical}' has a $parent cycle among its own rows (${involved}) — a row cannot be created before its parent. Break the cycle, or set the lookup after the build.`);
+ }
+ const readySet = new Set(ready);
+ for (const i of ready) waveOf[i] = waves.length;
+ waves.push(ready);
+ remaining = remaining.filter((i) => !readySet.has(i));
+ }
+ return waves;
+}
+
// Create sample rows topologically via the SDK's record-graph seeder. The plugin owns the App
// Spec translation (buildSeedGroup); the SDK owns @odata.bind formation and resolve-by-name
// idempotency. Groups are seeded one entity at a time (preserving the per-entity progress emit),
@@ -1183,14 +1246,46 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })
if (!group.matchOn && group.records.length > 0) {
process.stderr.write(`WARNING: sample rows for ${e.schemaName} have no idempotency key (no single-column alternate key, and not every row has a non-empty ${e.primaryAttribute.schemaName}) — a re-run or a retried insert will DUPLICATE these ${group.records.length} row(s). Add a single-column alternate key or give every row a unique ${e.primaryAttribute.schemaName} value.\n`);
}
- const { createdIds: made } = await sdk.seedRecordGraph([group], { entitySetFor, createdIds });
- Object.assign(createdIds, made);
- result.records[e.schemaName] = made[e.schemaName.toLowerCase()];
+ const logical = e.schemaName.toLowerCase();
+ // #544: seed in waves when rows reference their OWN entity. `waves` is [[0,1,2,...]] — one
+ // wave holding every row in order — unless a self-reference exists, so the common path below
+ // is exactly the single call it has always been.
+ const waves = selfReferenceWaves(logical, group.records, (i) => {
+ const name = records[i] && records[i][e.primaryAttribute.schemaName];
+ return name ? `'${name}'` : `record[${i}]`;
+ });
+
+ if (waves.length === 1) {
+ const { createdIds: made } = await sdk.seedRecordGraph([group], { entitySetFor, createdIds });
+ Object.assign(createdIds, made);
+ result.records[e.schemaName] = made[logical];
+ return;
+ }
+
+ // Ids indexed by ORIGINAL record position — the index a bind's `parentIndex` carries, and the
+ // index the SDK reads as createdIds[entity][parentIndex]. A wave-local array would misresolve
+ // every self-bind, silently linking rows to the wrong parents.
+ const idsByIndex = new Array(group.records.length);
+ for (const wave of waves) {
+ const waveGroup = { ...group, records: wave.map((i) => group.records[i]) };
+ const { createdIds: made } = await sdk.seedRecordGraph([waveGroup], {
+ entitySetFor,
+ // The SDK prefers ids created in the CURRENT call over these, but it publishes those only
+ // after a group completes — so during bind resolution this array is what a self-bind sees.
+ createdIds: { ...createdIds, [logical]: idsByIndex },
+ });
+ const madeIds = made[logical] || [];
+ wave.forEach((original, k) => { idsByIndex[original] = madeIds[k]; });
+ // A group only ever creates its own entity, but merge anything else the SDK reports rather
+ // than dropping it on the floor.
+ for (const [k, v] of Object.entries(made)) if (k !== logical) createdIds[k] = v;
+ }
+ createdIds[logical] = idsByIndex;
+ result.records[e.schemaName] = idsByIndex;
});
}
-
// Return entitySetFor closure so later phases can resolve entity-set names
return { records: result.records, entitySetFor };
}
-module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages };
+module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
index fe45e03ef..5ab43d0d4 100644
--- a/plugins/model-apps/scripts/lib/feature-flags.js
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -3,14 +3,19 @@
// Central feature-flag gate for the /genpage skill.
//
-// WHY: connector support spans three repos that ship on independent cadences —
-// the pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX
-// authoring control (power-platform-ux), and the maker/admin ECS setting. Until
-// ALL of them are live in PROD, the skill must behave exactly as it did before
-// connectors existed. A committed, default-OFF flag lets us merge the skill code
+// WHY: a GenPage capability typically spans several repos that ship on independent
+// cadences — a pac CLI verb, a host/authoring runtime, and a maker/admin ECS setting.
+// Until ALL of them are live in PROD, the skill must behave exactly as it did before
+// the capability existed. A committed, default-OFF flag lets us merge the skill code
// ahead of GA and flip it on in a one-line follow-up PR (or per-run via env var)
// once the dependencies are released — instead of carrying an un-merged branch.
//
+// A GA flag is flipped to `true` FIRST and removed in a later change, not both at once.
+// Flipping is reversible in one line if the rollout turns out to be incomplete in some
+// tenant; deleting the gate in the same change that enables the feature leaves no way
+// back except a revert. `connectors` is in that window now: GA, shipping `true`, gate
+// retained as a rollback switch.
+//
// Precedence (highest first), mirroring the telemetry opt-out convention in
// AGENTS.md where an env var overrides committed config:
// 1. env var GENPAGE_ENABLE_<FLAG> (e.g. GENPAGE_ENABLE_CONNECTORS)
@@ -61,7 +66,7 @@ function readFlagsFile(flagsPath) {
/**
* Returns whether a named feature flag is enabled.
*
- * @param {string} flag Flag name (e.g. 'connectors').
+ * @param {string} flag Flag name (e.g. 'custom-api').
* @param {object} [opts]
* @param {NodeJS.ProcessEnv} [opts.env] Env source (defaults to process.env).
* @param {object} [opts.flags] Pre-loaded flags map (skips file read).
@@ -94,7 +99,7 @@ function isCustomApiEnabled(opts) {
// metadata (what it enables, what it depends on, how to turn it on).
const FLAGS = {
connectors: {
- status: 'in-progress',
+ status: 'ga',
summary:
'GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) ' +
'and ALM packaging of connection references.',
@@ -140,6 +145,11 @@ const KNOWN_FLAGS = Object.keys(FLAGS);
// keeps the disabled message and exit code (3 = "feature off", distinct from
// 1 = runtime/usage error) consistent and prevents drift. `exit`/`write` are
// injectable for unit testing.
+//
+// connectors is GA and ships ON, so this normally does nothing. It is retained for one
+// release as the rollback path: if the cross-repo dependencies turn out to be incomplete
+// in some tenant, `"connectors": false` restores the previous behaviour in one line
+// rather than requiring a revert.
function exitIfConnectorsDisabled(opts = {}) {
const exit = opts.exit || process.exit;
const write = opts.write || ((s) => process.stderr.write(s));
@@ -151,8 +161,10 @@ function exitIfConnectorsDisabled(opts = {}) {
}
// Fail-closed gate shared by every Custom API (Dataverse Action/Function) script entry
-// point. Mirrors exitIfConnectorsDisabled so both features gate the same way: exit 3 =
-// "feature off" (distinct from 1 = runtime/usage error). `exit`/`write` are injectable for tests.
+// point: exit 3 = "feature off", distinct from 1 = runtime/usage error, so a caller can tell
+// "not released" from "it broke". Centralizing it (instead of each script inlining the same
+// `if (!isCustomApiEnabled()) exit 3`) keeps the disabled message and exit code consistent and
+// prevents drift. `exit`/`write` are injectable for unit testing.
function exitIfCustomApiDisabled(opts = {}) {
const exit = opts.exit || process.exit;
const write = opts.write || ((s) => process.stderr.write(s));
@@ -202,16 +214,16 @@ function validateFlags(flags) {
function connectorsDisabledMessage() {
return (
'Connector support is disabled (feature flag "connectors" is OFF). ' +
- 'GenPage connectors require the pac CLI connector verbs, the GenUX authoring ' +
- 'control, and the maker/admin setting to all be live in PROD. To enable for a ' +
- 'single run set GENPAGE_ENABLE_CONNECTORS=1, or flip "connectors" to true in ' +
- 'plugins/model-apps/feature-flags.json once the dependencies are released.'
+ 'It is GA and ships ON, so this means it was explicitly turned off — either ' +
+ 'GENPAGE_ENABLE_CONNECTORS=0 in this environment, or "connectors": false in ' +
+ 'plugins/model-apps/feature-flags.json. Set it back to true (or unset the env var) ' +
+ 'to re-enable connector authoring.'
);
}
// Standard operator-facing message printed when a Custom API entrypoint is invoked while
-// the flag is OFF. Centralized (mirrors connectorsDisabledMessage) so every Custom API
-// script speaks with one voice about why it stopped and how to turn the feature on.
+// the flag is OFF. Centralized so every Custom API script speaks with one voice about why it
+// stopped and how to turn the feature on.
function customApiDisabledMessage() {
return (
'Dataverse Custom API support is disabled (feature flag "custom-api" is OFF). ' +
diff --git a/plugins/model-apps/scripts/lib/genpage-cli.js b/plugins/model-apps/scripts/lib/genpage-cli.js
index a6f4a2884..dab5c3a6d 100644
--- a/plugins/model-apps/scripts/lib/genpage-cli.js
+++ b/plugins/model-apps/scripts/lib/genpage-cli.js
@@ -3,12 +3,17 @@
// to author/deploy generative pages. Page CONTENT only: uploads run WITHOUT --add-to-sitemap because
// the SDK owns the sitemap (it writes the GenPage subareas). Real impl spawns pac; tests inject `run`.
const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
// Quote an arg for a Windows/POSIX shell command line (needed because pac resolves as pac.cmd on
// Windows, which requires shell:true — and shell:true does not quote an args array). Embedded
-// newlines terminate the command line (pac then sees a truncated command and dumps its help), so
-// collapse them to spaces first — downloaded page prompts are multi-line ("Conversation with N
-// prompts:\r\n1. …\r\n2. …") and would otherwise break the upload on an edit-rebuild.
+// newlines terminate the Windows command line (pac then sees a truncated command and dumps its
+// help), so collapse them to spaces first. This is now purely a DEFENSIVE net for whatever args
+// still flow inline — e.g. a page --name; it is NOT how multi-line prompts survive. upload() passes
+// the prompt and agent-message to pac BY FILE (--prompt-file/--agent-message-file) precisely because
+// collapsing THEIR newlines was lossy (a downloaded prompt is a multi-line conversation transcript).
function quoteArg(a) {
const s = String(a).replace(/\r\n|[\r\n]/g, ' ');
const q = s.replace(/"/g, '""').replace(/%/g, '"^%"');
@@ -20,10 +25,11 @@ function quoteArg(a) {
// Build the spawnSync invocation for a `pac` call, per platform. Windows: pac resolves as pac.cmd,
// which requires a shell; shell:true ignores an args array, so pass a single cmd-quoted command
// line ("" escapes an embedded quote). POSIX: spawn pac directly with the args array (no shell) so
-// embedded quotes and other shell metacharacters in prompts round-trip verbatim instead of being
-// mangled by cmd-style quoting. Embedded newlines are collapsed to spaces on every arg first (they
-// truncate the command line on Windows and confuse pac's parsing) — downloaded page prompts are
-// multi-line and would otherwise break the upload on an edit-rebuild.
+// embedded quotes and other shell metacharacters round-trip verbatim instead of being mangled by
+// cmd-style quoting. Embedded newlines are still collapsed to spaces on every arg — a DEFENSIVE net
+// for any arg that still flows inline (e.g. a page --name), since a newline truncates the Windows
+// command line. It is no longer relied on for prompts: upload() passes prompt/agent-message via file
+// precisely because collapsing THEIR newlines was lossy for multi-line transcripts.
function buildPacInvocation(args, platform = process.platform) {
const clean = args.map((a) => String(a).replace(/\r\n|[\r\n]/g, ' '));
if (platform === 'win32') {
@@ -209,76 +215,105 @@ function makeGenpageCli(env, deps = {}) {
// newIds.length > 1 → THROW (ambiguous; concurrent creates or noise — never guess)
// NO name matching anywhere in recovery (names are unreliable — app-scoped list misses
// pre-sitemap pages; env-wide names drift with sitemap titles). Any enumerateEnv failure → THROW.
- async upload({ appId, pageId, codeFile, name, prompt, agentMessage, dataSources }) {
- const once = async (pid) => {
- const args = ['model', 'genpage', 'upload', '--environment', env, '--app-id', appId, '--code-file', codeFile];
- if (pid) args.push('--page-id', pid);
- if (name) args.push('--name', name);
- // pac requires BOTH --prompt and --agent-message for a new page.
- args.push('--prompt', prompt && String(prompt).trim() ? String(prompt) : `Generative page ${name || ''}`.trim());
- args.push('--agent-message', agentMessage && String(agentMessage).trim() ? String(agentMessage) : 'Authored by app-builder');
- if (dataSources && dataSources.length) args.push('--data-sources', dataSources.join(','));
- return run(args);
- };
- let pid = pageId;
- let lastErr = '';
- // Snapshot taken once (lazily on the first CREATE attempt) so the before/after diff is anchored
- // to the exact env state before this operation. Fail-closed: if we can't snapshot, we can't
- // safely attribute a later uncertain result — halt to prevent a blind duplicate.
- let beforeIds = null;
- for (let i = 0; i < attempts; i += 1) {
- if (!pid && name && beforeIds === null) {
- const before = await enumerateEnv();
- if (!before.ok) {
- throw new Error(
- `pac genpage upload for '${name}': cannot snapshot the environment before create (${before.error}) — refusing to create (would risk a duplicate)`
- );
- }
- beforeIds = new Set(before.ids);
- }
- const r = await once(pid);
- if (r.status === 0) {
- const id = parsePageId(r.stdout);
- if (id) {
- // I7 guard: when performing an UPDATE (pid is set — whether caller-provided or adopted after
- // uncertain-CREATE reconciliation), the returned Page ID MUST equal the pid we used. A mismatch
- // means pac silently operated on a different page — halt rather than let a wrong record persist.
- // Case-insensitive: PAC can normalize GUID casing across writes.
- if (pid && id.toLowerCase() !== pid.toLowerCase()) {
+ async upload({ appId, pageId, codeFile, compiledCodeFile, name, prompt, agentMessage, dataSources }) {
+ // pac REQUIRES both a prompt and an agent-message for a new page. Resolve the effective text
+ // (preserving the historical defaults) ONCE, then hand both to pac BY FILE via --prompt-file /
+ // --agent-message-file rather than inline --prompt / --agent-message. A downloaded page prompt is
+ // a multi-line conversation transcript ("Conversation with N prompts:\r\n1. …\r\n2. …"); passed
+ // inline it hits the newline-collapsing in quoteArg/buildPacInvocation (a defensive guard so a
+ // stray newline can't truncate the Windows command line) and silently loses every line break on
+ // an edit-rebuild. A file round-trips the text verbatim. See `pac model genpage upload --help`.
+ const promptText = prompt && String(prompt).trim() ? String(prompt) : `Generative page ${name || ''}`.trim();
+ const agentMessageText = agentMessage && String(agentMessage).trim() ? String(agentMessage) : 'Authored by app-builder';
+ // Write both files ONCE, before the retry loop, into a unique temp dir. mkdtempSync's random
+ // suffix keeps concurrent uploads from colliding on a fixed filename. UTF-8 because prompts carry
+ // non-ASCII (pac reads these back as UTF-8). The try/finally guarantees the dir is removed on
+ // EVERY exit below — the success return, the retry-exhaustion throw, and the mid-loop throws.
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-upload-'));
+ const promptFile = path.join(tmpDir, 'prompt.txt');
+ const agentMessageFile = path.join(tmpDir, 'agent-message.txt');
+ try {
+ fs.writeFileSync(promptFile, promptText, 'utf8');
+ fs.writeFileSync(agentMessageFile, agentMessageText, 'utf8');
+ const once = async (pid) => {
+ const args = ['model', 'genpage', 'upload', '--environment', env, '--app-id', appId, '--code-file', codeFile];
+ if (pid) args.push('--page-id', pid);
+ // Optional pre-compiled JavaScript. When omitted, pac auto-transpiles the TypeScript (the
+ // live-verified path the plugin uses today) — so only add the flag when the caller supplies one.
+ if (compiledCodeFile) args.push('--compiled-code-file', compiledCodeFile);
+ if (name) args.push('--name', name);
+ // pac requires BOTH for a new page; delivered by file (see above) so a multi-line
+ // prompt/agent-message round-trips intact instead of being newline-collapsed.
+ args.push('--prompt-file', promptFile);
+ args.push('--agent-message-file', agentMessageFile);
+ if (dataSources && dataSources.length) args.push('--data-sources', dataSources.join(','));
+ return run(args);
+ };
+ let pid = pageId;
+ let lastErr = '';
+ // Snapshot taken once (lazily on the first CREATE attempt) so the before/after diff is anchored
+ // to the exact env state before this operation. Fail-closed: if we can't snapshot, we can't
+ // safely attribute a later uncertain result — halt to prevent a blind duplicate.
+ let beforeIds = null;
+ for (let i = 0; i < attempts; i += 1) {
+ if (!pid && name && beforeIds === null) {
+ const before = await enumerateEnv();
+ if (!before.ok) {
throw new Error(
- `pac genpage upload for '${name}': UPDATE returned an unexpected Page ID (got ${id}, expected ${pid}) — refusing to persist a mismatched update`
+ `pac genpage upload for '${name}': cannot snapshot the environment before create (${before.error}) — refusing to create (would risk a duplicate)`
);
}
- return { pageId: id };
- }
- lastErr = `returned no Page ID: ${lastLine(r)}`;
- } else {
- lastErr = lastLine(r);
- }
- // Uncertain CREATE: no caller pid and result was non-zero or zero-without-Page-ID.
- // Strict env-wide before/after id diff — never use name matching (names drift; app-scoped
- // lists miss pre-sitemap pages; a page's list "Name" is its sitemap title, not its identity).
- if (!pid && name) {
- const after = await enumerateEnv();
- if (!after.ok) {
- throw new Error(
- `pac genpage upload for '${name}' had an uncertain result and env enumeration failed — refusing to retry (would risk a duplicate): ${after.error}`
- );
+ beforeIds = new Set(before.ids);
}
- const newIds = after.ids.filter((id) => !beforeIds.has(id));
- if (newIds.length === 1) {
- pid = newIds[0]; // CREATE landed → adopt; I7 guard verifies returned id on the UPDATE
- } else if (newIds.length === 0) {
- // CREATE did NOT land → safe to retry (pid stays undefined; beforeIds unchanged)
+ const r = await once(pid);
+ if (r.status === 0) {
+ const id = parsePageId(r.stdout);
+ if (id) {
+ // I7 guard: when performing an UPDATE (pid is set — whether caller-provided or adopted after
+ // uncertain-CREATE reconciliation), the returned Page ID MUST equal the pid we used. A mismatch
+ // means pac silently operated on a different page — halt rather than let a wrong record persist.
+ // Case-insensitive: PAC can normalize GUID casing across writes.
+ if (pid && id.toLowerCase() !== pid.toLowerCase()) {
+ throw new Error(
+ `pac genpage upload for '${name}': UPDATE returned an unexpected Page ID (got ${id}, expected ${pid}) — refusing to persist a mismatched update`
+ );
+ }
+ return { pageId: id };
+ }
+ lastErr = `returned no Page ID: ${lastLine(r)}`;
} else {
- throw new Error(
- `pac genpage upload for '${name}': ${newIds.length} new pages appeared after an uncertain create — cannot attribute (ambiguous)`
- );
+ lastErr = lastLine(r);
+ }
+ // Uncertain CREATE: no caller pid and result was non-zero or zero-without-Page-ID.
+ // Strict env-wide before/after id diff — never use name matching (names drift; app-scoped
+ // lists miss pre-sitemap pages; a page's list "Name" is its sitemap title, not its identity).
+ if (!pid && name) {
+ const after = await enumerateEnv();
+ if (!after.ok) {
+ throw new Error(
+ `pac genpage upload for '${name}' had an uncertain result and env enumeration failed — refusing to retry (would risk a duplicate): ${after.error}`
+ );
+ }
+ const newIds = after.ids.filter((id) => !beforeIds.has(id));
+ if (newIds.length === 1) {
+ pid = newIds[0]; // CREATE landed → adopt; I7 guard verifies returned id on the UPDATE
+ } else if (newIds.length === 0) {
+ // CREATE did NOT land → safe to retry (pid stays undefined; beforeIds unchanged)
+ } else {
+ throw new Error(
+ `pac genpage upload for '${name}': ${newIds.length} new pages appeared after an uncertain create — cannot attribute (ambiguous)`
+ );
+ }
}
+ if (i < attempts - 1) await sleep(500 * (i + 1));
}
- if (i < attempts - 1) await sleep(500 * (i + 1));
+ throw new Error(`pac genpage upload failed for '${name}' after ${attempts} attempt(s): ${lastErr}`);
+ } finally {
+ // Best-effort cleanup on EVERY exit path (success return, retry-exhaustion throw, mid-loop
+ // throws). A cleanup failure (e.g. a transient Windows file lock) must NEVER mask the upload's
+ // own error, so swallow it. force:true also ignores an already-removed dir.
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore cleanup errors */ }
}
- throw new Error(`pac genpage upload failed for '${name}' after ${attempts} attempt(s): ${lastErr}`);
},
list({ appId }) {
return listPages(appId);
diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.js
index c1a86375f..0d859df47 100644
--- a/plugins/model-apps/scripts/lib/hydrate-spec.js
+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js
@@ -120,6 +120,10 @@ async function hydrateSpec(read) {
void prefixResolved;
// `design` is threaded through from the page manifest (§7.3) when present; undefined for legacy apps.
const design = read.design ? await read.design() : undefined;
+ // #564: shared option sets bound by a downloaded Choice/MultiChoice column. Emitted only when the
+ // app actually binds one — an empty `globalChoices: []` on every other download would read as a
+ // positive claim that the app uses no shared choices, which this download cannot substantiate.
+ const globalChoices = read.globalChoices ? ((await read.globalChoices()) || []) : [];
const descriptionInventory = read.descriptionInventory ? sanitizeDescriptionInventory(await read.descriptionInventory()) : undefined;
// When downloaded pages carry stable keys (assigned by assignPageKeys), emit the v2 shape;
// legacy callers without keys fall back to the name-based shape for back-compat.
@@ -206,6 +210,7 @@ async function hydrateSpec(read) {
...(typeof app.headerNavigationRefresh === 'boolean' ? { headerNavigationRefresh: app.headerNavigationRefresh } : {}),
},
entities,
+ ...(globalChoices.length ? { globalChoices } : {}),
webResources,
views: [],
// NOT reconstructed (documented limitation): views, charts, forms, and commands. VIEWS were
diff --git a/plugins/model-apps/scripts/lib/interaction-mode.js b/plugins/model-apps/scripts/lib/interaction-mode.js
new file mode 100644
index 000000000..93dad5e5f
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/interaction-mode.js
@@ -0,0 +1,52 @@
+'use strict';
+
+// Whether a human is reachable on the other end of this run.
+//
+// WHY this is shared rather than decided per skill: `/app-builder` and `/genpage` both have
+// gates that must behave differently when nobody can answer, and a second, subtly different
+// definition of "unattended" is exactly how one skill ends up waiting forever on a host where
+// the other correctly proceeded. One definition, one place.
+//
+// The host matters here as much as the flags. Copilot CLI autopilot and Claude Code's
+// auto-accept both drive these skills with **no user watching**, so a gate that is specified
+// as "ask the user" has no answer to wait for: the run either stalls or, worse, records an
+// answer nobody gave. Detecting the mode is what lets a gate choose a documented default
+// instead of inventing one.
+
+// Env var truthiness for the unattended opt-in: '1' or 'true' (case-insensitive) count as set;
+// a missing or other value is false. Matches the dotnet-style boolean env convention used
+// elsewhere in this repo (see AGENTS.md "Shared Telemetry").
+function envTruthy(v) {
+ if (v == null) return false;
+ const s = String(v).trim().toLowerCase();
+ return s === '1' || s === 'true';
+}
+
+// The repo-wide unattended opt-in. Named once here so a caller cannot typo it into a silent
+// "attended" result — the failure mode of a mistyped env var is a run that hangs on a prompt
+// nobody sees, which looks like a hang rather than a configuration error.
+const NONINTERACTIVE_ENV = 'POWER_PLATFORM_SKILLS_NONINTERACTIVE';
+
+// Resolve the mode from an explicit flag first, then the env var, then default to attended.
+//
+// Defaulting to ATTENDED is deliberate: assuming a human is present makes an unattended run
+// stall visibly, whereas assuming one is absent makes an attended run silently skip the
+// questions the user expected to be asked. A stall is reported; a skipped question is not.
+//
+// SUPPRESSION ONLY. Being unattended never grants destructive authority — that stays gated on
+// an explicit `--allow-destructive`, because "nobody is watching" is the opposite of
+// "everyone consented".
+function resolveInteractionMode(opts = {}) {
+ const argv = Array.isArray(opts.argv) ? opts.argv : [];
+ const env = opts.env || process.env;
+
+ if (argv.includes('--non-interactive')) {
+ return { interactive: false, reason: '--non-interactive flag' };
+ }
+ if (envTruthy(env[NONINTERACTIVE_ENV])) {
+ return { interactive: false, reason: `${NONINTERACTIVE_ENV} is set` };
+ }
+ return { interactive: true, reason: 'default (attended)' };
+}
+
+module.exports = { envTruthy, resolveInteractionMode, NONINTERACTIVE_ENV };
diff --git a/plugins/model-apps/scripts/lib/nearest-name.js b/plugins/model-apps/scripts/lib/nearest-name.js
new file mode 100644
index 000000000..a1a6f22e6
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/nearest-name.js
@@ -0,0 +1,44 @@
+// plugins/model-apps/scripts/lib/nearest-name.js
+// Shared "did you mean" matcher for closed vocabularies (CLI flag names, FetchXML operators).
+'use strict';
+
+/**
+ * Returns the entry of `known` closest to `name`, or null when nothing is within one edit.
+ *
+ * An exact (case-insensitive) match wins outright, so a caller can use this both to canonicalize a
+ * name it already accepts and to suggest a correction for one it does not.
+ *
+ * The distance bound is a single edit, deliberately, and not full Levenshtein. The only suggestion
+ * worth making is a one-character slip — `--stagee` for `--stage`, `eq-businesid` for
+ * `eq-businessid`. At two edits the nearest entry is about as likely to be the wrong one as the
+ * right one, and a wrong suggestion is worse than none: it sends the reader to a flag or operator
+ * that silently does something else.
+ *
+ * @param {string} name the name the user actually typed
+ * @param {Iterable<string>} known the accepted vocabulary, in lower case
+ * @returns {string|null}
+ */
+function nearestName(name, known) {
+ const lower = String(name).toLowerCase();
+ for (const k of known) if (k === lower) return k;
+ for (const k of known) {
+ // A single edit can change a length by at most one, so anything further apart cannot match and
+ // does not need the walk below.
+ if (Math.abs(k.length - lower.length) > 1) continue;
+ // Walk both strings once, allowing a single edit (substitution when the lengths are equal,
+ // otherwise an insertion into whichever string is shorter).
+ let i = 0, j = 0, edits = 0;
+ while (i < k.length && j < lower.length) {
+ if (k[i] === lower[j]) { i++; j++; continue; }
+ if (++edits > 1) break;
+ if (k.length > lower.length) i++;
+ else if (k.length < lower.length) j++;
+ else { i++; j++; }
+ }
+ // Whatever is left unconsumed on either side counts against the same single-edit budget.
+ if (edits + (k.length - i) + (lower.length - j) <= 1) return k;
+ }
+ return null;
+}
+
+module.exports = { nearestName };
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 267205e0f..1561750a1 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -52,6 +52,10 @@ const {
provisionSampleData,
BuildHalt: _BuildHalt,
SDK_COLUMN_TYPE: _SDK_COLUMN_TYPE,
+ findExistingTable,
+ findExistingColumns,
+ relationshipExists,
+ localizedLabelLcidsInSpec,
} = require('./entity-provision.js');
// Pure App Spec -> canonical SDK intent compiler (new form topology + generic-surface intents).
const {
@@ -338,6 +342,12 @@ function planFor(spec, opts) {
const sol = spec.solution;
if (has('solution')) items.push({ phase: 'solution', label: `solution ${sol.uniqueName} (publisher ${sol.publisherPrefix})` });
if (has('data-model')) {
+ // The relationship probe identity must match the one the APPLY path uses, or an existing
+ // relationship reads as `create`. `provisionDataModel` queries the REFERENCED (parent) entity's
+ // OneToManyRelationships — the child's collection does not contain it — and builds the schema
+ // name WITH the publisher prefix. Getting either wrong is invisible for a self-referencing
+ // relationship (referenced === referencing), which is exactly the shape this was first tested on.
+ const relPrefix = spec.solution && spec.solution.publisherPrefix;
for (const gc of spec.globalChoices || []) items.push({ phase: 'data-model', label: `global choice ${gc.name}` });
for (const e of spec.entities) {
// `labelText` returns "" for an absent displayName, or for a localized map with nothing usable
@@ -345,17 +355,36 @@ function planFor(spec, opts) {
// has to decode. Fall back to the schema name, which is what the CREATE itself falls back to
// (`displayName || schemaName`), so the plan says what the build will actually do.
const shown = labelText(e.displayName, spec && spec.languageCode) || e.schemaName;
- items.push({ phase: 'data-model', label: `table ${e.schemaName} ("${shown}")` });
+ items.push({ phase: 'data-model', label: `table ${e.schemaName} ("${shown}")`, key: { kind: 'table', entity: e.schemaName } });
if (quickCreateEnabledFor(spec, e)) items.push({ phase: 'data-model', label: `enable quick create on ${e.schemaName.toLowerCase()}` });
for (const c of e.columns || []) {
- if (SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer') items.push({ phase: 'data-model', label: `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})` });
+ if (SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer') items.push({ phase: 'data-model', label: `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})`, key: { kind: 'column', entity: e.schemaName, name: c.schemaName } });
+ }
+ const buildable = (e.columns || []).filter((c) => SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer');
+ for (const c of [e.primaryAttribute, ...buildable]) {
+ if (c && c.schemaName && Object.prototype.hasOwnProperty.call(c, 'required')) {
+ items.push({ phase: 'data-model', label: `required ${e.schemaName}.${c.schemaName}` });
+ }
+ }
+ for (const c of buildable) {
+ if (c.type !== 'Customer' && (
+ c.defaultValue !== undefined || c.integerFormat !== undefined
+ || c.isValidForCreate !== undefined || c.isValidForUpdate !== undefined || c.isValidForRead !== undefined
+ )) {
+ items.push({ phase: 'data-model', label: `column capabilities ${e.schemaName}.${c.schemaName}` });
+ }
+ }
+ for (const c of e.columns || []) {
+ if (c && c.schemaName && c.visualization !== undefined) {
+ items.push({ phase: 'data-model', label: `visualization ${e.schemaName}.${c.schemaName} (${c.visualization})` });
+ }
}
for (const sr of e.statusReasons || []) items.push({ phase: 'data-model', label: `status reason ${e.schemaName}: ${sr.label}` });
for (const k of e.alternateKeys || []) items.push({ phase: 'data-model', label: `alt key ${e.schemaName}.${k.schemaName}` });
}
for (const r of spec.relationships || []) {
- if (r.type === 'OneToMany') items.push({ phase: 'data-model', label: `relationship 1:N ${r.referenced}->${r.referencing}` });
- else if (r.type === 'ManyToMany') items.push({ phase: 'data-model', label: `relationship N:N ${r.entity1}<->${r.entity2}` });
+ if (r.type === 'OneToMany') items.push({ phase: 'data-model', label: `relationship 1:N ${r.referenced}->${r.referencing}`, key: { kind: 'relationship', entity: r.referenced, name: relationshipSchemaName(r, relPrefix), relType: 'OneToMany' } });
+ else if (r.type === 'ManyToMany') items.push({ phase: 'data-model', label: `relationship N:N ${r.entity1}<->${r.entity2}`, key: { kind: 'relationship', entity: r.entity1, name: manyToManySchemaName(r, relPrefix), relType: 'ManyToMany' } });
}
}
if (has('sample-data') && opts.sampleData) {
@@ -363,13 +392,22 @@ function planFor(spec, opts) {
}
if (has('web-resources')) for (const wr of spec.webResources || []) items.push({ phase: 'web-resources', label: `web resource ${wr.name} (${wr.type || 'js'})` });
if (has('web-resources')) for (const e of spec.entities || []) if (e.icon || e.vectorIcon) items.push({ phase: 'web-resources', label: `table icon for ${e.schemaName.toLowerCase()}` });
- if (has('views')) for (const v of spec.views || []) items.push({ phase: 'views', label: `view "${v.name}" for ${v.entity}` });
+ if (has('views')) for (const v of spec.views || []) items.push({ phase: 'views', label: `view "${v.name}" for ${v.entity}`, key: { kind: 'view', entity: v.entity, name: v.name } });
if (has('views')) for (const e of spec.entities || []) if (enrichesDefaultViews(spec, e)) items.push({ phase: 'views', label: `enrich default views for ${e.schemaName.toLowerCase()}` });
- if (has('charts')) for (const c of spec.charts || []) items.push({ phase: 'charts', label: `chart "${c.name}" (${c.chartType}) for ${c.entity}` });
+ if (has('charts')) for (const c of spec.charts || []) items.push({ phase: 'charts', label: `chart "${c.name}" (${c.chartType}) for ${c.entity}`, key: { kind: 'chart', entity: c.entity, name: c.name } });
if (has('forms')) for (const f of spec.forms || []) {
const ft = f.formType || 'Main';
const subs = (f.subgrids || []).map((s) => s.childEntity).join(', ');
- items.push({ phase: 'forms', label: `${ft === 'Main' ? 'form' : `${ft} form`} for ${f.entity}${subs ? ` (sub-grids: ${subs})` : ''}` });
+ // The form's Dataverse NAME is whatever compileFormIntent derives (the author may omit `name`),
+ // and that is the name the reuse lookup keys on — so derive it the same way rather than guessing.
+ // Wrapped because planFor must stay total: a spec shape compileFormIntent rejects should still
+ // produce a plan LINE (it just cannot be probed live), never crash the dry run.
+ let formKey;
+ try {
+ const def = compileFormIntent(spec, f, { notesClassId: NOTES_CLASS_ID });
+ formKey = { kind: 'form', entity: def.entityLogicalName, name: def.name, formType: ft, formId: f.formId };
+ } catch { formKey = undefined; }
+ items.push({ phase: 'forms', label: `${ft === 'Main' ? 'form' : `${ft} form`} for ${f.entity}${subs ? ` (sub-grids: ${subs})` : ''}`, ...(formKey ? { key: formKey } : {}) });
if ((f.events || []).length) items.push({ phase: 'forms', label: `wire ${f.events.length} event handler(s) on ${f.entity}` });
if ((f.quickViews || []).length) items.push({ phase: 'forms', label: `place ${f.quickViews.length} quick-view(s) on ${f.entity}` });
}
@@ -380,12 +418,19 @@ function planFor(spec, opts) {
}
if (has('commands')) for (const [entity, cmds] of Object.entries(commandsByEntity(spec))) items.push({ phase: 'commands', label: `command bar for ${entity} (${cmds.length} button(s))` });
if (has('dashboards')) for (const d of spec.dashboards || []) items.push({ phase: 'dashboards', label: `dashboard "${d.name}" (${(d.tiles || []).length} tile(s))` });
- if (has('app-shell')) items.push({ phase: 'app-shell', label: `app module "${spec.app.name}" + sitemap` });
+ if (has('app-shell')) items.push({ phase: 'app-shell', label: `app module "${spec.app.name}" + sitemap`, key: { kind: 'app', uniqueName: appUniqueName(spec) } });
if (has('app-shell') && !(spec.app && spec.app.icon)) items.push({ phase: 'app-shell', label: `app icon (generated) ${appUniqueName(spec)}_icon` });
if (has('pages')) for (const p of spec.pages || []) items.push({ phase: 'pages', label: `page "${p.name}"` });
if (has('pages') && (spec.pages || []).length && appHasCrossPageNav(spec)) items.push({ phase: 'pages', label: 'resolve cross-page navigation' });
if (has('pages') && (spec.pages || []).length) items.push({ phase: 'pages', label: `page manifest ${appUniqueName(spec)}_pagemanifest` });
- if (has('pages') && (spec.pages || []).length && appHasPageSubareas(spec)) items.push({ phase: 'pages', label: 'finalize sitemap (genpage subareas)' });
+ // Budgeted whenever the pages phase runs, NOT only when the spec has page subareas. The runtime
+ // finalizes on `appHasPageSubareas(spec) || appWasExisting`, and `appWasExisting` is a LIVE fact
+ // planFor cannot see — so gating the plan on the spec alone under-counted every rebuild against an
+ // app that already existed, and the run overran its own denominator ([37/36], live-reproduced on a
+ // page-less spec). The runner's total is fixed at construction from plan.length, so the only way to
+ // stay in step is to budget the step and have the runtime emit an explicit `skip` when it does not
+ // fire — the same shape as the existing-column "applied on create" skips.
+ if (has('pages')) items.push({ phase: 'pages', label: 'finalize sitemap (genpage subareas)' });
if (has('ai-features') && specOptsIntoAi(spec)) {
items.push({ phase: 'ai-features', label: 'enable app AI features' });
// Do NOT short-circuit on `summaries.default === 'off'`. `selectSummaryTables` already implements
@@ -696,6 +741,7 @@ async function ensureAppIcon(spec, created, deps) {
const existing = await findByName(name);
if (existing) {
created.webResources[name] = existing;
+ runner.skip('app-shell', `app icon (generated) ${name} (exists — reuse)`);
return existing;
}
let id;
@@ -1184,6 +1230,173 @@ async function resolveRoleGrantTarget(provision, grant, buCache) {
}
+// Decide, against the LIVE environment, whether each planned item would be created or reused. #559.
+//
+// The dry run used to print `planFor`'s static, spec-derived listing and exit before any discovery,
+// so the identical plan appeared for a spec whose every artifact already exists and for one that
+// would create everything from nothing. A caller could not tell CREATE from REUSE — which is the one
+// question a dry run exists to answer before a production apply.
+//
+// This deliberately reuses the BUILD'S OWN discovery — `findExistingTable`, `findExistingColumns`,
+// `relationshipExists` and the shared `artifactIdentityQuery` — rather than re-implementing a
+// parallel "does it exist?" pass. A second implementation would drift from the one that actually
+// decides at apply time, and a dry run that confidently disagrees with the apply is worse than one
+// that says nothing.
+//
+// Read-only: every call here is a GET/query. Nothing is created, updated or published.
+//
+// Three states, because two would have to lie:
+// create — probed, not present: the apply will create it.
+// reuse — probed, present: the apply will discover and skip/reconcile it.
+// unknown — probed and the read FAILED. Never collapsed into create or reuse: guessing "create"
+// overstates the work and guessing "reuse" understates it, and both read as certainty.
+// An item with no `key` is left unprobed (`state` absent) — the plan line still prints.
+async function annotateLivePlan(plan, { spec, provision, warn } = {}) {
+ // Localization is decided PER ITEM, because that is how the apply path decides it (per entity in
+ // entity-provision.js, per relationship lookup label). A spec-wide flag would push a plain-label
+ // table down the fail-closed path because some unrelated table is localized, and the plan would
+ // then contradict the apply it exists to predict.
+ //
+ // The entity map is built here rather than carried on the key so it cannot depend on probe ORDER:
+ // `tableCache` is keyed by table alone, and a form/view item naming the same table must not be
+ // able to seed the cache with a different localization answer than the table item would.
+ //
+ // The previous spec-wide read also called `localizedLabelLcidsInSpec` without importing it. It
+ // lives in entity-provision.js, not app-spec.js, so the identifier was undeclared and the
+ // `typeof … === 'function'` guard silently evaluated to false on every run — the flag was never
+ // once true.
+ const localizedByEntity = new Map();
+ for (const e of (spec && spec.entities) || []) {
+ localizedByEntity.set(String(e.schemaName || '').toLowerCase(), localizedLabelLcidsInSpec({ entities: [e] }).length > 0);
+ }
+ const tableCache = new Map(); // entity logical -> { found: bool|null }
+ const columnCache = new Map(); // entity logical -> Set<logicalName> | null
+
+ // `findExistingColumns` is written for the APPLY path, where a failed read is safe to treat as
+ // "assume every column is new" — the create's own already-exists handling absorbs the duplicates.
+ // A dry run has no create to absorb anything, so the same `[]` would print `+ create` for columns
+ // that exist. The helper calls `warn` exactly when it is returning that fallback, so the warning
+ // is the signal that the answer was not conclusive.
+ const columnsOf = async (logical) => {
+ if (!columnCache.has(logical)) {
+ let readFailed = false;
+ try {
+ const cols = await findExistingColumns(provision, logical, (msg) => {
+ readFailed = true;
+ if (typeof warn === 'function') warn(msg);
+ });
+ columnCache.set(logical, readFailed ? null : new Set((cols || []).map((c) => String(c.logicalName || '').toLowerCase())));
+ } catch { columnCache.set(logical, null); }
+ }
+ return columnCache.get(logical);
+ };
+
+ // `relationshipExists` falls back to the BROAD `fetchEntityMetadata` read when the narrow one is
+ // inconclusive. Two reasons not to take that fallback here: the vendored implementation WRITES the
+ // fetched metadata into the on-disk workspace, which a read-only dry run must not do (it would
+ // change cached state a later apply reads); and the apply path deliberately treats its `null` as
+ // "absent" because the create absorbs the race, which a dry run must not copy. Handing it a
+ // reader with no `fetchEntityMetadata` makes an inconclusive probe return `null`, which becomes
+ // `unknown` below.
+ const relReader = { dataverse: provision && provision.dataverse };
+
+ const tableState = async (logical) => {
+ if (!tableCache.has(logical)) {
+ try {
+ const hit = await findExistingTable(provision, logical, { hasLocalizedLabels: localizedByEntity.get(logical) === true });
+ tableCache.set(logical, { found: !!hit });
+ } catch (err) {
+ // Includes the BuildHalt findExistingTable raises for a LOCALIZED spec whose probe is
+ // inconclusive — which is precisely an "unknown", not an absence.
+ //
+ // `why` is kept SHORT because it is printed once per plan line, and every column, view and
+ // form on the table inherits it: the BuildHalt text is a ~390-character remediation
+ // paragraph, so a 20-column table would emit ~8 KB of the same prose. The full text is kept
+ // on `whyLong` for the table's own line, where it is worth reading once.
+ const full = String((err && err.message) || err);
+ tableCache.set(logical, { found: null, why: 'the table existence probe was inconclusive', whyLong: full });
+ }
+ }
+ return tableCache.get(logical);
+ };
+
+ // Resolve view/chart/form/app the way the BUILD resolves them, so the plan cannot claim a state
+ // the apply then contradicts:
+ // - forms go through `resolveExistingFormId`, which validates a pinned `formId` (a stale or
+ // foreign pin makes the apply HALT — reporting that as create/reuse would hide it) and throws
+ // on two same-(entity,type,name) forms;
+ // - views/charts go through `provision.findArtifact`, which raises on an ambiguous identity;
+ // - the app is keyed by its deterministic unique name.
+ // Anything thrown becomes `unknown` with the resolver's own message, which is the actionable one.
+ const artifactPresent = async (kind, def) => {
+ if (kind === 'form') return !!(await resolveExistingFormId(provision, def));
+ if ((kind === 'view' || kind === 'chart') && typeof provision.findArtifact === 'function') {
+ return !!(await provision.findArtifact(kind, { name: def.name, entity: def.entityLogicalName }));
+ }
+ const q = artifactIdentityQuery(kind, def);
+ if (!q) return null;
+ const rows = await provision.queryRecords(q.set, { select: [q.idField], filter: q.filter, top: 1 });
+ return !!(rows && rows.length);
+ };
+
+ for (const item of plan) {
+ const k = item.key;
+ if (!k) continue;
+ try {
+ if (k.kind === 'table') {
+ const t = await tableState(String(k.entity).toLowerCase());
+ item.state = t.found === null ? 'unknown' : (t.found ? 'reuse' : 'create');
+ // The table's own line carries the FULL reason (the halt text names the remediation); every
+ // other item on the same table gets the short form, so the paragraph is printed once.
+ if (t.found === null) item.stateWhy = t.whyLong || t.why;
+ } else if (k.kind === 'column') {
+ const logical = String(k.entity).toLowerCase();
+ const t = await tableState(logical);
+ // A column on a table that does not exist is unambiguously a create — and asking Dataverse
+ // for the attributes of a non-existent table only produces a metadata-cache error.
+ if (t.found === false) { item.state = 'create'; continue; }
+ if (t.found === null) { item.state = 'unknown'; item.stateWhy = t.why; continue; }
+ const cols = await columnsOf(logical);
+ if (!cols) { item.state = 'unknown'; item.stateWhy = 'the table\'s attributes could not be read'; continue; }
+ item.state = cols.has(String(k.name).toLowerCase()) ? 'reuse' : 'create';
+ } else if (k.kind === 'relationship') {
+ // Tri-state: `null` means the probe could not tell. The apply path treats that as absent
+ // (its create absorbs the race); a plan has nothing to absorb it, so it must say so.
+ // The localized-label flag is deliberately NOT threaded here. Its only effect inside
+ // `relationshipExists` is to suppress the `fetchEntityMetadata` fallback — and `relReader`
+ // has no `fetchEntityMetadata` at all (see above), so an inconclusive probe already returns
+ // `null` either way. Passing it would be inert code that reads as though it decides
+ // something.
+ const present = await relationshipExists(relReader, String(k.entity).toLowerCase(), k.name, k.relType);
+ item.state = present === null || present === undefined ? 'unknown' : (present ? 'reuse' : 'create');
+ if (item.state === 'unknown') item.stateWhy = 'the relationship metadata read was inconclusive';
+ } else if (k.kind === 'app') {
+ const present = await artifactPresent('app', { uniqueName: k.uniqueName });
+ item.state = present ? 'reuse' : 'create';
+ } else if (k.kind === 'view' || k.kind === 'chart' || k.kind === 'form') {
+ // A form/view/chart on a table that does not exist yet cannot exist either, and the filter
+ // would 400 on the metadata cache — so answer from the table, as the build's own lookup does.
+ const t = await tableState(String(k.entity).toLowerCase());
+ if (t.found === false) { item.state = 'create'; continue; }
+ // …and if the TABLE probe was inconclusive, nothing about its artifacts is knowable either.
+ // Without this the plan contradicts itself in adjacent lines — `? unknown` for the table and
+ // a confident `+ create` for every view and form on it — and the apply never gets that far:
+ // findExistingTable raises BuildHalt for exactly this state, outside any runner.run, so the
+ // build aborts in `data-model`. The form arm is the worst of the three, because
+ // resolveExistingFormId deliberately swallows the MetadataCache 400 and returns null, which
+ // `!!` then flattens into a confident "absent".
+ if (t.found === null) { item.state = 'unknown'; item.stateWhy = t.why; continue; }
+ const present = await artifactPresent(k.kind, { name: k.name, entityLogicalName: String(k.entity).toLowerCase(), formType: k.formType, formId: k.formId, uniqueName: k.uniqueName });
+ item.state = present === null ? 'unknown' : (present ? 'reuse' : 'create');
+ }
+ } catch (err) {
+ item.state = 'unknown';
+ item.stateWhy = String((err && err.message) || err);
+ }
+ }
+ return plan;
+}
+
// --- orchestrator ----------------------------------------------------------------------
async function runSdkBuild(spec, opts = {}) {
const { sdk, apply = false, sampleData = false, publish = false } = opts;
@@ -1199,8 +1412,27 @@ async function runSdkBuild(spec, opts = {}) {
const plan = planFor(spec, { sampleData, publish, phases });
if (!apply) {
- plan.forEach((p, i) => emit({ phase: p.phase, status: 'skip', label: p.label, n: i + 1, total: plan.length }));
- return { ok: true, dryRun: true, plan: plan.map((p) => p.label) };
+ // #559: resolve create-vs-reuse against the live environment before printing the plan. Opt out
+ // with `livePlan: false` for an offline/spec-only listing (the old behaviour). Probing is
+ // skipped silently when the caller supplied no reader — a dry run must still work without one.
+ const canProbe = opts.livePlan !== false && provision && typeof provision.queryRecords === 'function';
+ if (canProbe) {
+ try {
+ await annotateLivePlan(plan, { spec, provision, warn: opts.warn });
+ } catch (err) {
+ // The plan itself is still worth printing; say the states are missing rather than implying
+ // every item is a create.
+ emit({ phase: 'plan', status: 'warn', label: `live plan unavailable (${(err && err.message) || err}) — showing the spec-derived plan only`, n: 0, total: plan.length });
+ }
+ }
+ plan.forEach((p, i) => emit({ phase: p.phase, status: p.state === 'reuse' ? 'skip' : 'skip', label: p.label, state: p.state, stateWhy: p.stateWhy, n: i + 1, total: plan.length }));
+ return {
+ ok: true,
+ dryRun: true,
+ livePlan: canProbe,
+ plan: plan.map((p) => (p.state ? `${p.label} [${p.state}]` : p.label)),
+ planItems: plan.map((p) => ({ phase: p.phase, label: p.label, ...(p.state ? { state: p.state } : {}), ...(p.stateWhy ? { stateWhy: p.stateWhy } : {}) })),
+ };
}
const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [] } };
@@ -2777,12 +3009,23 @@ async function runSdkBuild(spec, opts = {}) {
reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);
return result.created.app;
});
+ } else {
+ // planFor budgets this step for every pages-phase run, so consume the slot even when there is
+ // nothing to write — otherwise the remaining steps renumber past the advertised total.
+ runner.skip('pages', `finalize sitemap (genpage subareas) (${skipSitemapFinalize ? 'content-only re-upload — sitemap unchanged' : 'no sitemap change'})`);
}
} finally {
// Always clean up run-scoped staging (never leave env GUIDs on disk) and release the advisory lease.
try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch { /* best-effort */ }
lease.release();
}
+ } else if (has('pages')) {
+ // The pages phase was selected but the block above did not open: a FRESH app with a page-less
+ // spec has nothing to build and no pre-existing pages to remove, and its sitemap was already
+ // written by the app-shell create path. planFor still budgeted the finalize step (it cannot see
+ // that the app is fresh), so consume the slot here rather than leaving the run one short of its
+ // advertised total.
+ runner.skip('pages', 'finalize sitemap (genpage subareas) (fresh page-less app — sitemap written on create)');
}
// 7b-ii. Modern ("new look") shell — opt-in via `app.newLook`.
@@ -3135,7 +3378,7 @@ async function runSdkBuild(spec, opts = {}) {
// ADDITIVE, never converging. `addEntityPrivilegesToRole` compiles to `AddPrivilegesRole`, so a
// privilege the role already holds is re-asserted and every privilege the spec does NOT mention is
// left alone. That is what makes it safe to point at a role somebody else owns — and it is also why
- // this surface cannot REVOKE (documented in references/app-spec-schema.md).
+ // this surface cannot REVOKE (documented in references/app-spec-schema-advanced.md).
//
// Idempotency comes from Dataverse, not from a read-compare here: re-POSTing a grant the role already
// holds at the same depth succeeds and changes nothing. Re-POSTing at a HIGHER depth raises it. We do
@@ -3478,4 +3721,4 @@ async function runSdkBuild(spec, opts = {}) {
return result;
}
-module.exports = { runSdkBuild, planFor, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
+module.exports = { runSdkBuild, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.js
index 0a3a93fbf..f70812d21 100644
--- a/plugins/model-apps/scripts/lib/sdk-teardown.js
+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js
@@ -108,6 +108,57 @@ function isUndeletable(err) {
return /system-defined|system managed|system-managed/.test(msg);
}
+// Solution component type codes used when reporting what still references a relationship.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/dependency
+const DEPENDENT_COMPONENT_LABELS = { 1: 'table', 2: 'column', 10: 'relationship', 26: 'view', 59: 'chart', 60: 'form' };
+
+// Turn a blocked relationship delete into something an operator can act on.
+//
+// Dataverse refuses with a COUNT and no identities, e.g.:
+// "The EntityRelationship(cc5fe264-…) component cannot be deleted because it is referenced by 2
+// other components. For a list of referenced components, use the RetrieveDependenciesForDeleteRequest."
+// That is a dead end for anyone who now has to find those components by hand, so take the platform's
+// own advice and resolve them. LIVE-MEASURED on a self-referencing 1:N left on a RETAINED
+// (`existing: true`) table: the blocker was a single componenttype 60 (SystemForm) row — the main
+// form the build authored, which this teardown could not plan because the spec no longer declares it.
+//
+// Best-effort and fail-quiet by design: this is diagnostics layered on top of a failure that is
+// already being reported, so any problem here returns null and the caller rethrows the platform's
+// original error unchanged. A diagnostic must never replace a real error with a worse one.
+async function describeBlockingDependencies(sdk, schemaName) {
+ const raw = sdk && sdk.dataverse;
+ if (!raw || typeof raw.get !== 'function') return null;
+ try {
+ const lit = String(schemaName).replace(/'/g, "''");
+ const rel = await raw.get(`/RelationshipDefinitions?$select=MetadataId&$filter=SchemaName eq '${lit}'`);
+ const metadataId = rel && rel.body && Array.isArray(rel.body.value) && rel.body.value[0] && rel.body.value[0].MetadataId;
+ if (!metadataId) return null;
+ // ComponentType 10 = EntityRelationship, matching the component named in the platform's message.
+ const deps = await raw.get(`/RetrieveDependenciesForDelete(ObjectId=${metadataId},ComponentType=10)`);
+ const rows = (deps && deps.body && Array.isArray(deps.body.value)) ? deps.body.value : [];
+ const parts = [];
+ for (const r of rows) {
+ const type = Number(r && r.dependentcomponenttype);
+ const id = r && r.dependentcomponentobjectid;
+ if (!id) continue;
+ const label = DEPENDENT_COMPONENT_LABELS[type] || `component type ${type}`;
+ // Only forms are name-resolved: they are the blocker this path actually hits, and a name is
+ // what makes the message actionable ("Self Ref Acct Form", not a bare GUID).
+ let name = null;
+ if (type === 60) {
+ try {
+ const f = await raw.get(`/systemforms(${id})?$select=name`);
+ name = (f && f.body && f.body.name) || null;
+ } catch { /* a name is a nicety — fall back to the id */ }
+ }
+ parts.push(name ? `${label} "${name}" (${id})` : `${label} ${id}`);
+ }
+ return parts.length ? parts.join(', ') : null;
+ } catch {
+ return null;
+ }
+}
+
// Before deleting a MAIN form the build promoted to the entity default (Gap 2), restore a stock
// main form as the active default — Dataverse refuses to delete the default form and refuses to
// leave a table with zero active main forms. Reactivates any deactivated stock forms and re-defaults
@@ -585,7 +636,26 @@ const KIND_HANDLERS = {
async resolve(sdk, target) {
return [{ id: target.schemaName, schemaName: target.schemaName }];
},
- del: (sdk, item) => sdk.deleteRelationship(item.schemaName),
+ async del(sdk, item) {
+ try {
+ await sdk.deleteRelationship(item.schemaName);
+ } catch (err) {
+ // A dependency block here is a genuine leftover (this handler does NOT opt into
+ // tolerateDependencyBlock), so it still fails the step — but it fails with the identities
+ // of whatever is holding the relationship instead of just a count. The enriched message
+ // keeps the platform's original text as its prefix so isDependencyBlocked still matches it.
+ if (!isDependencyBlocked(err)) throw err;
+ const blockers = await describeBlockingDependencies(sdk, item.schemaName);
+ if (!blockers) throw err;
+ const e = new Error(
+ `${err.message} Still referenced by: ${blockers}. `
+ + 'Delete those components (or remove the lookup from them) and re-run teardown — this relationship '
+ + 'and its lookup column are still in the environment.'
+ );
+ e.cause = err;
+ throw e;
+ }
+ },
tolerateNotFound: true, // a relationship already removed (e.g. by a prior table delete) is "gone"
},
// Gap 6: the build adds parent lookups to the built-in Active/Inactive default views, which can't be
@@ -803,7 +873,7 @@ function planTeardown(spec) {
// access that predates us, which is precisely the outcome the bug asks to avoid, and is worse
// than leaving a stale grant (extra access on a role its owner still administers in Maker).
//
- // Consequence, stated in references/app-spec-schema.md: a roleGrant is one-way. Revoke in Maker.
+ // Consequence, stated in references/app-spec-schema-advanced.md: a roleGrant is one-way. Revoke in Maker.
for (const c of spec.charts || []) {
steps.push({ kind: 'chart', phase: 'charts', label: `chart "${c.name}" (${c.entity})`, target: { name: c.name, entity: String(c.entity).toLowerCase() } });
}
@@ -819,9 +889,42 @@ function planTeardown(spec) {
if (!lookupColumnsFor(spec, logical).length) continue;
steps.push({ kind: 'resetDefaultViews', phase: 'views', label: `reset default views for ${logical} (drop parent lookups)`, target: { entityLogical: logical, cols: defaultViewColumns(spec, e, { includeLookups: false }) } });
}
+ const selfRefRelSteps = [];
for (const r of spec.relationships || []) {
const schema = r.type === 'ManyToMany' ? manyToManySchemaName(r, spec.solution && spec.solution.publisherPrefix) : relationshipSchemaName(r, spec.solution && spec.solution.publisherPrefix);
- steps.push({ kind: 'relationship', phase: 'relationships', label: `relationship ${schema}`, target: { schemaName: schema } });
+ const step = { kind: 'relationship', phase: 'relationships', label: `relationship ${schema}`, target: { schemaName: schema } };
+ // A SELF-referencing 1:N (a hierarchy — `referenced === referencing`) is deleted AFTER its table
+ // rather than before. Deleting it first fails:
+ // ✗ relationship lph_org_lph_org — HTTP 400 … cannot be deleted because it is referenced by
+ // 2 other components.
+ // Its lookup lives on the same table that also hosts the form referencing it, so unlike a
+ // two-table relationship there is nothing left to unpick it from (Gap 6 above clears the default
+ // view, but the table's own main form still holds the lookup). MEASURED live: teardown printed
+ // that error and exited NON-ZERO on a run that then deleted the table and left the environment
+ // completely clean — a cry-wolf failure on the one operation whose report must be trustworthy.
+ // Self-referencing hierarchies became a mainstream shape once sample data could seed them (#544).
+ //
+ // DEFERRING rather than skipping is what keeps it safe for the table this build CREATED. If the
+ // table was deleted, the delete already cascaded this away and the step resolves to "not found",
+ // which this kind already tolerates (`tolerateNotFound: true`).
+ //
+ // If the table is RETAINED — `existing: true`, or one live discovery finds is not custom — the
+ // delete still RUNS, but it is not guaranteed to SUCCEED, and the spec alone cannot tell the two
+ // cases apart, which is why this is an ordering change and not a skip. Gap 6 above clears the
+ // lookup from the default views, but a form is a separate dependency and teardown only plans the
+ // forms the spec declares. LIVE-MEASURED: a retained `account` whose self-lookup was still on a
+ // main form the build authored but the CURRENT spec no longer lists produced
+ // ✗ relationship pp668_account_account — HTTP 400 … referenced by 2 other components
+ // and left the relationship and its lookup behind. That failure is now reported with the
+ // identity of each blocking component (see describeBlockingDependencies) rather than a bare
+ // count, because the remaining cleanup is the operator's: teardown deliberately does NOT delete
+ // forms it cannot prove it authored — stripping a lookup out of somebody's main form is a worse
+ // outcome than leaving a lookup on a table they already own.
+ if (r.type === 'OneToMany' && String(r.referenced || '').toLowerCase() === String(r.referencing || '').toLowerCase()) {
+ selfRefRelSteps.push(step);
+ continue;
+ }
+ steps.push(step);
}
// AI row-summary records must be removed BEFORE tables: the summary record references the
// table and would block its delete.
@@ -873,6 +976,10 @@ function planTeardown(spec) {
for (const e of topoOrderEntities(spec).slice().reverse()) {
steps.push({ kind: 'table', phase: 'tables', label: `table ${e.schemaName}`, target: { logical: e.schemaName.toLowerCase(), schemaName: e.schemaName, existing: e.existing === true } });
}
+ // Self-referencing relationships, deferred from the relationships phase above — see the reasoning
+ // there. After the tables: gone with a deleted table (tolerated not-found), still deletable on a
+ // table this run retained.
+ for (const step of selfRefRelSteps) steps.push(step);
// Web resources AFTER tables (see the order note in the file header): a form's JS is referenced
// by its form (deleted in the forms phase), but a table's vector/raster ICON web resource is
// referenced by the TABLE — Dataverse rejects the delete with "referenced by N other components"
diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.js
index eb6c8821b..e8a45638f 100644
--- a/plugins/model-apps/scripts/lib/spec-lint.js
+++ b/plugins/model-apps/scripts/lib/spec-lint.js
@@ -5,6 +5,7 @@
const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText } = require('./app-spec.js');
const { normalizeSpecShape } = require('./spec-shape.js');
const { resolveSurfaces, unresolvedSurfaceMessage } = require('./surface-resolver.js');
+const { nearestName } = require('./nearest-name.js');
const CHOICE_OPTION_WARN = 12;
const SEQNUM_RE = /\{SEQNUM(:\d+)?\}/i;
@@ -67,23 +68,12 @@ const KNOWN_FILTER_OPS = new Set([
// Cheap near-match for the "did you mean" hint, in the same spirit as the business-rule operator
// check. Catches the two mistakes that actually happen: wrong case (`EQ-USERID`) and a single
// dropped/extra/substituted character (`eq-useroruserteam`, `eq-businesid`).
+//
+// Shares the matcher with the CLI unknown-flag check (dataverse-auth.js): both answer the same
+// question against a closed vocabulary, and a second copy would be free to drift into disagreeing
+// about what counts as a near miss.
function nearestFilterOp(op) {
- const lower = String(op).toLowerCase();
- for (const known of KNOWN_FILTER_OPS) if (known === lower) return known;
- for (const known of KNOWN_FILTER_OPS) {
- if (Math.abs(known.length - lower.length) > 1) continue;
- // Walk both strings once, allowing a single edit. Full Levenshtein is not worth it here.
- let i = 0, j = 0, edits = 0;
- while (i < known.length && j < lower.length) {
- if (known[i] === lower[j]) { i++; j++; continue; }
- if (++edits > 1) break;
- if (known.length > lower.length) i++;
- else if (known.length < lower.length) j++;
- else { i++; j++; }
- }
- if (edits + (known.length - i) + (lower.length - j) <= 1) return known;
- }
- return null;
+ return nearestName(op, KNOWN_FILTER_OPS);
}
function lintAppSpec(spec) {
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index a77d7aead..469717147 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -317,6 +317,52 @@ async function verifySpec(spec, read, opts = {}) {
}
}
+ // App-module TABLE membership (appmodulecomponent componenttype 1).
+ //
+ // The sitemap and the app's component list are SEPARATE facts, and they can disagree: an app can
+ // show a table in navigation while omitting it from its Tables list. That is an internally
+ // inconsistent app definition and it breaks consumers that read app-module membership — but every
+ // check above passes, because the table EXISTS and the sitemap DOES name it. Verify reported PASS
+ // on exactly that app, which is what made the divergence invisible.
+ //
+ // Scoped to SITEMAP-VISIBLE entities on purpose. A spec entity with no subarea is a legitimate
+ // data-model-only/supporting table that the build does not pin, so requiring it would fail every
+ // app that declares one.
+ //
+ // Optional capability: verify-spec is also driven by minimal readers, and an optional reader must
+ // never become a TypeError for them (same rule as `columnVisualization`).
+ if (typeof read.appEntityComponents === 'function') {
+ const sitemapEntities = [];
+ for (const a of (spec.appShell && spec.appShell.areas) || []) {
+ for (const g of a.groups || []) {
+ for (const sa of g.subAreas || []) {
+ const logical = sa && sa.entity ? String(sa.entity).toLowerCase() : null;
+ if (logical && !sitemapEntities.includes(logical)) sitemapEntities.push(logical);
+ }
+ }
+ }
+ if (sitemapEntities.length) {
+ const res = await read.appEntityComponents(sitemapEntities);
+ if (!res || res.ok !== true) {
+ // Fail closed. "We could not look" must never read as "the app is fine" — that is the exact
+ // shape of the bug this check exists to catch.
+ add('app-table-component', 'app tables', false, `could not be read: ${(res && res.reason) || 'unknown'}`);
+ } else {
+ // Case-insensitive: Dataverse does not guarantee the casing of a resolved logical name.
+ const present = new Set((res.present || []).map((n) => String(n).toLowerCase()));
+ for (const logical of sitemapEntities) add('app-table-component', logical, present.has(logical));
+ // The known corruption: a table pinned as an `entity` INSTANCE pins the `entity` METADATA
+ // table itself, so the row points at no real table. Those rows are junk, they accumulate
+ // across reconciliation attempts, and they are worth naming even when every declared table
+ // is present.
+ if (res.placeholder) {
+ add('app-table-component', 'invalid `entity` placeholder component(s)', false,
+ 'the app module contains component(s) pointing at the `entity` metadata table rather than a real table — remove them.');
+ }
+ }
+ }
+ }
+
// Pages (design §13.1). Match BY ID against three authorities — IDENTITY (manifest), EXISTENCE
// (env-wide id set), MEMBERSHIP (app sitemap ids). Reader must supply sitemapPageIds(),
// existenceIds(), manifest(), and pageCode(id) when any page has nav. Fail-closed (Imp7):
diff --git a/plugins/model-apps/scripts/lint-app-spec.js b/plugins/model-apps/scripts/lint-app-spec.js
index 2b306cd41..d080e226e 100644
--- a/plugins/model-apps/scripts/lint-app-spec.js
+++ b/plugins/model-apps/scripts/lint-app-spec.js
@@ -33,9 +33,11 @@
// node lint-app-spec.js --spec @<app-folder>/app-spec.json
// [--profile design|plan|deploy|structural] [--strict] [--json]
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const path = require('node:path');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const { validateAppSpec, migrateAppSpec, VALIDATION_PROFILES } = require('./lib/app-spec.js');
const { lintAppSpec } = require('./lib/spec-lint.js');
+const { pageSourceFileErrors } = require('./lib/content-hash.js');
const USAGE = 'Usage: node lint-app-spec.js --spec @<path-to-app-spec.json> [--profile design|plan|deploy|structural] [--strict] [--json]';
@@ -85,8 +87,10 @@ function lintSpec(rawSpec, opts) {
lint = { ok: false, errors: [`lint could not run on this spec: ${err.message}`], warnings: [] };
}
+ const fileErrors = opts && opts.appDir ? pageSourceFileErrors(spec, opts.appDir) : [];
const errors = [
...validationErrors.map((e) => `schema: ${e}`),
+ ...fileErrors.map((e) => `schema: ${e}`),
...((lint.errors || []).map((e) => `lint: ${e}`)),
];
const warnings = [
@@ -127,20 +131,21 @@ function main() {
// Unknown flags are a USAGE ERROR, not something to ignore. parseArgs accepts any `--name`, so a
// typo (`--profle deploy`) would otherwise be dropped and the command would run the DEFAULT plan
- // profile while exiting 0 — a CI job reporting success for a gate it never applied. This CLI ships
- // in this change, so no caller can be relying on a flag outside this set.
+ // profile while exiting 0 — a CI job reporting success for a gate it never applied.
//
- // Read from argv rather than Object.keys(flags): assigning to `flags['__proto__']` goes through
- // the inherited setter and never becomes an own property, so `--__proto__ deploy` would slip the
- // allow-list AND swallow the next token. Same hazard modelapps-hook-utils.js guards with
- // Object.create(null).
- const KNOWN_FLAGS = new Set(['spec', 'profile', 'strict', 'json', 'help', 'h']);
- const passedFlagNames = process.argv.slice(2)
- .filter((a) => a.startsWith('--'))
- .map((a) => a.slice(2).split('=')[0]);
- const unknown = [...new Set(passedFlagNames.filter((k) => !KNOWN_FLAGS.has(k)))];
- if (unknown.length > 0) {
- return usageError(`unknown flag(s): ${unknown.map((k) => '--' + k).join(', ')}\n${USAGE}`);
+ // This check, and the value-less-flag check that used to sit below it, now come from the shared
+ // validateFlags so every CLI in this directory enforces the same contract; the bespoke copy that
+ // lived here only ever protected this one command.
+ const flagError = validateFlags(process.argv.slice(2), {
+ known: ['spec', 'profile', 'strict', 'json', 'help', 'h'],
+ needValue: ['spec', 'profile'],
+ // Keep the specific guidance the bespoke checks carried: a bare `--profile` is a caller who
+ // asked for a gate and did not say which, and naming the four valid profiles is the difference
+ // between a one-line fix and a trip to the docs.
+ hints: { spec: 'a path to the App Spec JSON', profile: `one of: ${VALIDATION_PROFILES.join(', ')}` },
+ });
+ if (flagError) {
+ return usageError(`${flagError}\n${USAGE}`);
}
// A positional argument is equally suspect: `--spec` is the only way to name the file. But the
// overwhelmingly likely cause on Windows is an UNQUOTED path containing spaces — the documented
@@ -156,21 +161,11 @@ function main() {
return usageError(`unexpected argument(s): ${positional.join(', ')}${hint}\n${USAGE}`);
}
- // parseArgs yields `true` for a bare `--flag` and a string for `--flag=value` / `--flag value`.
- // For a VALUE-taking flag, that bare `true` is a usage error and must be rejected rather than
- // coerced: a bare `--profile` silently falling back to the default would skip a `deploy` gate a
- // CI job believed it had requested, and a bare `--spec` would reach readJsonArg and surface as
- // "spec is not an object" — a gate report about a file the caller never named.
+ // validateFlags has already rejected a bare `--spec` / `--profile` and the `--flag=` empty form,
+ // so anything still present here is a non-empty string.
const isOn = (v) => v === true || v === 'true';
const specArg = flags.spec;
if (specArg === undefined) return usageError(USAGE);
- if (typeof specArg !== 'string' || !specArg.trim()) return usageError(`--spec needs a path\n${USAGE}`);
- if (flags.profile !== undefined && (typeof flags.profile !== 'string' || !flags.profile.trim())) {
- // Covers both the bare `--profile` (boolean true) and `--profile=` / `--profile ''` (empty
- // string). Both are a caller who asked for a profile and did not supply one; neither may fall
- // through to the default.
- return usageError(`--profile needs one of: ${VALIDATION_PROFILES.join(', ')}\n${USAGE}`);
- }
let rawSpec;
try {
@@ -183,7 +178,7 @@ function main() {
return usageError(`could not read spec ${specArg}: ${err.message}`);
}
- const report = lintSpec(rawSpec, { profile: flags.profile });
+ const report = lintSpec(rawSpec, { profile: flags.profile, appDir: path.dirname(path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg)) });
const strict = isOn(flags.strict);
const failed = !report.ok || (strict && report.warnings.length > 0);
diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.js
index a3bc09035..1b8b1f75c 100644
--- a/plugins/model-apps/scripts/list-connections.js
+++ b/plugins/model-apps/scripts/list-connections.js
@@ -16,6 +16,7 @@ const {
dataverseRequest,
ensureOk,
parseArgs,
+ validateFlags,
emitResult,
} = require('./lib/dataverse-auth');
const { exitIfConnectorsDisabled } = require('./lib/feature-flags');
@@ -97,9 +98,26 @@ function parseFixedWidthTable(raw) {
function parseWhitespaceTable(raw) {
const lines = raw.replace(/\r/g, '').split('\n').filter((line) => line.trim());
- const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector/i.test(line));
+ const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector|API Id/i.test(line));
if (headerIndex === -1) return [];
const headers = lines[headerIndex].trim().split(/\s{2,}/);
+ const normalizedHeaders = headers.map(normalizeHeader);
+ // Current PAC builds emit:
+ // Id Name API Id Status
+ // with no dashed separator. Names may contain spaces, so splitting each row on
+ // whitespace loses the boundary. The connector API path is the stable delimiter.
+ if (normalizedHeaders.join(',') === 'id,name,apiid,status') {
+ return lines
+ .slice(headerIndex + 1)
+ .map((line) => line.match(/^(\S+)\s+(.+?)\s+(\/providers\/Microsoft\.PowerApps\/apis\/\S+)\s+(\S+)\s*$/i))
+ .filter(Boolean)
+ .map((match) => mapConnectionRow({
+ Id: match[1],
+ Name: match[2],
+ 'API Id': match[3],
+ Status: match[4],
+ }));
+ }
return lines
.slice(headerIndex + 1)
.filter((line) => !/^-+$/.test(line.trim()))
@@ -182,13 +200,24 @@ function pacFailureMessage(pac) {
}
async function main() {
- // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature
- // off", distinct from 1 = runtime/usage error, so callers can tell them apart.
+ // Rollback gate (fail closed) — see lib/feature-flags.js. connectors is GA and ships ON, so
+ // this normally passes; exit 3 = "feature off" stays distinct from 1 = runtime/usage error.
exitIfConnectorsDisabled();
- const { positional } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional } = parseArgs(argv);
+ const USAGE = 'Usage: node list-connections.js <envUrl>';
+ // This CLI takes no flags at all, so the contract declares an EMPTY `known` set. That is not a
+ // no-op: parseArgs accepts any `--name` and drops it silently while still swallowing the token
+ // after it, so `--environment https://contoso.crm.dynamics.com` would leave `positional` empty
+ // and report a missing envUrl — naming the symptom instead of the typo that caused it.
+ const flagError = validateFlags(argv, { known: [] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 1) {
- process.stderr.write('Usage: node list-connections.js <envUrl>\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const [envUrl] = positional;
@@ -242,4 +271,14 @@ module.exports = {
refsForConnection,
sortReadyToBindFirst,
pacFailureMessage,
+ // The `pac connection list` parsers are exported for unit tests. They consume loosely
+ // structured CLI output whose shape varies across PAC builds (JSON, fixed-width table,
+ // whitespace table), which is exactly the code most likely to break silently on a CLI
+ // upgrade — a mis-parse yields "no connections found" rather than an error.
+ parsePacConnectionList,
+ parseJsonConnections,
+ parseFixedWidthTable,
+ parseWhitespaceTable,
+ mapConnectionRow,
+ extractConnectorId,
};
diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.js
index 03aec480b..b69ea093e 100644
--- a/plugins/model-apps/scripts/list-custom-apis.js
+++ b/plugins/model-apps/scripts/list-custom-apis.js
@@ -27,6 +27,7 @@ const {
dataverseRequest,
ensureOk,
parseArgs,
+ validateFlags,
emitResult,
} = require('./lib/dataverse-auth');
const { exitIfCustomApiDisabled } = require('./lib/feature-flags');
@@ -127,9 +128,16 @@ async function main() {
// from 1 = runtime/usage error, so a caller can tell "not released" from "it broke".
exitIfCustomApiDisabled();
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]';
+ const flagError = validateFlags(argv, { known: ['entities'], needValue: ['entities'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 1) {
- process.stderr.write('Usage: node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const [envUrl] = positional;
diff --git a/plugins/model-apps/scripts/preview-app.js b/plugins/model-apps/scripts/preview-app.js
index 66f2bc667..0ec1c3521 100644
--- a/plugins/model-apps/scripts/preview-app.js
+++ b/plugins/model-apps/scripts/preview-app.js
@@ -8,17 +8,24 @@
// node scripts/preview-app.js --spec @<app-folder>/app-spec.json
const path = require('node:path');
const { renderAppPreview } = require('./lib/app-preview.js');
-const { parseArgs, readJsonArg } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth.js');
const { migrateAppSpec } = require('./lib/app-spec.js');
function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node scripts/preview-app.js --spec @<app-folder>/app-spec.json';
+ const flagError = validateFlags(argv, { known: ['spec'], needValue: ['spec'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
const specArg = flags.spec || positional[0];
if (!specArg) {
- process.stderr.write('Usage: node scripts/preview-app.js --spec @<app-folder>/app-spec.json\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
- const specPath = path.resolve(typeof specArg === 'string' && specArg.startsWith('@') ? specArg.slice(1) : specArg);
+ const specPath = path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg);
const spec = migrateAppSpec(readJsonArg('@' + specPath));
process.stdout.write(renderAppPreview(spec));
}
diff --git a/plugins/model-apps/scripts/preview-form.js b/plugins/model-apps/scripts/preview-form.js
index 33eb5aa70..f2d74fb4c 100644
--- a/plugins/model-apps/scripts/preview-form.js
+++ b/plugins/model-apps/scripts/preview-form.js
@@ -7,17 +7,24 @@
// node scripts/preview-form.js --spec @<app-folder>/app-spec.json [--entity new_workorder]
const path = require('node:path');
const { renderForms } = require('./lib/form-preview.js');
-const { parseArgs, readJsonArg } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg } = require('./lib/dataverse-auth.js');
const { migrateAppSpec, validateAppSpec } = require('./lib/app-spec.js');
function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- const specArg = (typeof flags.spec === 'string' ? flags.spec : undefined) || (typeof positional[0] === 'string' ? positional[0] : undefined);
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node scripts/preview-form.js --spec @<app-folder>/app-spec.json [--entity <schemaName>]';
+ const flagError = validateFlags(argv, { known: ['spec', 'entity'], needValue: ['spec', 'entity'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const specArg = flags.spec || positional[0];
if (!specArg) {
- process.stderr.write('Usage: node scripts/preview-form.js --spec @<app-folder>/app-spec.json [--entity <schemaName>]\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
- const specPath = path.resolve(typeof specArg === 'string' && specArg.startsWith('@') ? specArg.slice(1) : specArg);
+ const specPath = path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg);
const spec = migrateAppSpec(readJsonArg('@' + specPath));
const validation = validateAppSpec(spec, { profile: 'structural' });
if (!validation.ok) {
@@ -26,7 +33,7 @@ function main() {
process.stderr.write(`Invalid App Spec:\n${validation.errors.map((e) => ` - ${e}`).join('\n')}\n`);
process.exit(1);
}
- const entity = typeof flags.entity === 'string' ? flags.entity : undefined;
+ const entity = flags.entity;
process.stdout.write(renderForms(spec, entity) + '\n');
}
diff --git a/plugins/model-apps/scripts/promote-intent-pages.js b/plugins/model-apps/scripts/promote-intent-pages.js
index 6ac02a819..c138264c6 100644
--- a/plugins/model-apps/scripts/promote-intent-pages.js
+++ b/plugins/model-apps/scripts/promote-intent-pages.js
@@ -18,7 +18,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const { migrateAppSpec } = require('./lib/app-spec.js');
const { pageKey, pageFile } = require('./lib/page-plan.js');
const { navReferencedKeys, navMalformedRefs, navTargetParity } = require('./lib/pageref-resolver.js');
@@ -84,12 +84,21 @@ function validatePage(page, absWorkingDir) {
}
function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- const str = (v) => (typeof v === 'string' ? v : undefined);
- const specArg = str(flags.spec) || (typeof positional[0] === 'string' ? positional[0] : undefined);
- const workingDir = str(flags['working-dir']);
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node scripts/promote-intent-pages.js --spec @<app-folder>/app-spec.json --working-dir <dir>';
+ const flagError = validateFlags(argv, {
+ known: ['spec', 'working-dir'],
+ needValue: ['spec', 'working-dir'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const specArg = flags.spec || positional[0];
+ const workingDir = flags['working-dir'];
if (!specArg || !workingDir) {
- process.stderr.write('Usage: node scripts/promote-intent-pages.js --spec @<app-folder>/app-spec.json --working-dir <dir>\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.js
index 6379fc40f..670266a94 100644
--- a/plugins/model-apps/scripts/provision-entities.js
+++ b/plugins/model-apps/scripts/provision-entities.js
@@ -12,7 +12,7 @@ const { validateProvisionInput } = require('./lib/provision-input.js');
const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData } = require('./lib/entity-provision.js');
const { quickCreateEnabledFor, normalizeLanguageCode } = require('./lib/app-spec.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
-const { parseArgs, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');
// Construct the SDK against the vendored bundle + an az-token HttpClient. Two clients:
// sdk — carries solutionUniqueName (metadata + record writes auto-join the
@@ -275,26 +275,27 @@ async function provisionEntities(input, opts = {}, deps = {}) {
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- // parseArgs represents a value-less flag as boolean true. These are value-bearing flags, so
- // coerce bare `--env` / `--input` to missing and let the usage guard produce the same clear error
- // as an omitted value instead of passing a boolean into auth or path resolution.
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const inputArg = (typeof flags.input === 'string' ? flags.input : undefined) || (typeof positional[0] === 'string' ? positional[0] : undefined);
-
- if (!env || !inputArg || flags.input === true) {
- process.stderr.write(
- 'Usage: node provision-entities.js --env <url> --input @<path> [--apply] [--sample-data] [--language-code|--languageCode <lcid>]\n'
- );
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node provision-entities.js --env <url> --input @<path> [--apply] [--sample-data] [--language-code|--languageCode <lcid>]';
+ // A value-less `--language-code` must never fall through to the org default, and an unknown flag
+ // must never be dropped while swallowing the token after it.
+ const flagError = validateFlags(argv, {
+ known: ['env', 'input', 'apply', 'sample-data', 'language-code', 'languageCode'],
+ needValue: ['env', 'input', 'language-code', 'languageCode'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
process.exit(1);
}
- // A value-less `--language-code` is a usage error, never a silent fall-through to the org default.
- const valuelessLang = ['language-code', 'languageCode'].find((k) => flags[k] === true);
- if (valuelessLang) {
- process.stderr.write(`✗ --${valuelessLang} requires a value.\n`);
+ const env = flags.env;
+ const inputArg = flags.input || positional[0];
+
+ if (!env || !inputArg) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
-
+
const inputPath = path.resolve(typeof inputArg === 'string' && inputArg.startsWith('@') ? inputArg.slice(1) : inputArg);
const input = readJsonArg('@' + inputPath);
diff --git a/plugins/model-apps/scripts/provision-solution.js b/plugins/model-apps/scripts/provision-solution.js
index b95ecd3d9..71601c390 100644
--- a/plugins/model-apps/scripts/provision-solution.js
+++ b/plugins/model-apps/scripts/provision-solution.js
@@ -16,7 +16,7 @@
//
// Output: { "ok": true, "solutionId": "...", "uniqueName": "...", "publisherUniqueName": "...", "publisherPrefix": "..." }
-const { parseArgs, emitResult } = require('./lib/dataverse-auth');
+const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth');
const { createAzHttpClient } = require('./lib/sdk-http-client');
const { odataLit } = require('./lib/odata.js');
@@ -129,11 +129,21 @@ async function runProvisionSolution(args, deps) {
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node provision-solution.js <envUrl> <uniqueName> <friendlyName> [--description <text>] [--version 1.0.0.0] [--publisher <uniqueName>]';
+ // All three optional flags carry a value that is written into the solution record; a bare
+ // `--publisher` would otherwise reach Dataverse as boolean true.
+ const flagError = validateFlags(argv, {
+ known: ['description', 'version', 'publisher'],
+ needValue: ['description', 'version', 'publisher'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
if (positional.length < 3) {
- process.stderr.write(
- 'Usage: node provision-solution.js <envUrl> <uniqueName> <friendlyName> [--description <text>] [--version 1.0.0.0] [--publisher <uniqueName>]\n'
- );
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const [envUrl, uniqueName, friendlyName] = positional;
diff --git a/plugins/model-apps/scripts/resolve-interaction-mode.js b/plugins/model-apps/scripts/resolve-interaction-mode.js
new file mode 100644
index 000000000..f1b111f28
--- /dev/null
+++ b/plugins/model-apps/scripts/resolve-interaction-mode.js
@@ -0,0 +1,29 @@
+#!/usr/bin/env node
+'use strict';
+
+// Reports whether a human can answer a question in THIS run, so a skill can pick a documented
+// default instead of waiting for an answer that will never come.
+//
+// WHY a script and not just "check the env var in the prompt": `/genpage` decides this at several
+// gates (create-vs-edit, an agent's needs_input, plan approval, the browser-verify offer). Each
+// one re-deriving the rule from prose is how they end up disagreeing — and a gate that guesses
+// "attended" under Copilot autopilot or Claude auto-accept stalls the whole run with no output
+// explaining why. One command, one answer, and the eval harness can assert it.
+//
+// Output is a single JSON line, matching the other discovery scripts in this plugin:
+// {"ok":true,"interactive":false,"reason":"POWER_PLATFORM_SKILLS_NONINTERACTIVE is set"}
+// Always exits 0: "there is no user" is a fact about the run, not a failure of it.
+
+const { resolveInteractionMode } = require('./lib/interaction-mode.js');
+
+function main(argv = process.argv.slice(2)) {
+ const mode = resolveInteractionMode({ argv, env: process.env });
+ process.stdout.write(JSON.stringify({ ok: true, ...mode }) + '\n');
+ return 0;
+}
+
+if (require.main === module) {
+ process.exit(main());
+}
+
+module.exports = { main };
diff --git a/plugins/model-apps/scripts/run-tests.js b/plugins/model-apps/scripts/run-tests.js
index 218a2e4c6..6242539f4 100644
--- a/plugins/model-apps/scripts/run-tests.js
+++ b/plugins/model-apps/scripts/run-tests.js
@@ -19,12 +19,26 @@ const path = require('node:path');
const NODE20_BIN = process.env.NODE20_BIN || null;
// The plugin test files to run, as repo-relative paths (sorted, stable order).
+//
+// RECURSIVE on purpose. This used to be a flat `readdirSync`, which silently ran zero tests from any
+// `scripts/tests/<subdir>/*.test.js` — the file would be committed, reviewed and green, and never
+// execute. Nothing else in CI would notice, because the runner reports success on the files it did
+// find. Every test file today happens to be top-level, so this changes nothing now; it removes the
+// trap for the first one that is not. `helpers/` holds fixtures, not tests, so the `.test.js` suffix
+// (not the directory) remains the selector.
function pluginTestFiles(testsDir) {
- return fs
- .readdirSync(testsDir)
- .filter((f) => f.endsWith('.test.js'))
- .sort()
- .map((f) => path.join('scripts', 'tests', f));
+ const out = [];
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full);
+ else if (entry.name.endsWith('.test.js')) out.push(full);
+ }
+ };
+ walk(testsDir);
+ // Paths stay `scripts/tests/...`-prefixed and relative to the PLUGIN root (what the runner spawns
+ // with), and a nested file keeps its subdirectory segment.
+ return out.map((f) => path.join('scripts', 'tests', path.relative(testsDir, f))).sort();
}
// Resolve the SDK package dir + whether it (and a Node-20 bin dir) are present.
diff --git a/plugins/model-apps/scripts/teardown-model-app.js b/plugins/model-apps/scripts/teardown-model-app.js
index a85c42af5..a06cc3dd7 100644
--- a/plugins/model-apps/scripts/teardown-model-app.js
+++ b/plugins/model-apps/scripts/teardown-model-app.js
@@ -24,7 +24,7 @@ const { validateAppSpec, migrateAppSpec } = require('./lib/app-spec.js');
const { runTeardown } = require('./lib/sdk-teardown.js');
const { classifyOps } = require('./lib/op-diff.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const snapStore = require('./lib/apply-snapshot-store.js');
// Build an SDK client for teardown. Uses the same az-token HttpClient as build-model-app.js.
@@ -118,15 +118,27 @@ async function teardownModelApp(spec, opts, deps) {
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const specArg = (typeof flags.spec === 'string' ? flags.spec : undefined) || (typeof positional[0] === 'string' ? positional[0] : undefined);
- const workspaceArg = typeof flags.workspace === 'string' ? flags.workspace : undefined;
- if (!env || !specArg || flags.workspace === true) {
- process.stderr.write(
- 'Usage: node scripts/teardown-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--allow-destructive] [--clear-workspace] [--workspace <dir>]\n' +
- ' Note: --workspace only controls the optional --clear-workspace cleanup; teardown itself uses a throwaway SDK workspace.\n'
- );
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE =
+ 'Usage: node scripts/teardown-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--allow-destructive] [--clear-workspace] [--workspace <dir>]\n' +
+ ' Note: --workspace only controls the optional --clear-workspace cleanup; teardown itself uses a throwaway SDK workspace.';
+ // Strictness matters more here than anywhere else: this tool deletes. A mistyped
+ // `--allow-destructiv` was previously dropped in silence, and the safety flag the operator
+ // believed they had passed simply did not exist.
+ const flagError = validateFlags(argv, {
+ known: ['env', 'spec', 'apply', 'allow-destructive', 'clear-workspace', 'workspace'],
+ needValue: ['env', 'spec', 'workspace'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const env = flags.env;
+ const specArg = flags.spec || positional[0];
+ const workspaceArg = flags.workspace;
+ if (!env || !specArg) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const specPath = path.resolve(typeof specArg === 'string' && specArg.startsWith('@') ? specArg.slice(1) : specArg);
diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
index 8004e2959..6521c32fa 100644
--- a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
@@ -13,13 +13,14 @@ test('adds appmodule (80) with required components', () => {
assert.match(scriptSrc, /addComponent\([^)]*APPMODULE_COMPONENT_TYPE,\s*true\)/);
});
-test('adds connection references by confirmed component type', () => {
+test('discovers connection-reference component type from environment metadata', () => {
assert.match(scriptSrc, /connectionreferences\?\$filter=connectionreferencelogicalname/);
- assert.match(scriptSrc, /CONNECTION_REFERENCE_COMPONENT_TYPE\s*=\s*10158/);
+ assert.match(scriptSrc, /EntityDefinitions\(LogicalName=/);
+ assert.match(scriptSrc, /CONNECTION_REFERENCE_LOGICAL_NAME\s*=\s*'connectionreference'/);
});
-test('adds the GenPage uxagentproject explicitly (type 10372)', () => {
- assert.match(scriptSrc, /UXAGENTPROJECT_COMPONENT_TYPE\s*=\s*10372/);
+test('discovers the GenPage component type from environment metadata', () => {
+ assert.match(scriptSrc, /UXAGENTPROJECT_LOGICAL_NAME\s*=\s*'uxagentproject'/);
assert.match(scriptSrc, /flags\['page-ids'\]/);
});
@@ -29,38 +30,214 @@ test('missing args exits 1 with usage', () => {
assert.match(res.stderr, /Usage:/);
});
-const { connectionRefsToAdd } = require(scriptPath);
+// --- Wire-level packaging contract ------------------------------------------
+//
+// These drive main() with a stubbed dataverseRequest and assert the ACTUAL sequence of
+// AddSolutionComponent calls. The component type codes are live-verified values that are not
+// locally obvious, and getting one wrong produces a solution that imports with unbound
+// connectors — a failure that only shows up in the TARGET environment, long after this ran.
-test('connection references are gated by the connectors flag (added only when ON)', () => {
- assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], true), ['new_a', 'new_b']);
- assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], false), []);
+const { loadCli } = require('./helpers/cli-harness.js');
+
+function defaultLookup(requestPath) {
+ if (requestPath.includes("EntityDefinitions(LogicalName='uxagentproject')")) {
+ return { status: 200, data: { ObjectTypeCode: 10372 } };
+ }
+ if (requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")) {
+ return { status: 200, data: { ObjectTypeCode: 10158 } };
+ }
+ return { status: 200, data: { value: [{ connectionreferenceid: 'cr-1' }] } };
+}
+
+function harness({ argv, refLookup = defaultLookup }) {
+ const calls = [];
+ const emitted = [];
+ const authStub = {
+ parseArgs: require('../lib/dataverse-auth.js').parseArgs,
+ validateFlags: require('../lib/dataverse-auth.js').validateFlags,
+ ensureOk: (res, what) => {
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`${what} failed: ${res && res.status}`);
+ },
+ emitResult: (ok, payload) => { emitted.push({ ok, payload }); },
+ dataverseRequest: async (envUrl, method, pathOrAction, body) => {
+ calls.push({ envUrl, method, path: pathOrAction, body });
+ if (method === 'GET') return refLookup(pathOrAction);
+ return { status: 204, data: {} };
+ },
+ };
+ const cli = loadCli(scriptPath, { requires: { './lib/dataverse-auth': authStub }, argv });
+ return { cli, calls, emitted };
+}
+
+const ENV = 'https://contoso.crm.dynamics.com';
+
+test('packages appmodule, each page, and each connection reference with the right component types', async () => {
+ const { cli, calls, emitted } = harness({
+ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1,p2', '--connection-refs', 'new_sp'],
+ });
+
+ await cli.main();
+
+ const adds = calls.filter((c) => c.path === 'AddSolutionComponent');
+ // appmodule (80) with AddRequiredComponents=true pulls the sitemap + appmodulecomponent.
+ assert.deepEqual(
+ { ComponentId: adds[0].body.ComponentId, ComponentType: adds[0].body.ComponentType, AddRequiredComponents: adds[0].body.AddRequiredComponents },
+ { ComponentId: 'app-1', ComponentType: 80, AddRequiredComponents: true }
+ );
+ // Each GenPage is added EXPLICITLY as uxagentproject (10372) — it does not travel with the app.
+ assert.deepEqual(adds.slice(1, 3).map((c) => [c.body.ComponentId, c.body.ComponentType, c.body.AddRequiredComponents]),
+ [['p1', 10372, true], ['p2', 10372, true]]);
+ // The connection reference resolves by logical name, then is added as 10158 WITHOUT required
+ // components (371 is msdyn_Connector and fails with a MetadataCache error).
+ assert.deepEqual([adds[3].body.ComponentId, adds[3].body.ComponentType, adds[3].body.AddRequiredComponents],
+ ['cr-1', 10158, false]);
+ assert.equal(emitted[0].ok, true);
+ assert.deepEqual(emitted[0].payload.added.map((a) => a.type),
+ ['appmodule', 'uxagentproject', 'uxagentproject', 'connectionreference']);
+});
+
+test('discovers environment-specific component types for GenPages and connection references', async () => {
+ const { cli, calls } = harness({
+ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1', '--connection-refs', 'new_sp'],
+ refLookup: (requestPath) => {
+ if (requestPath.includes("EntityDefinitions(LogicalName='uxagentproject')")) {
+ return { status: 200, data: { ObjectTypeCode: 10380 } };
+ }
+ if (requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")) {
+ return { status: 200, data: { ObjectTypeCode: 10162 } };
+ }
+ return { status: 200, data: { value: [{ connectionreferenceid: 'cr-1' }] } };
+ },
+ });
+
+ await cli.main();
+
+ const adds = calls.filter((c) => c.path === 'AddSolutionComponent');
+ assert.equal(adds[1].body.ComponentType, 10380);
+ assert.equal(adds[2].body.ComponentType, 10162);
+});
+
+test('the appmodule is packaged BEFORE any page or connection reference', async () => {
+ // Order is load-bearing: adding a uxagentproject to a solution the app is not yet in produces a
+ // solution whose page has no owning app.
+ const { cli, calls } = harness({ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1', '--connection-refs', 'new_sp'] });
+ await cli.main();
+ const types = calls.filter((c) => c.path === 'AddSolutionComponent').map((c) => c.body.ComponentType);
+ assert.equal(types[0], 80, 'appmodule must be first');
+ assert.ok(types.indexOf(10372) < types.indexOf(10158), 'pages before connection references');
});
-// Fail-closed backstop (AGENTS.md → connectors gate checklist item 4). Explicitly requesting
-// --connection-refs while the flag is OFF must exit 3 BEFORE any AddSolutionComponent call, so the
-// run cannot report success while silently dropping the refs (which would package a solution whose
-// connectors are unbound on import).
-test('--connection-refs while connectors are OFF exits 3 before any mutation', () => {
+test('a connection reference that does not exist fails the run instead of packaging a partial solution', async () => {
+ const { cli, emitted } = harness({
+ argv: [ENV, 'sol', 'app-1', '--connection-refs', 'new_missing'],
+ refLookup: (requestPath) =>
+ requestPath.includes("EntityDefinitions(LogicalName='connectionreference')")
+ ? { status: 200, data: { ObjectTypeCode: 10158 } }
+ : { status: 200, data: { value: [] } },
+ });
+ await cli.main();
+ assert.equal(emitted[0].ok, false);
+ assert.match(String(emitted[0].payload.message || emitted[0].payload), /new_missing.*not found/);
+});
+
+test('a connection reference logical name with a quote is OData-escaped, not injected', async () => {
+ const seen = [];
+ const { cli } = harness({
+ argv: [ENV, 'sol', 'app-1', '--connection-refs', "new_o'brien"],
+ refLookup: (p) => {
+ if (p.includes("EntityDefinitions(LogicalName='connectionreference')")) {
+ return { status: 200, data: { ObjectTypeCode: 10158 } };
+ }
+ seen.push(p);
+ return { status: 200, data: { value: [{ connectionreferenceid: 'cr-9' }] } };
+ },
+ });
+ await cli.main();
+ // OData escapes a single quote by DOUBLING it; an unescaped quote would terminate the literal
+ // and make the $filter a syntax error (or worse, a different filter).
+ assert.match(seen[0], /connectionreferencelogicalname eq 'new_o''brien'/);
+});
+
+test('no --connection-refs packages the app and pages only', async () => {
+ const { cli, calls, emitted } = harness({ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1'] });
+ await cli.main();
+ assert.equal(calls.filter((c) => c.method === 'GET').length, 1, 'only the page component-type lookup runs');
+ assert.deepEqual(emitted[0].payload.added.map((a) => a.type), ['appmodule', 'uxagentproject']);
+});
+
+test('a failing AddSolutionComponent surfaces as a failure, not a silent partial success', async () => {
+ const calls = [];
+ const emitted = [];
+ let addCalls = 0;
+ const authStub = {
+ parseArgs: require('../lib/dataverse-auth.js').parseArgs,
+ validateFlags: require('../lib/dataverse-auth.js').validateFlags,
+ ensureOk: (res, what) => {
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`${what} failed: ${res && res.status}`);
+ },
+ emitResult: (ok, payload) => { emitted.push({ ok, payload }); },
+ dataverseRequest: async (envUrl, method, p, body) => {
+ calls.push({ method, p, body });
+ if (method === 'GET') return { status: 200, data: { ObjectTypeCode: 10372 } };
+ // Fail on the SECOND add (the page), after the app already succeeded.
+ addCalls += 1;
+ return addCalls === 2 ? { status: 400, data: { error: { message: 'bad' } } } : { status: 204, data: {} };
+ },
+ };
+ const cli = loadCli(scriptPath, {
+ requires: { './lib/dataverse-auth': authStub },
+ argv: [ENV, 'sol', 'app-1', '--page-ids', 'p1'],
+ });
+ await cli.main();
+ assert.equal(emitted[0].ok, false, 'a mid-sequence failure must not report ok:true');
+ assert.deepEqual(
+ calls.filter((call) => call.p === 'AddSolutionComponent').map((call) => call.body.ComponentType),
+ [80, 10372],
+ 'the app add succeeds before the page add fails',
+ );
+});
+
+test('--connection-refs while the rollback switch is off exits 3 before any mutation', () => {
+ // The gate's whole purpose: refuse BEFORE the first AddSolutionComponent, so a refused run
+ // leaves the solution untouched rather than half-packaged (app + pages added, refs missing).
+ // Dropping the refs while still reporting ok:true is what made this silently lossy before —
+ // the solution then imports with unbound connectors.
const res = spawnSync(
process.execPath,
- [scriptPath, 'https://example.crm.dynamics.com', 'sol', 'app-1', '--connection-refs', 'new_a'],
+ [scriptPath, 'https://contoso.crm.dynamics.com', 'sol', 'app-1', '--connection-refs', 'new_a'],
{ encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }
);
assert.equal(res.status, 3, 'exit 3 = feature off (distinct from 1 = usage/runtime error)');
assert.match(res.stderr, /Connector support is disabled/);
- // No Dataverse call was attempted: the env URL is bogus, so any mutation would have surfaced a
- // network/auth error on stderr instead of the clean gate message.
- assert.doesNotMatch(res.stderr, /AddSolutionComponent/);
assert.doesNotMatch(res.stdout || '', /"ok":\s*true/, 'must not report success');
});
-test('no --connection-refs is NOT gated (non-connector packaging proceeds when OFF)', () => {
- // Only an explicit request is refused; ordinary page packaging must still work with the flag OFF.
+test('packaging WITHOUT --connection-refs is not gated by the rollback switch', () => {
+ // Only an explicit connector request is refused; ordinary page packaging must still work.
// Reaching a Dataverse/auth failure (not exit 3) proves the gate did not fire.
const res = spawnSync(
process.execPath,
[scriptPath, 'https://example.invalid', 'sol', 'app-1', '--page-ids', 'p1'],
{ encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }
);
- assert.notEqual(res.status, 3, 'the connectors gate must not fire without --connection-refs');
+ assert.notEqual(res.status, 3, 'the gate must not fire without --connection-refs');
+});
+
+test('connectionRefsToAdd drops refs only when the switch is off', () => {
+ const { connectionRefsToAdd } = require(scriptPath);
+ assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], true), ['new_a', 'new_b']);
+ assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], false), []);
+});
+
+test('the stable app component type and dynamic entity names are pinned', () => {
+ const {
+ APPMODULE_COMPONENT_TYPE,
+ UXAGENTPROJECT_LOGICAL_NAME,
+ CONNECTION_REFERENCE_LOGICAL_NAME,
+ escapeODataString,
+ } = require(scriptPath);
+ assert.equal(APPMODULE_COMPONENT_TYPE, 80);
+ assert.equal(UXAGENTPROJECT_LOGICAL_NAME, 'uxagentproject');
+ assert.equal(CONNECTION_REFERENCE_LOGICAL_NAME, 'connectionreference');
+ assert.equal(escapeODataString("a'b'c"), "a''b''c");
});
diff --git a/plugins/model-apps/scripts/tests/ai-preflight.test.js b/plugins/model-apps/scripts/tests/ai-preflight.test.js
index 74038abb0..8003f895f 100644
--- a/plugins/model-apps/scripts/tests/ai-preflight.test.js
+++ b/plugins/model-apps/scripts/tests/ai-preflight.test.js
@@ -5,6 +5,7 @@ const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { runPreflight } = require('../ai-preflight.js');
+const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');
test('runPreflight lists features and produces admin actions for disabled ones', () => {
const readiness = {
@@ -88,6 +89,7 @@ function loadPreflightCli({ parseResult, readiness, sdkThrows = null }) {
if (id === './lib/dataverse-auth.js') {
return {
parseArgs: () => parseResult,
+ validateFlags: validateFlagsFromParsed(() => parseResult.flags),
emitResult: (ok, payload) => events.push({ type: 'emitResult', ok, payload }),
};
}
diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.js
index 40ceb9cc7..5a2010bdd 100644
--- a/plugins/model-apps/scripts/tests/app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec.test.js
@@ -608,6 +608,66 @@ test('#1 a valid $parent.match that resolves to a real parent row still passes',
assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});
+// --- #544: self-referencing sample data, validated at LINT time -------------------------------
+// The build halting partway through sample-data — after other data is already written — is the
+// worst outcome, so the rules the seeder enforces at runtime are all gated here first.
+function selfRefDesk() {
+ const s = cloneDesk();
+ s.entities.push({ schemaName: 'new_org', displayName: 'Org', pluralName: 'Orgs', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] });
+ s.relationships.push({ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_ParentOrgId', displayName: 'Parent Org' } });
+ s.sampleData.new_org = [
+ { new_name: 'Root' },
+ { new_name: 'Child', $parent: { entity: 'new_org', match: { new_name: 'Root' } } },
+ ];
+ return s;
+}
+
+test('#544 a self-referencing $parent hierarchy is VALID (the seeder creates it in waves)', () => {
+ const r = validateAppSpec(selfRefDesk());
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+});
+
+test('#544 a self-reference cycle is rejected at lint time, naming the record indices', () => {
+ const s = selfRefDesk();
+ s.sampleData.new_org[0].$parent = { entity: 'new_org', match: { new_name: 'Child' } };
+ const r = validateAppSpec(s);
+ assert.strictEqual(r.ok, false);
+ assert.ok(r.errors.some((e) => /\$parent cycle/.test(e) && /0, 1/.test(e)), JSON.stringify(r.errors));
+});
+
+test('#544 a row that is its own parent is rejected as a cycle', () => {
+ const s = selfRefDesk();
+ s.sampleData.new_org = [{ new_name: 'Loop', $parent: { entity: 'new_org', match: { new_name: 'Loop' } } }];
+ const r = validateAppSpec(s);
+ assert.strictEqual(r.ok, false);
+ assert.ok(r.errors.some((e) => /\$parent cycle/.test(e)), JSON.stringify(r.errors));
+});
+
+test('#544 TWO relationships for one pair make a $parent ambiguous unless it names the lookup', () => {
+ const s = selfRefDesk();
+ s.relationships.push({ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_GroupAncestorId', displayName: 'Group Ancestor' } });
+ const ambiguous = validateAppSpec(s);
+ assert.strictEqual(ambiguous.ok, false);
+ assert.ok(ambiguous.errors.some((e) => /ambiguous/.test(e) && /new_ParentOrgId/.test(e) && /new_GroupAncestorId/.test(e)), JSON.stringify(ambiguous.errors));
+
+ s.sampleData.new_org[1].$parent.lookup = 'new_GroupAncestorId';
+ const named = validateAppSpec(s);
+ assert.strictEqual(named.ok, true, JSON.stringify(named.errors));
+});
+
+test('#544 a $parent.lookup that names no relationship lists the valid ones', () => {
+ const s = selfRefDesk();
+ s.sampleData.new_org[1].$parent.lookup = 'new_NotARelationship';
+ const r = validateAppSpec(s);
+ assert.strictEqual(r.ok, false);
+ assert.ok(r.errors.some((e) => /new_NotARelationship/.test(e) && /new_ParentOrgId/.test(e)), JSON.stringify(r.errors));
+});
+
+test('#544 a cross-entity $parent is unaffected by the self-reference checks', () => {
+ // The stock desk binds tickets to customers; no self-reference exists anywhere in it.
+ assert.strictEqual(validateAppSpec(cloneDesk()).ok, true);
+});
+
test('#1 (hardening) a non-array $parents is rejected (it diverges from the seeder otherwise)', () => {
const bad = cloneDesk();
bad.sampleData.new_ticket[0] = { new_name: 'Row', new_priority: 'High', new_status: 'New',
diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.js
index e66166f94..4efb09093 100644
--- a/plugins/model-apps/scripts/tests/check-auth.test.js
+++ b/plugins/model-apps/scripts/tests/check-auth.test.js
@@ -3,6 +3,7 @@ const { test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
+const { execFileSync } = require('node:child_process');
const scriptPath = path.join(__dirname, '..', 'check-auth.js');
const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
@@ -52,6 +53,36 @@ test('parseEnvUrl returns null when no url is given', () => {
assert.equal(parseEnvUrl(['--apply']), null);
});
+test('a positional url survives a preceding boolean --require-pac', () => {
+ // parseArgs has no flag contract, so it treats the token after the boolean `--require-pac` as its
+ // value. Reading the fallback from parseArgs' `positional` array therefore LOST the URL and fell
+ // back to `pac org who` — silently probing a different environment than the caller named. The
+ // header documents both orderings and callers do not control argument order.
+ assert.equal(parseEnvUrl(['--require-pac', 'https://contoso.crm.dynamics.com']), 'https://contoso.crm.dynamics.com');
+ assert.equal(parseEnvUrl(['https://contoso.crm.dynamics.com', '--require-pac']), 'https://contoso.crm.dynamics.com');
+});
+
+test('a mistyped flag is a structured blocker, not a silently weaker check', () => {
+ // `--requir-pac` used to be dropped in silence, which quietly downgraded genpage's HARD pac
+ // requirement to a warning. It must be reported — but still on exit 0, because every caller of
+ // this tool gates on the parsed stdout rather than the exit code.
+ const out = execFileSync(process.execPath, [scriptPath, '--env', 'https://contoso.crm.dynamics.com', '--requir-pac'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const payload = JSON.parse(out);
+ assert.equal(payload.ok, false);
+ assert.equal(payload.blocker, 'usage');
+ assert.match(payload.message, /did you mean --require-pac\?/);
+});
+
+test('a bare --env is reported rather than treated as "no environment given"', () => {
+ const out = execFileSync(process.execPath, [scriptPath, '--env'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ const payload = JSON.parse(out);
+ assert.equal(payload.blocker, 'usage');
+ assert.match(payload.message, /--env requires a value/);
+});
+
test('check-auth.js exits 0 even on failure (output drives gating)', () => {
// The emit() helper always exits 0.
assert.match(scriptSrc, /process\.exit\(0\)/);
@@ -75,3 +106,180 @@ test('check-auth.js compares identities case-insensitively', () => {
test('check-auth.js: 403 hint mentions az login --username when identities differ', () => {
assert.match(scriptSrc, /az login --username \$\{pacUser\}/);
});
+
+// --- Decision tree: blocker classification ----------------------------------
+//
+// check-auth is the FIRST thing both skills run, and every downstream failure is interpreted
+// through its verdict. Each branch below produces a different operator instruction, so a wrong
+// classification sends the user to fix the wrong thing (e.g. "run az login" when the real problem
+// is that their identity has no access to the environment).
+
+const { loadCli } = require('./helpers/cli-harness.js');
+
+const ENVURL = 'https://contoso.crm.dynamics.com';
+
+// runQuiet() shells out via execFileSync and treats a throw as "absent". These stubs therefore
+// model each CLI as either returning stdout or throwing, exactly as a missing binary would.
+function makeExec({ azVersion = 'azure-cli 2.60.0', azUser = '[email protected]', pacOrg = null }) {
+ return (cmd, args) => {
+ const argv = (args || []).join(' ');
+ if (cmd === 'az' && argv.includes('--version')) {
+ if (azVersion === null) throw new Error('spawn az ENOENT');
+ return azVersion;
+ }
+ if (cmd === 'az' && argv.includes('account show')) {
+ if (azUser === null) throw new Error('Please run az login');
+ return azUser;
+ }
+ if (cmd === 'pac' && argv.includes('org who')) {
+ if (pacOrg === null) throw new Error('spawn pac ENOENT');
+ return pacOrg;
+ }
+ throw new Error(`unexpected command: ${cmd} ${argv}`);
+ };
+}
+
+async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows }) {
+ const cli = loadCli(scriptPath, {
+ argv,
+ requires: {
+ 'child_process': { execFileSync: makeExec(exec) },
+ './lib/dataverse-auth': {
+ parseArgs: require('../lib/dataverse-auth.js').parseArgs,
+ validateFlags: require('../lib/dataverse-auth.js').validateFlags,
+ dataverseRequest: async () => {
+ if (whoAmIThrows) throw new Error(whoAmIThrows);
+ return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };
+ },
+ },
+ },
+ });
+ // emit() always exits 0 so callers can parse stdout; the harness turns that into a throw.
+ try {
+ await cli.main();
+ } catch (e) {
+ if (e.exitCode === undefined) throw e;
+ }
+ return JSON.parse(cli.stdoutText());
+}
+
+test('a missing az CLI blocks with az_missing before anything else is probed', async () => {
+ const r = await run({ argv: ['--env', ENVURL], exec: { azVersion: null } });
+ assert.equal(r.ok, false);
+ assert.equal(r.blocker, 'az_missing');
+ assert.match(r.message, /aka\.ms\/azure-cli/);
+});
+
+test('az installed but logged out blocks with az_not_logged_in', async () => {
+ const r = await run({ argv: ['--env', ENVURL], exec: { azUser: null } });
+ assert.equal(r.blocker, 'az_not_logged_in');
+ assert.match(r.message, /az login/);
+});
+
+test('a missing pac login is a WARNING for the app-builder path, not a blocker', async () => {
+ // The build/verify/teardown flow authenticates with the az token; only the genpage pages phase
+ // shells out to pac. Blocking here would stop a build that would have worked.
+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: null } });
+ assert.equal(r.ok, true);
+ assert.equal(r.blocker, null);
+ assert.equal(r.pacUser, null);
+ assert.equal(r.warnings.length, 1);
+ assert.match(r.warnings[0], /genpage/i);
+});
+
+test('--require-pac turns the same missing pac login into a hard block', async () => {
+ const r = await run({ argv: ['--env', ENVURL, '--require-pac'], exec: { pacOrg: null } });
+ assert.equal(r.ok, false);
+ assert.equal(r.blocker, 'pac_not_logged_in');
+ assert.match(r.message, /pac auth create/);
+});
+
+test('the env URL is recovered from `pac org who` when --env is omitted', async () => {
+ // Parses the pac banner: Connected as [email protected] / Org URL: https://contoso.crm.dynamics.com/
+ const r = await run({
+ exec: { pacOrg: `Connected as [email protected]\nOrg URL: ${ENVURL}/\n` },
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.envUrl, ENVURL, 'the trailing slash is stripped');
+ assert.equal(r.pacUser, '[email protected]');
+ assert.equal(r.identitiesMatch, true);
+});
+
+test('no --env and no pac Org URL blocks with no_env_url', async () => {
+ const r = await run({ exec: { pacOrg: 'Connected as [email protected]\n' } });
+ assert.equal(r.blocker, 'no_env_url');
+ assert.match(r.message, /--env/);
+});
+
+test('a WhoAmI transport failure is whoami_error, not a 401', async () => {
+ // Distinct because the operator action differs: a transport failure is a network/URL problem,
+ // a 401 is a stale token.
+ const r = await run({ argv: ['--env', ENVURL], whoAmIThrows: 'getaddrinfo ENOTFOUND' });
+ assert.equal(r.blocker, 'whoami_error');
+ assert.match(r.message, /ENOTFOUND/);
+});
+
+test('WhoAmI 401 says refresh the token; 403 says fix access', async () => {
+ const r401 = await run({ argv: ['--env', ENVURL], whoAmI: { status: 401, data: {} } });
+ assert.equal(r401.blocker, 'whoami_401');
+ assert.match(r401.message, /az login/);
+
+ const r403 = await run({ argv: ['--env', ENVURL], whoAmI: { status: 403, data: {} } });
+ assert.equal(r403.blocker, 'whoami_403');
+});
+
+test('the 403 hint names the identity mismatch when az and pac differ', async () => {
+ // This is the single most common real cause, and the hint must name BOTH identities and the
+ // exact command to align them — a generic "access denied" sends the user to an admin instead.
+ const r = await run({
+ argv: ['--env', ENVURL],
+ exec: { azUser: '[email protected]', pacOrg: 'Connected as [email protected]\n' },
+ whoAmI: { status: 403, data: {} },
+ });
+ assert.equal(r.identitiesMatch, false);
+ assert.match(r.message, /dev@contoso\.com/);
+ assert.match(r.message, /az login --username maker@contoso\.com/);
+});
+
+test('a 403 with MATCHING identities points at environment access, not at re-login', async () => {
+ const r = await run({
+ argv: ['--env', ENVURL],
+ exec: { azUser: '[email protected]', pacOrg: 'Connected as [email protected]\n' },
+ whoAmI: { status: 403, data: {} },
+ });
+ assert.equal(r.identitiesMatch, true);
+ assert.match(r.message, /added to the env/i);
+ assert.doesNotMatch(r.message, /az login --username/);
+});
+
+test('an unexpected non-2xx status is reported with its status code', async () => {
+ const r = await run({ argv: ['--env', ENVURL], whoAmI: { status: 500, data: {} } });
+ assert.equal(r.blocker, 'whoami_error');
+ assert.match(r.message, /500/);
+ assert.equal(r.whoAmI.ok, false);
+});
+
+test('a clean run reports ok with the WhoAmI identity ids', async () => {
+ const r = await run({
+ argv: ['--env', ENVURL],
+ exec: { pacOrg: 'Connected as [email protected]\n' },
+ whoAmI: { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } },
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.blocker, null);
+ assert.deepEqual(r.whoAmI, { ok: true, userId: 'u-1', organizationId: 'o-1' });
+ assert.match(r.message, /Ready \(az \+ pac both signed in/);
+});
+
+test('a mismatched-but-working identity is reported as ready WITH the caveat', async () => {
+ // WhoAmI passed, so this is not a blocker — but entity creation can still 403 later, and the
+ // message has to carry that forward or the user has no way to connect the two events.
+ const r = await run({
+ argv: ['--env', ENVURL],
+ exec: { azUser: '[email protected]', pacOrg: 'Connected as [email protected]\n' },
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.identitiesMatch, false);
+ assert.match(r.message, /different identities/);
+ assert.match(r.message, /403/);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/content-hash.test.js b/plugins/model-apps/scripts/tests/content-hash.test.js
index 2d52b9792..4ef320eec 100644
--- a/plugins/model-apps/scripts/tests/content-hash.test.js
+++ b/plugins/model-apps/scripts/tests/content-hash.test.js
@@ -1,7 +1,7 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { annotateContentHashes, pageContentPath } = require('../lib/content-hash.js');
+const { annotateContentHashes, pageContentPath, pageSourceFileErrors } = require('../lib/content-hash.js');
const { diffPhases } = require('../lib/phase-diff.js');
// A minimal spec with one implemented tsx page + one contentPath web resource + one inline web resource.
@@ -117,3 +117,29 @@ test('pageContentPath: resolves tsx/legacy sources and returns null for intent/b
assert.strictEqual(pageContentPath({ source: { kind: 'tsx', codeFile: ' ' } }), null,
'a whitespace-only codeFile is treated as absent by normalizePageSource');
});
+
+test('pageSourceFileErrors: missing implemented page blocks while intent pages are ignored', () => {
+ const errors = pageSourceFileErrors(spec(), 'C:\\app', (absolutePath) =>
+ absolutePath.replace(/\\/g, '/').endsWith('/wr/styles.css'),
+ );
+ assert.deepStrictEqual(errors, [
+ "page 'overview': codeFile 'pages/overview.tsx' does not exist or is not a file",
+ ]);
+});
+
+test('pageSourceFileErrors: an existing implemented page passes', () => {
+ assert.deepStrictEqual(pageSourceFileErrors(spec(), 'C:\\app', () => true), []);
+});
+
+test('pageSourceFileErrors: a lexically confined link resolving outside the workspace is rejected', () => {
+ const errors = pageSourceFileErrors(spec(), 'C:\\app', {
+ isFile: () => true,
+ realpath: (absolutePath) =>
+ absolutePath.replace(/\\/g, '/').endsWith('/pages/overview.tsx')
+ ? 'C:\\outside\\overview.tsx'
+ : 'C:\\app',
+ });
+ assert.deepStrictEqual(errors, [
+ "page 'overview': codeFile 'pages/overview.tsx' resolves outside the workspace",
+ ]);
+});
diff --git a/plugins/model-apps/scripts/tests/create-connection-reference.test.js b/plugins/model-apps/scripts/tests/create-connection-reference.test.js
index 134d280d2..1a148ad85 100644
--- a/plugins/model-apps/scripts/tests/create-connection-reference.test.js
+++ b/plugins/model-apps/scripts/tests/create-connection-reference.test.js
@@ -18,22 +18,112 @@ test('binds connectorid and logical name', () => {
});
test('missing args exits 1 with usage', () => {
- // Enable connectors so the run reaches arg validation instead of the feature gate.
- const res = spawnSync(process.execPath, [scriptPath], {
- encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
- });
+ const res = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });
assert.equal(res.status, 1);
assert.match(res.stderr, /Usage:/);
});
-test('exits 3 with a disabled message when the connectors flag is OFF', () => {
- // Gate runs before any Dataverse call, so complete args still bail out early.
+test('the rollback switch still works end to end (exit 3 before any Dataverse call)', () => {
const res = spawnSync(
process.execPath,
- [scriptPath, 'https://example.crm.dynamics.com', 'new_x', '/providers/Microsoft.PowerApps/apis/shared_x'],
+ [scriptPath, 'https://contoso.crm.dynamics.com', 'new_x', '/providers/Microsoft.PowerApps/apis/shared_x'],
{ encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }
);
assert.equal(res.status, 3);
assert.match(res.stderr, /disabled/i);
});
+
+// --- Wire-level contract ----------------------------------------------------
+
+const { loadCli } = require('./helpers/cli-harness.js');
+const ENV = 'https://contoso.crm.dynamics.com';
+const SP = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+
+function harness({ argv, response }) {
+ const calls = [];
+ const emitted = [];
+ const real = require('../lib/dataverse-auth.js');
+ const authStub = {
+ parseArgs: real.parseArgs,
+ validateFlags: real.validateFlags,
+ ensureOk: (res, what) => {
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`${what} failed: ${res && res.status}`);
+ },
+ emitResult: (ok, payload) => { emitted.push({ ok, payload }); },
+ dataverseRequest: async (envUrl, method, p, body, opts) => {
+ calls.push({ envUrl, method, path: p, body, opts });
+ return response || { status: 204, headers: {}, data: {} };
+ },
+ };
+ const cli = loadCli(scriptPath, { requires: { './lib/dataverse-auth': authStub }, argv });
+ return { cli, calls, emitted };
+}
+
+test('POSTs the connection reference with logical name, display name and connector id', async () => {
+ const { cli, calls } = harness({
+ argv: [ENV, 'new_sp', SP, '--display-name', 'Team Docs'],
+ response: { status: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.2/connectionreferences(11111111-2222-3333-4444-555555555555)` }, data: {} },
+ });
+ await cli.main();
+ assert.equal(calls[0].method, 'POST');
+ assert.equal(calls[0].path, 'connectionreferences');
+ assert.deepEqual(calls[0].body, {
+ connectionreferencelogicalname: 'new_sp',
+ connectionreferencedisplayname: 'Team Docs',
+ connectorid: SP,
+ });
+ // includeHeaders is required: the new row's id only comes back on the OData-EntityId header.
+ assert.equal(calls[0].opts.includeHeaders, true);
+});
+
+test('the display name defaults to the logical name when not supplied', async () => {
+ const { cli, calls } = harness({ argv: [ENV, 'new_sp', SP] });
+ await cli.main();
+ assert.equal(calls[0].body.connectionreferencedisplayname, 'new_sp');
+});
+
+test('--connection-id binds immediately; omitting it leaves the ref unbound for ALM to fill', async () => {
+ const bound = harness({ argv: [ENV, 'new_sp', SP, '--connection-id', 'conn-1'] });
+ await bound.cli.main();
+ assert.equal(bound.calls[0].body.connectionid, 'conn-1');
+
+ const unbound = harness({ argv: [ENV, 'new_sp', SP] });
+ await unbound.cli.main();
+ // Absent, not null/empty: a deployment-settings import supplies the target-env ConnectionId, and
+ // sending an explicit null would overwrite that.
+ assert.ok(!Object.prototype.hasOwnProperty.call(unbound.calls[0].body, 'connectionid'));
+});
+
+test('the new row id is parsed from the OData-EntityId header, in either header casing', async () => {
+ // Dataverse returns: OData-EntityId: https://org/api/data/v9.2/connectionreferences(<guid>)
+ // Node lower-cases response headers, but the raw casing shows up through some transports, so
+ // both spellings must resolve or the caller silently gets connectionReferenceId: null.
+ for (const key of ['odata-entityid', 'OData-EntityId']) {
+ const { cli, emitted } = harness({
+ argv: [ENV, 'new_sp', SP],
+ response: { status: 204, headers: { [key]: `${ENV}/api/data/v9.2/connectionreferences(11111111-2222-3333-4444-555555555555)` }, data: {} },
+ });
+ await cli.main();
+ assert.equal(emitted[0].ok, true);
+ assert.equal(emitted[0].payload.connectionReferenceId, '11111111-2222-3333-4444-555555555555', `casing: ${key}`);
+ assert.equal(emitted[0].payload.logicalName, 'new_sp');
+ }
+});
+
+test('a missing or unparseable entity header yields a null id rather than a crash', async () => {
+ for (const headers of [{}, { 'odata-entityid': 'not-a-url' }]) {
+ const { cli, emitted } = harness({ argv: [ENV, 'new_sp', SP], response: { status: 204, headers, data: {} } });
+ await cli.main();
+ assert.equal(emitted[0].ok, true, 'the row WAS created — only its id is unknown');
+ assert.equal(emitted[0].payload.connectionReferenceId, null);
+ }
+});
+
+test('a non-2xx create is reported as a failure, not a success with a null id', async () => {
+ const { cli, emitted } = harness({
+ argv: [ENV, 'new_sp', SP],
+ response: { status: 400, headers: {}, data: { error: { message: 'duplicate logical name' } } },
+ });
+ await cli.main();
+ assert.equal(emitted[0].ok, false);
+});
diff --git a/plugins/model-apps/scripts/tests/dataverse-request.test.js b/plugins/model-apps/scripts/tests/dataverse-request.test.js
index 5074a0719..285e2a5a9 100644
--- a/plugins/model-apps/scripts/tests/dataverse-request.test.js
+++ b/plugins/model-apps/scripts/tests/dataverse-request.test.js
@@ -32,6 +32,7 @@ function runCli(args, { errorMessage = null } = {}) {
if (resolved === authPath) {
return {
parseArgs: realAuth.parseArgs,
+ validateFlags: realAuth.validateFlags,
readJsonArg: realAuth.readJsonArg,
dataverseRequest: async (envUrl, method, apiPath, body, opts) => {
if (${JSON.stringify(errorMessage)} !== null) throw new Error(${JSON.stringify(errorMessage)});
@@ -101,7 +102,7 @@ test('--timeout without a value is rejected before the Dataverse request is invo
const res = runCli(['https://org.crm.dynamics.com', 'GET', 'accounts', '--timeout']);
assert.equal(res.status, 1);
- assert.match(res.stderr, /--timeout must include a positive millisecond value/);
+ assert.match(res.stderr, /--timeout requires a value — a positive millisecond value/);
assert.equal(res.stdout, '');
});
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index baa79a620..c7c9d14a4 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -6,7 +6,7 @@ const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const { untypedColumnNames, resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, iconWebResources, readDashboards, droppedSubareaCount, preserveAuthoredLanguageCode } = require('../download-model-app.js');
+const { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, resolveAppId, collectSitemap, parseDownloadedPages, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, iconWebResources, readDashboards, droppedSubareaCount, preserveAuthoredLanguageCode } = require('../download-model-app.js');
test('resolveAppId returns a guid as-is, else resolves by uniquename', async () => {
const guid = '11111111-2222-3333-4444-555555555555';
@@ -249,7 +249,7 @@ test('readEntityWithDescriptions reads descriptions through the RAW dataverse cl
// The $select also carries the DISPLAY labels now, so a table/column labelled in more than one
// language round-trips (AB#6686428). The SDK's flattened `displayName` keeps only one.
assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName$/.test(u)), `table read URL wrong: ${gets.join(' | ')}`);
- assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);
+ assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeTypeName$/.test(u)), `attribute read URL wrong: ${gets.join(' | ')}`);
assert.strictEqual(e.description, 'Order table purpose.');
const status = e.columns.find((c) => c.schemaName === 'new_status');
assert.strictEqual(status.description, 'State shown to dispatchers.');
@@ -397,6 +397,194 @@ test('a downloaded Choice column is reported as untyped, so the Text downgrade i
assert.deepStrictEqual(untypedColumnNames([entityFromMetadata(meta, 'new_ticket')]), ['new_ticket.new_status']);
});
+// ---------------------------------------------------------------------------
+// #564 — Choice / MultiChoice column TYPES survive a download.
+// ---------------------------------------------------------------------------
+
+// A picklist attribute row exactly as Dataverse returns it through the cast + $expand. LIVE-MEASURED
+// against a stock org on `account.accountcategorycode`:
+// { "LogicalName": "accountcategorycode",
+// "OptionSet": { "Name": "account_accountcategorycode", "IsGlobal": false,
+// "Options": [ { "Value": 1, "Label": { "LocalizedLabels": [ { Label, LanguageCode } ],
+// "UserLocalizedLabel": { "Label": "Preferred Customer" } } } ] },
+// "GlobalOptionSet": { "Name": "account_accountcategorycode", "MetadataId": "..." } }
+// Note GlobalOptionSet is populated even though IsGlobal is FALSE — the trap pinned below.
+function picklistRow(logicalName, { name, isGlobal, options, globalEcho = true }) {
+ const label = (l) => (typeof l === 'string'
+ ? { LocalizedLabels: [{ Label: l, LanguageCode: 1033 }], UserLocalizedLabel: { Label: l, LanguageCode: 1033 } }
+ : { LocalizedLabels: Object.entries(l).map(([lcid, text]) => ({ Label: text, LanguageCode: Number(lcid) })), UserLocalizedLabel: { Label: l['1033'], LanguageCode: 1033 } });
+ return {
+ LogicalName: logicalName,
+ OptionSet: { Name: name, IsGlobal: isGlobal, Options: options.map(([value, l]) => ({ Value: value, Label: label(l) })) },
+ ...(globalEcho ? { GlobalOptionSet: { Name: name, MetadataId: 'aaaaaaaa-0000-0000-0000-000000000001' } } : {}),
+ };
+}
+
+// An sdk whose RAW client answers the description reads AND the two picklist cast reads.
+function sdkWithOptionSets({ attributes, picklist = [], multiSelect = [], optionSetStatus = 200, urls = [], throwOnOptionSets = false }) {
+ return {
+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name', attributes }),
+ queryRecords: async (set) => { throw new Error("queryRecords must not be used for metadata paths (got '" + set + "')"); },
+ dataverse: {
+ get: async (url) => {
+ urls.push(url);
+ if (/AttributeMetadata/.test(url)) {
+ if (throwOnOptionSets) throw new Error('metadata read blew up');
+ const rows = /MultiSelectPicklistAttributeMetadata/.test(url) ? multiSelect : picklist;
+ return { status: optionSetStatus, headers: {}, body: { value: rows } };
+ }
+ if (/\/Attributes\?/.test(url)) return { status: 200, headers: {}, body: { value: [] } };
+ return { status: 200, headers: {}, body: {} };
+ },
+ },
+ };
+}
+
+const CHOICE_ATTRS = [
+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'new_notes', displayName: 'Notes', attributeType: 'Memo', isCustomAttribute: true },
+];
+
+test('#564 a LOCAL option set downloads as a real Choice with inline options[], not an untyped column', async () => {
+ const urls = [];
+ const sdk = sdkWithOptionSets({
+ attributes: CHOICE_ATTRS,
+ picklist: [picklistRow('new_status', { name: 'new_ticket_new_status', isGlobal: false, options: [[100000000, 'Open'], [100000001, 'Closed']] })],
+ urls,
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_ticket'), 'new_ticket');
+ const status = e.columns.find((c) => c.schemaName === 'new_status');
+ assert.strictEqual(status.type, 'Choice');
+ // Plain label strings, in the order Dataverse returned them — the App Spec assigns
+ // value = 100000000 + index, so the ARRAY ORDER is semantics, not presentation.
+ assert.deepStrictEqual(status.options, ['Open', 'Closed']);
+ assert.strictEqual(status.globalChoice, undefined, 'a local set must not emit a globalChoice reference');
+ // The column is no longer reported as untyped — that warning exists for columns we cannot type.
+ assert.deepStrictEqual(untypedColumnNames([e]), []);
+ // The cast segment is required: Attributes is a heterogeneous collection, so OptionSet can only be
+ // expanded through it. Pin the exact URL so a silent shape change is caught here, not live.
+ assert.ok(
+ urls.some((u) => u === "/EntityDefinitions(LogicalName='new_ticket')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,IsGlobal,Options)"),
+ 'picklist read URL wrong: ' + urls.join(' | ')
+ );
+});
+
+test('#564 GlobalOptionSet being present does NOT make a local set global (live-measured trap)', async () => {
+ // Measured on a live org: a LOCAL set (IsGlobal:false) still returns a populated GlobalOptionSet
+ // echoing its own name. Keying off GlobalOptionSet would emit a globalChoice reference to a shared
+ // set that does not exist, and the rebuild would bind the column to nothing.
+ const sdk = sdkWithOptionSets({
+ attributes: CHOICE_ATTRS,
+ picklist: [picklistRow('new_status', { name: 'new_ticket_new_status', isGlobal: false, options: [[1, 'Open']], globalEcho: true })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_ticket'), 'new_ticket');
+ const status = e.columns.find((c) => c.schemaName === 'new_status');
+ assert.strictEqual(status.globalChoice, undefined);
+ assert.deepStrictEqual(status.options, ['Open']);
+});
+
+test('#564 a GLOBAL-bound picklist emits a globalChoice reference instead of inline options', async () => {
+ const sdk = sdkWithOptionSets({
+ attributes: CHOICE_ATTRS,
+ picklist: [picklistRow('new_status', { name: 'shared_stage', isGlobal: true, options: [[1, 'Draft'], [2, 'Final']] })],
+ });
+ const meta = await readEntityWithDescriptions(sdk, 'new_ticket');
+ const e = entityFromMetadata(meta, 'new_ticket');
+ const status = e.columns.find((c) => c.schemaName === 'new_status');
+ assert.strictEqual(status.type, 'Choice');
+ assert.strictEqual(status.globalChoice, 'shared_stage');
+ assert.strictEqual(status.options, undefined, 'a global-bound column must not ALSO carry inline options');
+ // The shared set itself has to be declared, or a fresh-environment rebuild has nothing to bind to.
+ const decls = new Map();
+ collectGlobalChoices(meta, decls);
+ assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Draft', 'Final'] }]);
+});
+
+test('#564 a MultiSelect picklist downloads as MultiChoice', async () => {
+ const sdk = sdkWithOptionSets({
+ attributes: [{ logicalName: 'new_tags', displayName: 'Tags', attributeType: 'MultiSelectPicklist', isCustomAttribute: true }],
+ multiSelect: [picklistRow('new_tags', { name: 'new_ticket_new_tags', isGlobal: false, options: [[1, 'Urgent'], [2, 'Billable']] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_ticket'), 'new_ticket');
+ const tags = e.columns.find((c) => c.schemaName === 'new_tags');
+ assert.strictEqual(tags.type, 'MultiChoice');
+ assert.deepStrictEqual(tags.options, ['Urgent', 'Billable']);
+});
+
+test('#564 inline options keep their localizations, but a global declaration is flattened', async () => {
+ // Inline columns[].options[] localizes correctly; globalChoices[] options are REJECTED by
+ // validateAppSpec when localized, because Dataverse stores only the base language for a shared set.
+ // So the same Label object must be emitted two different ways depending on where it lands.
+ const localized = { 1033: 'Open', 3082: 'Abierto' };
+ const sdk = sdkWithOptionSets({
+ attributes: [
+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'new_stage', displayName: 'Stage', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ picklist: [
+ picklistRow('new_status', { name: 'new_ticket_new_status', isGlobal: false, options: [[1, localized]] }),
+ picklistRow('new_stage', { name: 'shared_stage', isGlobal: true, options: [[1, localized]] }),
+ ],
+ });
+ const meta = await readEntityWithDescriptions(sdk, 'new_ticket');
+ const e = entityFromMetadata(meta, 'new_ticket');
+ assert.deepStrictEqual(e.columns.find((c) => c.schemaName === 'new_status').options, [{ 1033: 'Open', 3082: 'Abierto' }]);
+ const decls = new Map();
+ collectGlobalChoices(meta, decls);
+ assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Open'] }]);
+});
+
+test('#564 one global set bound by two columns is declared exactly once', async () => {
+ const sdk = sdkWithOptionSets({
+ attributes: [
+ { logicalName: 'new_a', displayName: 'A', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'new_b', displayName: 'B', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ picklist: [
+ picklistRow('new_a', { name: 'shared_stage', isGlobal: true, options: [[1, 'Draft']] }),
+ picklistRow('new_b', { name: 'shared_stage', isGlobal: true, options: [[1, 'Draft']] }),
+ ],
+ });
+ const decls = new Map();
+ collectGlobalChoices(await readEntityWithDescriptions(sdk, 'new_ticket'), decls);
+ assert.strictEqual(decls.size, 1);
+});
+
+test('#564 a FAILED option-set read leaves the column untyped rather than guessing a type', async () => {
+ // Fail-safe, and the reason the untyped warning survives this change: emitting type "Choice" with
+ // no options[] produces a spec that fails its OWN validation, and guessing options invents data.
+ // A non-2xx and a throw must land on the same untyped outcome.
+ for (const variant of [{ optionSetStatus: 403 }, { throwOnOptionSets: true }]) {
+ const sdk = sdkWithOptionSets({ attributes: CHOICE_ATTRS, ...variant });
+ const meta = await readEntityWithDescriptions(sdk, 'new_ticket');
+ const e = entityFromMetadata(meta, 'new_ticket');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'new_status').type, undefined, JSON.stringify(variant));
+ assert.deepStrictEqual(untypedColumnNames([e]), ['new_ticket.new_status'], JSON.stringify(variant));
+ // The failure is RECORDED, not swallowed — a silent degrade here is the bug being fixed.
+ assert.ok(meta.optionSetReadFailed, 'the read failure was not recorded for ' + JSON.stringify(variant));
+ }
+});
+
+test('#564 a picklist the option-set read did not cover stays untyped', async () => {
+ // A 200 that simply omits the attribute is NOT evidence of "no options" — it is evidence we did
+ // not see them. Typing it anyway would emit an invalid spec.
+ const sdk = sdkWithOptionSets({ attributes: CHOICE_ATTRS, picklist: [] });
+ const meta = await readEntityWithDescriptions(sdk, 'new_ticket');
+ const e = entityFromMetadata(meta, 'new_ticket');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'new_status').type, undefined);
+ assert.deepStrictEqual(untypedColumnNames([e]), ['new_ticket.new_status']);
+});
+
+test('#564 an option set with no usable labels is not emitted as an empty Choice', async () => {
+ // An option whose Label carries no usable text would emit options: [undefined], which fails
+ // validateAppSpec ("options[0] must be a non-empty string"). Refuse to type it instead.
+ const sdk = sdkWithOptionSets({
+ attributes: CHOICE_ATTRS,
+ picklist: [{ LogicalName: 'new_status', OptionSet: { Name: 'new_ticket_new_status', IsGlobal: false, Options: [{ Value: 1, Label: { LocalizedLabels: [], UserLocalizedLabel: null } }] } }],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_ticket'), 'new_ticket');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'new_status').type, undefined);
+});
test('iconWebResources looks up web resources by NAME (not id) and maps type from webresourcetype', async () => {
const calls = [];
const sdk = {
@@ -571,8 +759,48 @@ test('readDescriptionInventory captures view, chart, form, business-rule, and gl
assert.ok(calls.some((c) => c.set === 'savedqueryvisualization' && c.opts.select.includes('description')), 'chart read selects description');
assert.ok(calls.some((c) => c.set === 'systemform' && c.opts.select.includes('description')), 'form read selects description');
assert.ok(calls.some((c) => c.set === 'workflow' && c.opts.select.includes('description')), 'business-rule read selects description');
- assert.ok(calls.some((c) => c.get === '/GlobalOptionSetDefinitions?$select=Name,Description'),
- `global choices must be read through the RAW client (queryRecords cannot take a metadata path); calls: ${JSON.stringify(calls.map((c) => c.get || c.set))}`);
+ assert.ok(calls.some((c) => c.get === '/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged'),
+ `global choices must be read through the RAW client (queryRecords cannot take a metadata path), selecting IsManaged so managed sets can be excluded; calls: ${JSON.stringify(calls.map((c) => c.get || c.set))}`);
+});
+
+test('the global-choice inventory excludes MANAGED option sets but keeps an unknown flag', async () => {
+ // A managed global choice ships with its solution and exists in any environment that has that
+ // solution, so naming it as "not round-tripped" is false — there is nothing for a rebuild to
+ // recreate. Measured live on a stock environment: 149 option sets, exactly 1 unmanaged, so
+ // reporting all of them buried the real findings under 148 unactionable lines.
+ //
+ // `$filter` cannot do this server-side: GlobalOptionSetDefinitions answers HTTP 405
+ // (0x80060888) for `?$filter=IsManaged eq false`, which is why the filter is client-side.
+ const sdk = {
+ queryRecords: async () => [],
+ dataverse: {
+ get: async (url) => {
+ if (/^\/GlobalOptionSetDefinitions\?/.test(url)) {
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ value: [
+ { Name: 'new_priority', IsManaged: false },
+ { Name: 'msdyn_solutionhealthruleseverity', IsManaged: true },
+ { Name: 'legacy_noflag' }, // IsManaged absent — must be KEPT, not silently dropped
+ ],
+ },
+ };
+ }
+ return { status: 404, headers: {}, body: {} };
+ },
+ },
+ };
+
+ const inv = await readDescriptionInventory(sdk, 'app-1', 'ContosoSolution');
+ const names = (inv.globalChoices || []).map((c) => c.name);
+ assert.ok(names.includes('new_priority'), 'an unmanaged choice is genuinely not round-tripped');
+ assert.ok(!names.includes('msdyn_solutionhealthruleseverity'), 'a managed choice must not be reported');
+ assert.ok(
+ names.includes('legacy_noflag'),
+ 'an ABSENT IsManaged must keep the row — this inventory must not assert an absence it cannot substantiate'
+ );
});
test('readDashboards keeps the sitemap title when the dashboard name lookup fails', async () => {
@@ -1524,3 +1752,461 @@ test('#514: a tenant without the setting definitions still downloads cleanly', a
const throws = { queryRecords: async () => { throw new Error('no access to appsettings'); } };
assert.deepStrictEqual(await readAppShellSettings(throws, 'app-1'), {});
});
+
+// ---------------------------------------------------------------------------
+// #564 — the emitted spec must be valid, and the reports must stay truthful.
+// ---------------------------------------------------------------------------
+
+test('#564 a downloaded spec carrying Choice/MultiChoice types still passes validateAppSpec', async () => {
+ // The companion rule is the whole reason the type used to be dropped: declaring type "Choice"
+ // obliges the column to carry options[] or a globalChoice, and a spec that fails its own gate is
+ // useless. This is the positive counterpart to the long-standing "must not claim a type it cannot
+ // substantiate" test — now that we CAN substantiate it, the result still has to validate.
+ const { validateAppSpec: validate } = require('../lib/app-spec.js');
+ const sdk = sdkWithOptionSets({
+ attributes: [
+ { logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'new_tags', displayName: 'Tags', attributeType: 'MultiSelectPicklist', isCustomAttribute: true },
+ { logicalName: 'new_stage', displayName: 'Stage', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ picklist: [
+ picklistRow('new_status', { name: 'new_ticket_new_status', isGlobal: false, options: [[1, 'Open'], [2, 'Closed']] }),
+ picklistRow('new_stage', { name: 'shared_stage', isGlobal: true, options: [[1, 'Draft'], [2, 'Final']] }),
+ ],
+ multiSelect: [picklistRow('new_tags', { name: 'new_ticket_new_tags', isGlobal: false, options: [[1, 'Urgent']] })],
+ });
+ const meta = await readEntityWithDescriptions(sdk, 'new_ticket');
+ const decls = new Map();
+ collectGlobalChoices(meta, decls);
+ const res = validate({
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'A' },
+ entities: [entityFromMetadata(meta, 'new_ticket')],
+ globalChoices: [...decls.values()],
+ appShell: { areas: [] },
+ }, { profile: 'deploy' });
+ assert.deepStrictEqual(res.errors, [], res.errors.join(' | '));
+});
+
+test('#564 roundTrippedAware stops the report claiming a DECLARED global choice was left behind', () => {
+ const { roundTrippedAware: aware } = require('../download-model-app.js');
+ const inventory = { globalChoices: [{ name: 'shared_stage' }, { name: 'untouched_set' }], forms: [{ name: 'F', entity: 'new_ticket' }] };
+ const decls = new Map([['shared_stage', { name: 'shared_stage', options: ['Draft'] }]]);
+ // The set the spec now declares IS carried forward, so reporting it as lost would be false. Every
+ // other set in the environment stays listed — the app does not bind it, so a rebuild will not
+ // recreate it, and that claim is still true.
+ assert.deepStrictEqual(aware(inventory, decls).globalChoices, [{ name: 'untouched_set' }]);
+ assert.deepStrictEqual(aware(inventory, decls).forms, [{ name: 'F', entity: 'new_ticket' }], 'unrelated classes must be untouched');
+ // Nothing left -> the KEY goes, not an empty array: notRoundTrippedSummary skips an empty class,
+ // and `globalChoices: []` would be indistinguishable from "the read returned no rows".
+ const allDeclared = aware({ globalChoices: [{ name: 'shared_stage' }] }, decls);
+ assert.ok(!('globalChoices' in allDeclared), 'an emptied class must be dropped, not left as []');
+ // Case-insensitive: Dataverse does not guarantee the casing of a returned option-set Name.
+ assert.ok(!('globalChoices' in aware({ globalChoices: [{ name: 'SHARED_STAGE' }] }, decls)));
+ // No declarations -> the inventory is returned untouched (identity, not a rebuilt copy).
+ assert.strictEqual(aware(inventory, new Map()), inventory);
+});
+
+test('#564 hydrateSpec emits globalChoices ONLY when the app actually binds one', async () => {
+ const { hydrateSpec: hydrate } = require('../lib/hydrate-spec.js');
+ const base = {
+ app: async () => ({ name: 'A', description: '', siteMap: { areas: [] } }),
+ pages: async () => [],
+ entities: async () => [],
+ webResources: async () => [],
+ solution: async () => ({ uniqueName: 'S', publisherPrefix: 'new' }),
+ };
+ const withNone = await hydrate(base);
+ // An empty `globalChoices: []` on every download would read as a positive claim that the app binds
+ // no shared choices — which a download whose option-set read failed cannot substantiate.
+ assert.ok(!('globalChoices' in withNone), 'an app binding no shared choice must not emit the key');
+ const withSome = await hydrate({ ...base, globalChoices: async () => [{ name: 'shared_stage', options: ['Draft'] }] });
+ assert.deepStrictEqual(withSome.globalChoices, [{ name: 'shared_stage', options: ['Draft'] }]);
+ // A legacy `read` with no globalChoices accessor must still hydrate (back-compat).
+ assert.ok(!('globalChoices' in (await hydrate({ ...base, globalChoices: undefined }))));
+});
+test('#564 option ORDER is Dataverse display order, not Value order', async () => {
+ // Dataverse returns options in their DISPLAY order, and the App Spec assigns
+ // value = 100000000 + index — so the array order is what a rebuild reproduces in the picker.
+ // Sorting by Value here would silently reorder any set whose author arranged it by hand. Values
+ // are deliberately DESCENDING so a sort would be visible.
+ //
+ // Driven through readEntityWithDescriptions ON PURPOSE: the ordering decision lives in the READ
+ // (optionSetFromRow), so a test that pre-attaches `optionSet` to the metadata proves nothing — an
+ // earlier version of this test did exactly that and a value-sort mutation survived it.
+ const sdk = sdkWithOptionSets({
+ attributes: [{ logicalName: 'new_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true }],
+ picklist: [picklistRow('new_status', { name: 'new_ticket_new_status', isGlobal: false, options: [[9, 'Last'], [3, 'Middle'], [1, 'First']] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'new_ticket'), 'new_ticket');
+ assert.deepStrictEqual(e.columns.find((c) => c.schemaName === 'new_status').options, ['Last', 'Middle', 'First']);
+});
+test('#564 a MultiChoice column is NOT dropped even though Dataverse types it as "Virtual"', async () => {
+ // LIVE-MEASURED on a real table. A MultiSelectPicklist attribute reports:
+ // { "LogicalName": "pp_tags", "AttributeType": "Virtual", "AttributeTypeName": "MultiSelectPicklistType" }
+ // while its synthetic formatted-value shadow reports:
+ // { "LogicalName": "pp_tagsname", "AttributeType": "Virtual", "AttributeTypeName": "VirtualType" }
+ // The SDK projection carries only `attributeType`, so BOTH looked like "Virtual" — a type the App
+ // Spec cannot declare — and the real MultiChoice column was filtered out of columns[] ENTIRELY.
+ // That is worse than the untyped degrade #564 describes: the column vanished from the spec, so a
+ // rebuild did not create it at all. The MultiSelect CAST read is the discriminator: only a genuine
+ // multi-select comes back from it, so an attribute it returned is a MultiChoice whatever
+ // `attributeType` claims. The `*name` shadow is absent from every cast read and stays filtered.
+ const sdk = sdkWithOptionSets({
+ attributes: [
+ { logicalName: 'pp_tags', displayName: 'Tags', attributeType: 'Virtual', isCustomAttribute: true },
+ { logicalName: 'pp_tagsname', displayName: 'Tags Name', attributeType: 'Virtual', isCustomAttribute: true },
+ { logicalName: 'pp_stagename', displayName: 'Stage Name', attributeType: 'Virtual', isCustomAttribute: true },
+ ],
+ multiSelect: [picklistRow('pp_tags', { name: 'pp_item_pp_tags', isGlobal: false, options: [[1, 'Urgent'], [2, 'Billable']] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_item'), 'pp_item');
+ const tags = e.columns.find((c) => c.schemaName === 'pp_tags');
+ assert.ok(tags, 'the MultiChoice column was dropped from columns[]');
+ assert.strictEqual(tags.type, 'MultiChoice');
+ assert.deepStrictEqual(tags.options, ['Urgent', 'Billable']);
+ // The synthetic shadows must STILL be filtered out: emitting them would feed defaultViewColumns
+ // and rewrite the table's default views with junk.
+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['pp_tags']);
+});
+
+test('#564 a Virtual attribute with NO option set is still filtered out', async () => {
+ // The relaxation above must be driven by the presence of companion data, not by the type name —
+ // otherwise every platform Virtual attribute would start appearing in columns[].
+ const sdk = sdkWithOptionSets({
+ attributes: [{ logicalName: 'pp_shadow', displayName: 'Shadow', attributeType: 'Virtual', isCustomAttribute: true }],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_item'), 'pp_item');
+ assert.deepStrictEqual(e.columns, []);
+});
+test('#564 the CAST type outranks the attributeType map (defensive precedence)', async () => {
+ // Today this precedence is not observable: the only disagreement measured in the wild is a
+ // MultiSelectPicklist reporting `Virtual`, which the map does not contain at all — so either order
+ // produces MultiChoice, and a mutation that swaps them survives the other tests. It is pinned
+ // anyway because the ordering is a deliberate contract, not an accident: the cast segment is
+ // direct evidence of what the attribute IS, while `attributeType` has already been observed to
+ // misreport it once. A future cleanup that "simplifies" the order should fail here.
+ const sdk = sdkWithOptionSets({
+ attributes: [{ logicalName: 'pp_odd', displayName: 'Odd', attributeType: 'Picklist', isCustomAttribute: true }],
+ multiSelect: [picklistRow('pp_odd', { name: 'pp_item_pp_odd', isGlobal: false, options: [[1, 'A']] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_item'), 'pp_item');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_odd').type, 'MultiChoice',
+ 'the map said Choice and the multi-select cast said MultiChoice — the cast must win');
+});
+test('#564 a lookup name SHADOW is filtered out, but a logical CHOICE column is kept', async () => {
+ // LIVE-MEASURED. Creating a lookup `pp_parentorgid` also creates a synthetic formatted-name
+ // attribute `pp_parentorgidname`:
+ // { AttributeType: "String", AttributeTypeName: "StringType", IsCustomAttribute: true, IsLogical: true }
+ // It reports IsCustomAttribute TRUE, so the custom-only filter let it through, and its String type
+ // maps cleanly to Text — so a downloaded spec declared a REAL Text column named after a lookup's
+ // shadow. Measured consequence on a fresh-environment rebuild: the build happily created
+ // `pp563_org2.pp563_parentorgidname (Text)`, an invented column that also collides with the name
+ // the real lookup's shadow needs. It is IsLogical (not stored on this table), which is what makes
+ // it distinguishable.
+ //
+ // The rule is deliberately "logical AND no option set", NOT plain "logical": on `account`, 6 REAL
+ // choice columns (address1_addresstypecode, address1_freighttermscode, address1_shippingmethodcode
+ // and their address2_ twins) are themselves IsLogical, because they live on the address entity and
+ // surface logically here. Dropping every logical attribute would delete real Choice columns from
+ // the spec — reintroducing exactly the silent column-loss this change exists to end.
+ const sdk = {
+ fetchEntityMetadata: async () => ({
+ logicalName: 'pp_org', schemaName: 'pp_org', displayName: 'Org', primaryNameAttribute: 'pp_name',
+ attributes: [
+ { logicalName: 'pp_parentorgidname', displayName: 'Parent Org Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'pp_real', displayName: 'Real', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'pp_addrtype', displayName: 'Address Type', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ }),
+ dataverse: {
+ get: async (url) => {
+ if (/MultiSelectPicklistAttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: [] } };
+ if (/PicklistAttributeMetadata/.test(url)) {
+ return { status: 200, headers: {}, body: { value: [picklistRow('pp_addrtype', { name: 'pp_addrtype_set', isGlobal: false, options: [[1, 'Bill To'], [2, 'Ship To']] })] } };
+ }
+ if (/\/Attributes\?/.test(url)) {
+ return { status: 200, headers: {}, body: { value: [
+ { LogicalName: 'pp_parentorgidname', IsLogical: true },
+ { LogicalName: 'pp_real', IsLogical: false },
+ // A REAL choice column that is nonetheless logical — must survive.
+ { LogicalName: 'pp_addrtype', IsLogical: true },
+ ] } };
+ }
+ return { status: 200, headers: {}, body: {} };
+ },
+ },
+ };
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_org'), 'pp_org');
+ const names = e.columns.map((c) => c.schemaName);
+ assert.ok(!names.includes('pp_parentorgidname'), 'the lookup name shadow must not be emitted as a real Text column');
+ assert.ok(names.includes('pp_real'), 'a normal custom column must survive');
+ assert.ok(names.includes('pp_addrtype'), 'a LOGICAL column that carries an option set is a real Choice and must survive');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_addrtype').type, 'Choice');
+});
+
+test('#564 an attribute whose IsLogical could not be read is KEPT, not dropped', async () => {
+ // Fail-safe: an absent flag means "we could not look", and dropping a real column on that basis is
+ // the more destructive error. Same reasoning as the existing isCustomAttribute handling, which
+ // drops only on an explicit `false`.
+ const sdk = sdkWithOptionSets({
+ attributes: [{ logicalName: 'pp_real', displayName: 'Real', attributeType: 'String', isCustomAttribute: true }],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_org'), 'pp_org');
+ assert.deepStrictEqual(e.columns.map((c) => c.schemaName), ['pp_real']);
+});
+// ---------------------------------------------------------------------------
+// Review round: findings from the adversarial review of the #564 work.
+// ---------------------------------------------------------------------------
+
+// Builds the `/Attributes?$select=...` row the label/shape read returns.
+const attrRow = (logicalName, { isLogical = false, typeName = undefined } = {}) => ({
+ LogicalName: logicalName,
+ ...(isLogical !== undefined ? { IsLogical: isLogical } : {}),
+ ...(typeName ? { AttributeTypeName: { Value: typeName } } : {}),
+});
+
+// An sdk with FULL control of both reads: the attribute shape read and the two casts.
+function sdkFull({ attributes, attrRows = [], picklist = [], multiSelect = [], picklistStatus = 200, multiSelectStatus = 200, attrStatus = 200 }) {
+ return {
+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, schemaName: logical, displayName: 'T', primaryNameAttribute: 'pp_name', attributes }),
+ dataverse: {
+ get: async (url) => {
+ if (/MultiSelectPicklistAttributeMetadata/.test(url)) return { status: multiSelectStatus, headers: {}, body: { value: multiSelect } };
+ if (/PicklistAttributeMetadata/.test(url)) return { status: picklistStatus, headers: {}, body: { value: picklist } };
+ if (/\/Attributes\?/.test(url)) return { status: attrStatus, headers: {}, body: { value: attrRows } };
+ return { status: 200, headers: {}, body: {} };
+ },
+ },
+ };
+}
+
+test('REVIEW-A a cross-language AMBIGUOUS option set leaves the column untyped instead of aborting the whole download', async () => {
+ // Reported by adversarial review, proven reachable. Option labels need not be unique across
+ // options OR languages in Dataverse, so this set is legal:
+ // options[0] = "Open" (English only)
+ // options[1] = { 1033: "Closed", 3082: "Open" }
+ // "Open" then names BOTH options. `ambiguousChoiceAliases` treats that as an ERROR (not a warning)
+ // when either side is localized, because the collision is invisible on the page. Emitting it made
+ // `validateAppSpec` fail, and runDownload returns BEFORE writing the spec — so ONE colliding pair
+ // anywhere aborted the download of the ENTIRE app, and --allow-lossy-download does not bypass that
+ // gate. Pre-#564 these columns carried no options[], so the rule returned early and the download
+ // succeeded. Refusing to type just this column restores that, and is the same fail-safe already
+ // used for an unreadable label.
+ const localized = { 1033: 'Closed', 3082: 'Open' };
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true }],
+ attrRows: [attrRow('pp_status', { typeName: 'PicklistType' })],
+ picklist: [picklistRow('pp_status', { name: 'pp_t_pp_status', isGlobal: false, options: [[1, 'Open'], [2, localized]] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ const col = e.columns.find((c) => c.schemaName === 'pp_status');
+ assert.ok(col, 'the column must still be emitted');
+ assert.strictEqual(col.type, undefined, 'an ambiguous option set must not be typed');
+ assert.strictEqual(col.options, undefined, 'and must not carry the invalid options[]');
+ assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_status'], 'it is named in the untyped warning instead');
+ // The whole point: the emitted spec must still validate.
+ const { validateAppSpec: validate } = require('../lib/app-spec.js');
+ const res = validate({ solution: { uniqueName: 'S', publisherPrefix: 'pp' }, app: { name: 'A' }, entities: [e], appShell: { areas: [] } }, { profile: 'plan', reconstructed: true });
+ assert.deepStrictEqual(res.errors, [], res.errors.join(' | '));
+});
+
+test('REVIEW-A duplicate PLAIN labels are still typed (they are a warning, not an error)', async () => {
+ // Only the localized/hidden collision is an error. Two identical plain strings provisioned fine
+ // before this rule existed, so refusing to type them would reject specs that still work.
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true }],
+ attrRows: [attrRow('pp_status', { typeName: 'PicklistType' })],
+ picklist: [picklistRow('pp_status', { name: 'pp_t_pp_status', isGlobal: false, options: [[1, 'Open'], [2, 'Open']] })],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_status').type, 'Choice');
+});
+
+test('REVIEW-B a MultiChoice survives an unusable option label - untyped and NAMED, never dropped', async () => {
+ // Reported by adversarial review. A MultiSelectPicklist is `Virtual`, so before this the ONLY
+ // thing keeping it in columns[] was a successfully PARSED option set. An unusable label made
+ // optionSetFromRow return null, the cast membership was discarded, and the column vanished from
+ // the spec entirely while the warning claimed it was "captured WITHOUT a type".
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_tags', displayName: 'Tags', attributeType: 'Virtual', isCustomAttribute: true }],
+ attrRows: [attrRow('pp_tags', { typeName: 'MultiSelectPicklistType' })],
+ multiSelect: [{ LogicalName: 'pp_tags', OptionSet: { Name: 'pp_t_pp_tags', IsGlobal: false, Options: [{ Value: 1, Label: { LocalizedLabels: [], UserLocalizedLabel: null } }] } }],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ assert.ok(e.columns.find((c) => c.schemaName === 'pp_tags'), 'the MultiChoice column must not vanish');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_tags').type, undefined);
+ assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_tags'], 'and it must be NAMED, so the loss is never silent');
+});
+
+test('REVIEW-B/D a MultiChoice survives a FAILED or EMPTY option-set read, identified by AttributeTypeName', async () => {
+ // Two shapes, same requirement. The cast can fail (503) or answer 200 with an empty value[] — the
+ // second does not even throw, so nothing was recorded and the column disappeared with ZERO
+ // operator signal. `AttributeTypeName` identifies a multi-select INDEPENDENTLY of the cast, so
+ // membership is no longer the only thing standing between a real column and silent deletion.
+ for (const variant of [{ multiSelectStatus: 503 }, { multiSelect: [] }]) {
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_tags', displayName: 'Tags', attributeType: 'Virtual', isCustomAttribute: true }],
+ attrRows: [attrRow('pp_tags', { typeName: 'MultiSelectPicklistType' })],
+ ...variant,
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ const label = JSON.stringify(variant);
+ assert.ok(e.columns.find((c) => c.schemaName === 'pp_tags'), 'MultiChoice vanished for ' + label);
+ assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_tags'], 'not named for ' + label);
+ }
+});
+
+test('REVIEW-C a LOGICAL choice column is not dropped when the option-set read fails', async () => {
+ // The isLogical shadow filter keyed off `optionSet === undefined`, so a genuine logical Choice
+ // whose option read failed was DROPPED rather than left untyped — and the warning then promised a
+ // Text column that a rebuild would never create. Positive type evidence (AttributeTypeName) now
+ // protects it; the shadow, which has none, is still dropped.
+ const sdk = sdkFull({
+ attributes: [
+ { logicalName: 'pp_logchoice', displayName: 'Logical Choice', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'pp_parentidname', displayName: 'Parent Name', attributeType: 'String', isCustomAttribute: true },
+ ],
+ attrRows: [
+ attrRow('pp_logchoice', { isLogical: true, typeName: 'PicklistType' }),
+ attrRow('pp_parentidname', { isLogical: true, typeName: 'StringType' }),
+ ],
+ picklistStatus: 503,
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ const names = e.columns.map((c) => c.schemaName);
+ assert.ok(names.includes('pp_logchoice'), 'a real logical Choice must survive a failed option read');
+ assert.ok(!names.includes('pp_parentidname'), 'the lookup shadow must still be dropped');
+ assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_logchoice']);
+});
+
+test('REVIEW-B a failing SECOND cast does not discard the successful first one', async () => {
+ // readOptionSets threw on the first non-2xx, so a 503 on the multi-select cast threw away an
+ // already-valid Picklist map and every Choice on the table lost its type.
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_status', displayName: 'Status', attributeType: 'Picklist', isCustomAttribute: true }],
+ attrRows: [attrRow('pp_status', { typeName: 'PicklistType' })],
+ picklist: [picklistRow('pp_status', { name: 'pp_t_pp_status', isGlobal: false, options: [[1, 'Open']] })],
+ multiSelectStatus: 503,
+ });
+ const meta = await readEntityWithDescriptions(sdk, 'pp_t');
+ const e = entityFromMetadata(meta, 'pp_t');
+ assert.strictEqual(e.columns.find((c) => c.schemaName === 'pp_status').type, 'Choice', 'the successful cast must survive the other one failing');
+ assert.ok(meta.optionSetReadFailed, 'the partial failure is still recorded');
+});
+
+test('REVIEW-C globalChoices declares only sets an EMITTED column actually references', async () => {
+ // collectGlobalChoices scanned raw metadata, so a set bound only by a SYSTEM attribute (filtered
+ // out of columns[]) or by a table later dropped for having no primary name still produced a
+ // declaration — and the build then creates or reuses every declaration in the target environment.
+ const sdk = sdkFull({
+ attributes: [
+ { logicalName: 'pp_mine', displayName: 'Mine', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'sys_theirs', displayName: 'Theirs', attributeType: 'Picklist', isCustomAttribute: false },
+ ],
+ attrRows: [attrRow('pp_mine', { typeName: 'PicklistType' }), attrRow('sys_theirs', { typeName: 'PicklistType' })],
+ picklist: [
+ picklistRow('pp_mine', { name: 'bound_set', isGlobal: true, options: [[1, 'A']] }),
+ picklistRow('sys_theirs', { name: 'orphan_set', isGlobal: true, options: [[1, 'B']] }),
+ ],
+ });
+ const meta = await readEntityWithDescriptions(sdk, 'pp_t');
+ const e = entityFromMetadata(meta, 'pp_t');
+ const candidates = collectGlobalChoices(meta, new Map());
+ const decls = finalizeGlobalChoices([e], candidates);
+ assert.deepStrictEqual(decls.map((g) => g.name), ['bound_set'], 'the orphan set must not be declared');
+});
+
+test('REVIEW-D a global-choice reference is canonicalized to the declaration casing', async () => {
+ // Declarations dedupe case-insensitively but each column kept its own raw casing, and
+ // entity-provision looks up `globalChoiceIds[c.globalChoice]` CASE-SENSITIVELY — so a second
+ // casing left that column unbound and it fell back to an empty inline option list.
+ const e = {
+ schemaName: 'pp_t',
+ columns: [
+ { schemaName: 'a', type: 'Choice', globalChoice: 'Shared_Set' },
+ { schemaName: 'b', type: 'Choice', globalChoice: 'shared_set' },
+ ],
+ };
+ const candidates = new Map([['shared_set', { name: 'Shared_Set', options: ['A'] }]]);
+ const decls = finalizeGlobalChoices([e], candidates);
+ assert.deepStrictEqual(decls.map((g) => g.name), ['Shared_Set']);
+ assert.deepStrictEqual(e.columns.map((c) => c.globalChoice), ['Shared_Set', 'Shared_Set'], 'every reference must match the declaration exactly');
+});
+test('REVIEW-C runDownload emits ONLY referenced globalChoices (drives the real wiring, not the helper)', async () => {
+ // Deliberately driven through runDownload. An earlier version of this test called
+ // finalizeGlobalChoices directly, and a mutation that reverted the ACCESSOR to
+ // `[...globalChoiceDecls.values()]` survived it — the helper was right while the wiring was not.
+ const APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000c1';
+ const APP_UNIQUE = 'test_gcwiring';
+ const SM_ID = '5111e0f2-0000-4000-8000-0000000000c2';
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-gc-'));
+ try {
+ const sdk = {
+ fetchArtifact: async () => ({ name: 'GC App', description: '', siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'Entity', entity: 'contoso_item' }] }] }] } }),
+ queryRecords: async (logical, opts) => {
+ const filter = (opts && opts.filter) || '';
+ if (logical === 'appmodule') {
+ const m = filter.match(/uniquename eq '([^']+)'/);
+ if (m) return m[1] === APP_UNIQUE ? [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-0000000000c3' }] : [];
+ return [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-0000000000c3', uniquename: APP_UNIQUE }];
+ }
+ if (logical === 'appmodulecomponent') return [{ objectid: SM_ID, componenttype: 62 }];
+ if (logical === 'sitemap') return [{ sitemapxml: '<SiteMap><Area><Group><SubArea Entity="contoso_item"/></Group></Area></SiteMap>' }];
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({
+ schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name',
+ attributes: [
+ { logicalName: 'contoso_mine', displayName: 'Mine', attributeType: 'Picklist', isCustomAttribute: true },
+ // SYSTEM attribute: filtered out of columns[], so the set it binds must NOT be declared.
+ { logicalName: 'sys_theirs', displayName: 'Theirs', attributeType: 'Picklist', isCustomAttribute: false },
+ ],
+ }),
+ dataverse: {
+ get: async (url) => {
+ if (/MultiSelectPicklistAttributeMetadata/.test(url)) return { status: 200, headers: {}, body: { value: [] } };
+ if (/PicklistAttributeMetadata/.test(url)) {
+ return { status: 200, headers: {}, body: { value: [
+ picklistRow('contoso_mine', { name: 'bound_set', isGlobal: true, options: [[1, 'A']] }),
+ picklistRow('sys_theirs', { name: 'orphan_set', isGlobal: true, options: [[1, 'B']] }),
+ ] } };
+ }
+ if (/\/Attributes\?/.test(url)) {
+ return { status: 200, headers: {}, body: { value: [
+ { LogicalName: 'contoso_mine', AttributeTypeName: { Value: 'PicklistType' } },
+ { LogicalName: 'sys_theirs', AttributeTypeName: { Value: 'PicklistType' } },
+ ] } };
+ }
+ if (/GlobalOptionSetDefinitions/.test(url)) return { status: 200, headers: {}, body: { value: [] } };
+ return { status: 200, headers: {}, body: {} };
+ },
+ },
+ };
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }), download: async () => true };
+ const res = await runDownload({ sdk, genpageCli, outDir: out, appId: APP_ID, appUnique: APP_UNIQUE });
+ assert.ok(res.ok, JSON.stringify(res));
+ assert.deepStrictEqual((res.spec.globalChoices || []).map((g) => g.name), ['bound_set'],
+ 'a set bound only by a filtered SYSTEM attribute must not be declared — the build writes every declaration into the target org');
+ const col = res.spec.entities[0].columns.find((c) => c.schemaName === 'contoso_mine');
+ assert.strictEqual(col.globalChoice, 'bound_set');
+ // And the emitted spec must still validate.
+ assert.deepStrictEqual(validateAppSpec(res.spec, { profile: 'plan' }).errors, []);
+ } finally {
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+});
+
+test('REVIEW-B cast membership still keeps a column when the ATTRIBUTE read also failed', async () => {
+ // The combination neither guard covers alone: no AttributeTypeName (attribute read 403) AND an
+ // unparseable option label. Cast MEMBERSHIP is then the only evidence the column exists, so the
+ // entry must be recorded even when its options cannot be parsed.
+ const sdk = sdkFull({
+ attributes: [{ logicalName: 'pp_tags', displayName: 'Tags', attributeType: 'Virtual', isCustomAttribute: true }],
+ attrStatus: 403,
+ multiSelect: [{ LogicalName: 'pp_tags', OptionSet: { Name: 'pp_t_pp_tags', IsGlobal: false, Options: [{ Value: 1, Label: { LocalizedLabels: [], UserLocalizedLabel: null } }] } }],
+ });
+ const e = entityFromMetadata(await readEntityWithDescriptions(sdk, 'pp_t'), 'pp_t');
+ assert.ok(e.columns.find((c) => c.schemaName === 'pp_tags'), 'cast membership must keep the column when nothing else can');
+ assert.deepStrictEqual(untypedColumnNames([e]), ['pp_t.pp_tags']);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.js
index 66eda47db..e4cfaa515 100644
--- a/plugins/model-apps/scripts/tests/entity-provision.test.js
+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js
@@ -549,6 +549,173 @@ test('buildSeedGroup omits matchOn (no dedup) when the key value is empty in a r
assert.ok(!('primaryAttribute' in group));
});
+// --- #544: self-referencing $parent (a hierarchy on one table) ---------------------------------
+// seedRecordGraph resolves EVERY bind in a group before creating ANY of that group's rows, and only
+// publishes the group's ids afterwards. Topological ordering BETWEEN entities therefore does not
+// help WITHIN one, so a `$parent` pointing at the row's own entity could never resolve — the whole
+// sample-data phase halted, several phases into a build that had already written data. The spec
+// cannot work around it either: the plugin, not the author, decides the grouping.
+const hierarchySpec = () => ({
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ entities: [{ schemaName: 'new_org', displayName: 'Org', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],
+ relationships: [
+ { type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_ParentOrgId', displayName: 'Parent Org' } },
+ ],
+ sampleData: {
+ new_org: [
+ { new_name: 'Root' },
+ { new_name: 'Child', $parent: { entity: 'new_org', match: { new_name: 'Root' } } },
+ { new_name: 'Grandchild', $parent: { entity: 'new_org', match: { new_name: 'Child' } } },
+ ],
+ },
+});
+
+// Capture every seedRecordGraph call so the WAVES are observable, and return ids the way the real
+// bundle does: one id per record of the group it was handed, in order.
+function recordingSdk() {
+ const calls = [];
+ let n = 0;
+ return {
+ calls,
+ seedRecordGraph: async (groups, opts) => {
+ const g = groups[0];
+ calls.push({ names: g.records.map((r) => r.body.new_name), binds: g.records.map((r) => r.binds), createdIds: JSON.parse(JSON.stringify(opts.createdIds || {})) });
+ return { createdIds: { [g.entityLogical]: g.records.map(() => `id-${n++}`) } };
+ },
+ };
+}
+
+async function runHierarchy(spec) {
+ const runner = makeRunner({ emit: () => {}, total: 1 });
+ const sdk = recordingSdk();
+ const dataModel = { entities: { new_org: { logicalName: 'new_org', entitySetName: 'new_orgs' } }, statusReasonValues: {} };
+ const res = await provisionSampleData({ sdk, provision: {}, runner, spec, dataModel });
+ return { sdk, res };
+}
+
+test('#544 a self-referencing $parent seeds in waves instead of failing the whole phase', async () => {
+ const { sdk } = await runHierarchy(hierarchySpec());
+ assert.deepStrictEqual(sdk.calls.map((c) => c.names), [['Root'], ['Child'], ['Grandchild']],
+ 'one wave per depth: a row is seeded only after the row it points at');
+});
+
+test('#544 each wave receives its parents ids at their ORIGINAL record index', async () => {
+ const { sdk, res } = await runHierarchy(hierarchySpec());
+ // The bind carries parentIndex = the parent's index in the entity's FULL sample list, and the SDK
+ // looks it up as createdIds[entity][parentIndex]. A wave-local array would misresolve every bind.
+ assert.deepStrictEqual(sdk.calls[1].binds[0], [{ navProperty: 'new_ParentOrgId', parentEntity: 'new_org', parentIndex: 0 }]);
+ assert.strictEqual(sdk.calls[1].createdIds.new_org[0], 'id-0', "wave 2 sees Root's id at index 0");
+ assert.strictEqual(sdk.calls[2].createdIds.new_org[1], 'id-1', "wave 3 sees Child's id at index 1");
+ assert.deepStrictEqual(res.records.new_org, ['id-0', 'id-1', 'id-2'], 'the entity reports one id per ORIGINAL row, in order');
+});
+
+test('#544 a spec with no self-reference still seeds in exactly one call (no behaviour change)', async () => {
+ const spec = hierarchySpec();
+ delete spec.sampleData.new_org[1].$parent;
+ delete spec.sampleData.new_org[2].$parent;
+ const { sdk } = await runHierarchy(spec);
+ assert.strictEqual(sdk.calls.length, 1, 'unchanged specs must not be split into waves');
+ assert.deepStrictEqual(sdk.calls[0].names, ['Root', 'Child', 'Grandchild']);
+ assert.strictEqual(sdk.calls[0].createdIds.new_org, undefined, 'and must not gain a self-entity key in options');
+});
+
+// Waves are by DEPTH, not by row order: independent rows at the same depth go in one call, and a row
+// declared BEFORE its parent still lands after it. Order in the array must not matter.
+test('#544 rows at the same depth share a wave, and a parent declared LATER still goes first', async () => {
+ const spec = hierarchySpec();
+ spec.sampleData.new_org = [
+ { new_name: 'Leaf', $parent: { entity: 'new_org', match: { new_name: 'Mid' } } }, // depth 2, declared first
+ { new_name: 'Mid', $parent: { entity: 'new_org', match: { new_name: 'Root' } } }, // depth 1
+ { new_name: 'Root' }, // depth 0, declared last
+ { new_name: 'OtherRoot' }, // depth 0
+ { new_name: 'OtherMid', $parent: { entity: 'new_org', match: { new_name: 'OtherRoot' } } }, // depth 1
+ ];
+ const { sdk, res } = await runHierarchy(spec);
+ assert.deepStrictEqual(sdk.calls.map((c) => c.names), [
+ ['Root', 'OtherRoot'],
+ ['Mid', 'OtherMid'],
+ ['Leaf'],
+ ], 'one call per depth, independent rows batched together');
+ // Ids still come back indexed by the ORIGINAL declaration order, which is what every bind means.
+ assert.strictEqual(res.records.new_org.length, 5);
+ assert.ok(res.records.new_org.every((id) => typeof id === 'string'), JSON.stringify(res.records.new_org));
+});
+
+// `$parents` (the array form used by junction rows) must be treated identically — it is the same
+// bind list, so a self-reference through it has to drive the waves too.
+test('#544 a self-reference expressed through $parents drives the waves as well', async () => {
+ const spec = hierarchySpec();
+ spec.sampleData.new_org = [
+ { new_name: 'Child', $parents: [{ entity: 'new_org', match: { new_name: 'Root' } }] },
+ { new_name: 'Root' },
+ ];
+ const { sdk } = await runHierarchy(spec);
+ assert.deepStrictEqual(sdk.calls.map((c) => c.names), [['Root'], ['Child']]);
+});
+
+// A CROSS-entity parent must not be mistaken for a self-reference: it is already handled by the
+// topological ordering BETWEEN entities, and splitting on it would add calls for no reason.
+test('#544 a cross-entity $parent does not trigger wave splitting', async () => {
+ const spec = hierarchySpec();
+ spec.entities.push({ schemaName: 'new_owner', displayName: 'Owner', primaryAttribute: { schemaName: 'new_name' }, columns: [] });
+ spec.relationships.push({ type: 'OneToMany', referenced: 'new_owner', referencing: 'new_org', lookup: { schemaName: 'new_OwnerId', displayName: 'Owner' } });
+ spec.sampleData.new_owner = [{ new_name: 'Acme' }];
+ spec.sampleData.new_org = [
+ { new_name: 'A', $parent: { entity: 'new_owner', match: { new_name: 'Acme' } } },
+ { new_name: 'B', $parent: { entity: 'new_owner', match: { new_name: 'Acme' } } },
+ ];
+ const { sdk } = await runHierarchy(spec);
+ const orgCalls = sdk.calls.filter((c) => c.names.includes('A') || c.names.includes('B'));
+ assert.strictEqual(orgCalls.length, 1, 'both org rows seed in one call');
+});
+
+test('#544 a self-reference CYCLE fails with a message naming the rows, not a hang', async () => { const spec = hierarchySpec();
+ spec.sampleData.new_org[0].$parent = { entity: 'new_org', match: { new_name: 'Grandchild' } };
+ await assert.rejects(runHierarchy(spec), (err) => {
+ assert.match(err.message, /cycle/i);
+ assert.match(err.message, /new_org/);
+ assert.match(err.message, /Root|Grandchild/, `the message must name the rows involved: ${err.message}`);
+ return true;
+ });
+});
+
+test('#544 a row that is its own parent is reported as a cycle', async () => {
+ const spec = hierarchySpec();
+ spec.sampleData.new_org = [{ new_name: 'Loop', $parent: { entity: 'new_org', match: { new_name: 'Loop' } } }];
+ await assert.rejects(runHierarchy(spec), /cycle/i);
+});
+
+// The ambiguity this fix makes REACHABLE: `$parent` resolves through relationshipFor, which returns
+// the FIRST OneToMany for the pair. A hierarchy table commonly has two self-lookups, and silently
+// binding the wrong one asserts something false about the data.
+test('#544 two relationships for the same pair are rejected unless $parent names the lookup', () => {
+ const spec = hierarchySpec();
+ spec.relationships.push({ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_GroupAncestorId', displayName: 'Group Ancestor' } });
+ assert.throws(
+ () => buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_org, statusReasonValues: {} }),
+ /ambiguous|more than one/i
+ );
+});
+
+test('#544 $parent.lookup selects which relationship to bind', () => {
+ const spec = hierarchySpec();
+ spec.relationships.push({ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_GroupAncestorId', displayName: 'Group Ancestor' } });
+ spec.sampleData.new_org[1].$parent.lookup = 'new_GroupAncestorId';
+ spec.sampleData.new_org[2].$parent.lookup = 'new_ParentOrgId';
+ const group = buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_org, statusReasonValues: {} });
+ assert.strictEqual(group.records[1].binds[0].navProperty, 'new_GroupAncestorId');
+ assert.strictEqual(group.records[2].binds[0].navProperty, 'new_ParentOrgId');
+});
+
+test('#544 an unknown $parent.lookup names the valid ones', () => {
+ const spec = hierarchySpec();
+ spec.sampleData.new_org[1].$parent.lookup = 'new_NopeId';
+ assert.throws(
+ () => buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.new_org, statusReasonValues: {} }),
+ /new_NopeId[\s\S]*new_ParentOrgId/
+ );
+});
+
// --- provisionSampleData: F9 keyless-seeding warning ------------------------------------------
function runSample(spec) {
// The F9 warning goes to stderr (non-fatal), so capture stderr for the duration of the run.
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
index 2c825ca80..934438a45 100644
--- a/plugins/model-apps/scripts/tests/feature-flags.test.js
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -24,14 +24,24 @@ const {
// --- Default OFF (fail-closed) ---------------------------------------------
-test('connectors flag is OFF by default (no env override)', () => {
- // Empty env → falls through to the committed feature-flags.json, which ships false.
- assert.equal(isConnectorsEnabled({ env: {} }), false);
+test('connectors is GA and ships ON, with the rollback switch still working', () => {
+ // connectors was flipped to true rather than removed, so the gate survives one release as a
+ // rollback path. Pin BOTH halves: shipping ON (a regression to false silently disables a GA
+ // feature for every user) and still gate-able (if the switch stopped working there would be no
+ // way back short of a revert, which is the whole reason the flag was kept).
+ const json = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
+ );
+ assert.equal(json.connectors, true, 'feature-flags.json must ship connectors: true');
+ assert.equal(isConnectorsEnabled({ env: {} }), true);
+ assert.equal(FLAGS.connectors.status, 'ga');
+ // The rollback path: an env override must still be able to turn it off.
+ assert.equal(isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '0' } }), false);
});
test('custom-api flag is OFF by default (no env override)', () => {
- // Same fail-closed contract as connectors: empty env falls through to the committed
- // feature-flags.json, which ships custom-api:false until the runtime stack is GA in PROD.
+ // Same fail-closed contract every gated feature relies on: an empty env falls through to the
+ // committed feature-flags.json, which ships custom-api:false until the runtime stack is GA in PROD.
assert.equal(isCustomApiEnabled({ env: {} }), false);
});
@@ -47,7 +57,7 @@ test('unknown flags are OFF (fail-closed)', () => {
test('missing/invalid flags file is treated as all-OFF', () => {
assert.equal(
- isEnabled('connectors', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }),
+ isEnabled('custom-api', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }),
false
);
});
@@ -56,33 +66,33 @@ test('missing/invalid flags file is treated as all-OFF', () => {
test('env var enables a flag that is false in config', () => {
assert.equal(
- isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '1' }, flags: { connectors: false } }),
+ isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '1' }, flags: { 'custom-api': false } }),
true
);
});
test('env var OFF overrides config true', () => {
assert.equal(
- isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '0' }, flags: { connectors: true } }),
+ isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '0' }, flags: { 'custom-api': true } }),
false
);
});
test('unrecognized env value defers to config', () => {
assert.equal(
- isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: 'maybe' }, flags: { connectors: true } }),
+ isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: 'maybe' }, flags: { 'custom-api': true } }),
true
);
});
test('config true enables when env is unset', () => {
- assert.equal(isEnabled('connectors', { env: {}, flags: { connectors: true } }), true);
+ assert.equal(isEnabled('custom-api', { env: {}, flags: { 'custom-api': true } }), true);
});
// --- Helpers ----------------------------------------------------------------
test('envVarName maps flag names to GENPAGE_ENABLE_<FLAG>', () => {
- assert.equal(envVarName('connectors'), 'GENPAGE_ENABLE_CONNECTORS');
+ assert.equal(envVarName('custom-api'), 'GENPAGE_ENABLE_CUSTOM_API');
assert.equal(envVarName('multi-word flag'), 'GENPAGE_ENABLE_MULTI_WORD_FLAG');
});
@@ -92,12 +102,6 @@ test('parseBool recognizes common truthy/falsey tokens, defers otherwise', () =>
for (const v of [undefined, null, '', ' ', 'maybe']) assert.equal(parseBool(v), null, `defer: ${String(v)}`);
});
-test('connectorsDisabledMessage explains how to enable', () => {
- const m = connectorsDisabledMessage();
- assert.match(m, /GENPAGE_ENABLE_CONNECTORS/);
- assert.match(m, /feature-flags\.json/);
-});
-
test('customApiDisabledMessage explains how to enable', () => {
const m = customApiDisabledMessage();
assert.match(m, /GENPAGE_ENABLE_CUSTOM_API/);
@@ -106,11 +110,18 @@ test('customApiDisabledMessage explains how to enable', () => {
// --- Committed config actually ships OFF ------------------------------------
-test('committed feature-flags.json ships connectors: false', () => {
- const json = JSON.parse(
- fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
- );
- assert.equal(json.connectors, false);
+test('the retired connectors flag is gone from every surface', () => {
+ // Intentionally inverted from its original form: connectors is GA but the gate was KEPT for one
+ // release as a rollback switch, so the flag, its helpers and its catalog entry must all still
+ // exist. When the follow-up change removes them, flip these assertions back.
+ assert.ok(KNOWN_FLAGS.includes('connectors'), 'connectors stays in the catalog until the gate is removed');
+ const lib = require(libPath);
+ for (const present of ['isConnectorsEnabled', 'exitIfConnectorsDisabled', 'connectorsDisabledMessage']) {
+ assert.equal(typeof lib[present], 'function', `${present} must still be exported while the gate exists`);
+ }
+ // And it must NOT be an unknown key — a leftover value the validator rejects would mean the
+ // committed file and the catalog had drifted apart.
+ assert.deepEqual(validateFlags({ connectors: true }), []);
});
test('committed feature-flags.json ships custom-api: false', () => {
@@ -130,18 +141,18 @@ test('committed feature-flags.json ships custom-telemetry: false', () => {
// --- CLI probe (deterministic gate for the skill markdown) ------------------
test('CLI prints "disabled" and exits 1 when OFF', () => {
- const res = spawnSync(process.execPath, [libPath, 'connectors'], {
+ const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '' },
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '' },
});
assert.equal(res.status, 1);
assert.match(res.stdout, /disabled/);
});
test('CLI prints "enabled" and exits 0 when env override ON', () => {
- const res = spawnSync(process.execPath, [libPath, 'connectors'], {
+ const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '1' },
});
assert.equal(res.status, 0);
assert.match(res.stdout, /enabled/);
@@ -153,13 +164,13 @@ test('CLI without a flag name exits 2 with usage', () => {
assert.match(res.stderr, /Usage:/);
});
-// --- exitIfConnectorsDisabled (DRY gate helper) -----------------------------
+// --- exitIfConnectorsDisabled / exitIfCustomApiDisabled (DRY gate helpers) --
test('exitIfConnectorsDisabled exits 3 and writes the message when OFF', () => {
let exitCode = null;
let written = '';
exitIfConnectorsDisabled({
- env: {},
+ env: { GENPAGE_ENABLE_CONNECTORS: '0' },
exit: (c) => { exitCode = c; },
write: (s) => { written += s; },
});
@@ -167,14 +178,20 @@ test('exitIfConnectorsDisabled exits 3 and writes the message when OFF', () => {
assert.match(written, /disabled/i);
});
-test('exitIfConnectorsDisabled is a no-op when ON', () => {
+test('exitIfConnectorsDisabled is a no-op in the shipped (ON) configuration', () => {
let exitCalled = false;
exitIfConnectorsDisabled({
- env: { GENPAGE_ENABLE_CONNECTORS: '1' },
+ env: {},
exit: () => { exitCalled = true; },
write: () => {},
});
- assert.equal(exitCalled, false);
+ assert.equal(exitCalled, false, 'connectors ships ON, so the gate must not fire by default');
+});
+
+test('connectorsDisabledMessage explains that it was explicitly turned off', () => {
+ const m = connectorsDisabledMessage();
+ assert.match(m, /GENPAGE_ENABLE_CONNECTORS/);
+ assert.match(m, /feature-flags\.json/);
});
test('exitIfCustomApiDisabled exits 3 and writes the message when OFF', () => {
@@ -201,10 +218,6 @@ test('exitIfCustomApiDisabled is a no-op when ON', () => {
// --- known-flag registry + describe() + validation --------------------------
-test('KNOWN_FLAGS includes connectors', () => {
- assert.ok(KNOWN_FLAGS.includes('connectors'));
-});
-
test('KNOWN_FLAGS includes custom-api', () => {
assert.ok(KNOWN_FLAGS.includes('custom-api'));
});
@@ -214,37 +227,30 @@ test('KNOWN_FLAGS includes custom-telemetry', () => {
});
test('describe reports effective state and source per known flag', () => {
- const envOn = describe({ env: { GENPAGE_ENABLE_CONNECTORS: '1' }, flags: { connectors: false } });
- const c1 = envOn.find((f) => f.flag === 'connectors');
+ const envOn = describe({ env: { GENPAGE_ENABLE_CUSTOM_API: '1' }, flags: { 'custom-api': false } });
+ const c1 = envOn.find((f) => f.flag === 'custom-api');
assert.equal(c1.enabled, true);
assert.equal(c1.source, 'env');
- const fileOn = describe({ env: {}, flags: { connectors: true } });
- const c2 = fileOn.find((f) => f.flag === 'connectors');
+ const fileOn = describe({ env: {}, flags: { 'custom-api': true } });
+ const c2 = fileOn.find((f) => f.flag === 'custom-api');
assert.equal(c2.enabled, true);
assert.equal(c2.source, 'file');
const dflt = describe({ env: {}, flags: {} });
- const c3 = dflt.find((f) => f.flag === 'connectors');
+ const c3 = dflt.find((f) => f.flag === 'custom-api');
assert.equal(c3.enabled, false);
assert.equal(c3.source, 'default');
});
test('validateFlags warns on unknown keys and non-boolean values, ignores _comment', () => {
- assert.deepEqual(validateFlags({ connectors: false, _comment: 'x' }), []);
- assert.match(validateFlags({ conectors: true })[0], /unknown flag/i);
- assert.match(validateFlags({ connectors: 'yes' })[0], /boolean/i);
+ assert.deepEqual(validateFlags({ 'custom-api': false, _comment: 'x' }), []);
+ assert.match(validateFlags({ 'custom-apy': true })[0], /unknown flag/i);
+ assert.match(validateFlags({ 'custom-api': 'yes' })[0], /boolean/i);
});
// --- flag catalog: status tracking for experimental / in-progress features --
-test('FLAGS catalog documents connectors with a status and summary', () => {
- assert.ok(FLAGS.connectors, 'connectors flag should be in the catalog');
- assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS.connectors.status));
- assert.match(FLAGS.connectors.summary, /connector/i);
- assert.ok(FLAGS.connectors.dependencies, 'should document what it depends on');
-});
-
test('FLAGS catalog documents custom-api with a status and summary', () => {
assert.ok(FLAGS['custom-api'], 'custom-api flag should be in the catalog');
assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS['custom-api'].status));
@@ -259,6 +265,6 @@ test('KNOWN_FLAGS is derived from the FLAGS catalog', () => {
test('describe includes the status for each known flag', () => {
const d = describe({ env: {}, flags: {} });
- const c = d.find((f) => f.flag === 'connectors');
- assert.equal(c.status, FLAGS.connectors.status);
+ const c = d.find((f) => f.flag === 'custom-api');
+ assert.equal(c.status, FLAGS['custom-api'].status);
});
diff --git a/plugins/model-apps/scripts/tests/genpage-cli.test.js b/plugins/model-apps/scripts/tests/genpage-cli.test.js
index eff331739..69ba9f087 100644
--- a/plugins/model-apps/scripts/tests/genpage-cli.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-cli.test.js
@@ -104,21 +104,112 @@ test('upload builds pac args WITHOUT --add-to-sitemap and returns the pageId', a
// The upload call is NOT calls[0] any more (before-snapshot is first); find by verb.
const args = calls.find((a) => a[2] === 'upload');
assert.ok(!args.includes('--add-to-sitemap'), 'never adds to sitemap (the SDK owns it)');
- assert.ok(args.includes('--prompt') && args.includes('--agent-message'), 'always supplies pac-required prompt + agent-message');
+ assert.ok(args.includes('--prompt-file') && args.includes('--agent-message-file'), 'supplies pac-required prompt + agent-message BY FILE (multi-line safe)');
+ assert.ok(!args.includes('--prompt') && !args.includes('--agent-message'), 'never inline --prompt/--agent-message (they would be lossily newline-collapsed)');
assert.ok(args.includes('--data-sources') && args.includes('new_o'));
assert.ok(args.includes('--environment') && args.includes('https://x'));
});
-test('upload defaults prompt + agent-message when absent (pac requires both)', async () => {
+test('upload defaults prompt + agent-message when absent (pac requires both), delivered by file', async () => {
+ const fs = require('node:fs');
const calls = [];
+ let promptText = null;
+ let agentText = null;
const run = async (args) => {
calls.push(args);
if (args[2] === 'list') return { status: 0, stdout: LIST_EMPTY, stderr: '' };
+ // Read the temp files back while upload() still owns them (before its finally cleans up).
+ const pi = args.indexOf('--prompt-file');
+ const ai = args.indexOf('--agent-message-file');
+ promptText = fs.readFileSync(args[pi + 1], 'utf8');
+ agentText = fs.readFileSync(args[ai + 1], 'utf8');
return { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' };
};
await makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', codeFile: 'o.tsx', name: 'X' });
const uploadCall = calls.find((a) => a[2] === 'upload');
- assert.ok(uploadCall.includes('--prompt') && uploadCall.includes('--agent-message'));
+ assert.ok(uploadCall.includes('--prompt-file') && uploadCall.includes('--agent-message-file'));
+ assert.ok(!uploadCall.includes('--prompt') && !uploadCall.includes('--agent-message'), 'defaults go by file too, never inline');
+ assert.strictEqual(promptText, 'Generative page X', 'historical default prompt preserved, just delivered by file');
+ assert.strictEqual(agentText, 'Authored by app-builder', 'historical default agent-message preserved, just delivered by file');
+});
+
+test('upload delivers the prompt via --prompt-file and a multi-line transcript round-trips verbatim (#565)', async () => {
+ const fs = require('node:fs');
+ // A real downloaded page prompt: a multi-line conversation transcript carrying BOTH \r\n and \n
+ // breaks plus non-ASCII — exactly the shape the old inline --prompt path collapsed to spaces on an
+ // edit-rebuild (`pac model genpage upload --help` documents --prompt-file for precisely this).
+ const multiline = 'Conversation with 2 prompts:\r\n1. Show an overview \u2014 caf\u00e9 \u2615\n2. Add a bar chart';
+ let promptFilePath = null;
+ let roundTripped = null;
+ const run = async (args) => {
+ if (args[2] === 'list') return { status: 0, stdout: LIST_EMPTY, stderr: '' };
+ assert.ok(!args.includes('--prompt'), 'prompt is never passed inline (that path is lossy for newlines)');
+ const i = args.indexOf('--prompt-file');
+ assert.ok(i >= 0, 'prompt is delivered via --prompt-file');
+ promptFilePath = args[i + 1];
+ // Read the file back while upload() still owns it (before the finally cleans it up).
+ roundTripped = fs.readFileSync(promptFilePath, 'utf8');
+ return { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' };
+ };
+ const r = await makeGenpageCli('https://x', { run, sleep: async () => {} })
+ .upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview', prompt: multiline });
+ assert.strictEqual(r.pageId, GUID);
+ assert.strictEqual(roundTripped, multiline, 'every \\r\\n and \\n line break and the non-ASCII survive byte-for-byte');
+ assert.ok(promptFilePath && !fs.existsSync(promptFilePath), 'the prompt temp file is cleaned up on success');
+});
+
+test('upload threads --compiled-code-file only when the caller supplies it (else pac auto-transpiles) (#565)', async () => {
+ const seen = [];
+ const run = async (args) => {
+ if (args[2] === 'list') return { status: 0, stdout: LIST_EMPTY, stderr: '' };
+ seen.push(args);
+ return { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' };
+ };
+ const cli = makeGenpageCli('https://x', { run, sleep: async () => {} });
+ // Absent → flag omitted so pac auto-transpiles the TypeScript (the live-verified default path).
+ await cli.upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' });
+ assert.ok(!seen[0].includes('--compiled-code-file'), 'no --compiled-code-file when the caller omits it');
+ // Supplied → flag present with the exact caller path.
+ await cli.upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', compiledCodeFile: 'o.js', name: 'Overview' });
+ const ci = seen[1].indexOf('--compiled-code-file');
+ assert.ok(ci >= 0 && seen[1][ci + 1] === 'o.js', 'passes --compiled-code-file <path> when supplied');
+});
+
+test('upload cleans up its temp files even when it throws after exhausting retries (#565)', async () => {
+ const fs = require('node:fs');
+ let promptPath = null;
+ let agentPath = null;
+ const run = async (args) => {
+ const pi = args.indexOf('--prompt-file');
+ const ai = args.indexOf('--agent-message-file');
+ if (pi >= 0) promptPath = args[pi + 1];
+ if (ai >= 0) agentPath = args[ai + 1];
+ // UPDATE path (caller pageId) so there is no CREATE reconcile — every attempt just fails and the
+ // wrapper throws after `attempts`. The finally must still remove the temp dir.
+ return { status: 1, stdout: '', stderr: 'boom' };
+ };
+ await assert.rejects(
+ makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
+ /pac genpage upload failed/i
+ );
+ assert.ok(promptPath && !fs.existsSync(promptPath), 'prompt temp file removed on the retry-exhaustion throw');
+ assert.ok(agentPath && !fs.existsSync(agentPath), 'agent-message temp file removed on the retry-exhaustion throw');
+});
+
+test('upload cleans up its temp files even when it throws mid-loop (I7 identity mismatch) (#565)', async () => {
+ const fs = require('node:fs');
+ let promptPath = null;
+ const run = async (args) => {
+ const pi = args.indexOf('--prompt-file');
+ if (pi >= 0) promptPath = args[pi + 1];
+ // Return a DIFFERENT id than the requested pageId → the I7 guard throws from inside the loop.
+ return { status: 0, stdout: `Page ID: ${GP_A}`, stderr: '' };
+ };
+ await assert.rejects(
+ makeGenpageCli('https://x', { run }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
+ /unexpected Page ID|refusing to persist/i
+ );
+ assert.ok(promptPath && !fs.existsSync(promptPath), 'temp file removed even on a mid-loop throw');
});
test('upload with a pageId updates in place (adds --page-id)', async () => {
diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
new file mode 100644
index 000000000..5a74cbaaf
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
@@ -0,0 +1,294 @@
+// plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
+// The `Connectors:` dispatch line is a CONTRACT between two markdown files: the /genpage
+// orchestrator produces it (skills/genpage/SKILL.md Phase 4.5 + the Phase 5c dispatch templates)
+// and genpage-page-builder consumes it to decide whether to emit connector code.
+//
+// Nothing executes that contract, so a rename on one side is invisible until a real run produces a
+// connector-backed page with no connector code. That happened when the `connectors` feature flag
+// was retired: Phase 4.5 and the page-builder both moved to `none` / `<n> binding(s)`, but the
+// Phase 5c dispatch templates were left emitting the retired `enabled` / `disabled` — a token that
+// matches NEITHER the consumer's positive trigger nor its negative one, so the page would have
+// shipped without its binding.
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+
+function mdFiles() {
+ const out = [];
+ for (const dir of [path.join(PLUGIN, 'skills'), path.join(PLUGIN, 'agents'), path.join(PLUGIN, 'references')]) {
+ const walk = (d) => {
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.endsWith('.md')) out.push(p);
+ }
+ };
+ if (fs.existsSync(dir)) walk(dir);
+ }
+ return out;
+}
+
+const rel = (p) => p.replace(PLUGIN + path.sep, '').replace(/\\/g, '/');
+
+test('no Connectors dispatch line uses the retired enabled/disabled vocabulary', () => {
+ const offenders = [];
+ for (const f of mdFiles()) {
+ const lines = fs.readFileSync(f, 'utf8').split(/\r?\n/);
+ lines.forEach((line, i) => {
+ // Only DECLARATION lines: a dispatch template row (`> - Connectors: …`) or an input-spec
+ // bullet (`- **Connectors** — …` / `- **Connectors: …**`). Prose that merely mentions the
+ // field while explaining it — "`Connectors: none` and `Telemetry: disabled` are constants
+ // here" — is legitimate and must not trip this, which an unanchored match cannot tell apart.
+ if (!/^\s*>?\s*-\s*(?:\*\*)?Connectors\b/.test(line)) return;
+ if (/\b(enabled|disabled)\b/.test(line)) offenders.push(`${rel(f)}:${i + 1} ${line.trim()}`);
+ });
+ }
+ assert.deepEqual(offenders, [], `Connectors dispatch must use none|<n> binding(s):\n${offenders.join('\n')}`);
+});
+
+test('the orchestrator emits the exact token the page-builder triggers on', () => {
+ const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');
+
+ // Consumer side: the page-builder reads connectors.md and emits connector code only on the
+ // positive token, and treats the negative token (or an absent line) as no connectors.
+ assert.match(builder, /Connectors: <n> binding\(s\)/, 'page-builder must state its positive trigger');
+ assert.match(builder, /Connectors: none/, 'page-builder must state its negative trigger');
+
+ // Producer side: both Phase 5c dispatch templates (dataverse + mock) must carry the same
+ // vocabulary, or a connector-backed page is dispatched with a token the consumer ignores.
+ const templates = skill.match(/^> - Connectors: .*$/gm) || [];
+ assert.ok(templates.length >= 2, `expected both dispatch templates to carry a Connectors line, found ${templates.length}`);
+ for (const t of templates) {
+ assert.match(t, /none\|<n> binding\(s\)/, `dispatch template must use the consumer's vocabulary: ${t}`);
+ }
+});
+
+test('the connectors rollback gate is documented where the scripts enforce it', () => {
+ // connectors is GA and ships ON, but the gate was kept for one release as a rollback switch.
+ // The scripts fail closed with exit 3 when it is off, so the prose has to tell an agent that
+ // path exists — otherwise a run that hits exit 3 looks like a crash rather than a switch.
+ //
+ // This assertion is the inverse of the one that stood here while the flag was being retired.
+ // When the follow-up change removes the gate, invert it again: assert NO prose references the
+ // flag, because a probe of a removed flag prints `disabled` (unknown flags are fail-closed) and
+ // would silently turn connector authoring back off.
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');
+ const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');
+ const probe = /feature-flags\.js"?\s+connectors\b/;
+ assert.match(builder, probe, 'the connector-builder owns the gate and must probe it');
+ assert.match(skill, probe, 'Phase 4.5 must re-probe the gate before deploying bindings');
+ // Both must describe the OFF outcome, or an agent has no defined behaviour for it.
+ assert.match(builder, /\bdisabled\b/, 'connector-builder must define the disabled path');
+ assert.match(skill, /\bdisabled\b/, 'Phase 4.5 must define the disabled path');
+});
+
+test('connector metadata discovery uses the PAC connector name, not the full API resource path', () => {
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');
+ assert.match(
+ builder,
+ /terminal segment|final path segment/i,
+ 'connector-builder must explain how to derive the short PAC connector name from connectorId',
+ );
+ assert.match(
+ builder,
+ /--connector-id <connectorName>/,
+ 'PAC metadata commands must receive the short connector name',
+ );
+ assert.match(
+ builder,
+ /connectors\.json[\s\S]*full.*connectorId|full.*connectorId[\s\S]*connectors\.json/i,
+ 'the persisted binding must retain the full connector resource path',
+ );
+});
+
+test('connector-builder defines setup when no suitable connection exists', () => {
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-connector-builder.md'), 'utf8');
+ assert.match(builder, /power-apps\s+create-connection/, 'connector-builder must document the connection-creation command');
+ assert.match(builder, /POWERAPPS_CLI_ENABLE_BROWSER_CONNECTION/, 'interactive connector setup gate must be explicit');
+ // Bare /needs_input/ is the agent's universal return shape and was already present, so it
+ // asserted nothing. Anchor to the connection-setup path that must hand back to the orchestrator.
+ // Spans use `\s+`/bounded `[\s\S]` rather than literal spaces and `[^\n]*`: these phrases sit on
+ // hard-wrapped ~76-col prose lines, so a pure re-wrap (identical words, different line breaks)
+ // would otherwise break the build for no safety gain. Word order is still required.
+ assert.match(
+ builder,
+ /create-connection[\s\S]{0,120}reports\s+that\s+login[\s\S]{0,200}needs_input/i,
+ 'connection setup that requires interaction must return to the orchestrator',
+ );
+ assert.match(builder, /Org URL[\s\S]*<ENV_URL>|<ENV_URL>[\s\S]*Org URL/i, 'connection setup must compare the active profile with the resolved environment');
+ assert.match(builder, /mismatch[\s\S]*needs_input|needs_input[\s\S]*mismatch/i, 'an environment mismatch must stop before mutation');
+ assert.match(builder, /auth-status/, 'headless setup must inspect cached Power Apps CLI accounts');
+ assert.match(builder, /auth-switch/, 'headless setup may switch only to an already-cached account');
+ assert.match(builder, /never.*login|do not.*login/i, 'the headless worker must not launch browser login');
+ assert.match(builder, /homeAccountId/, 'cached account selection must be tenant-specific');
+ // "exactly one" and "ambiguous" both occur in unrelated prose; anchor to the cached-match rule.
+ assert.match(builder, /exactly\s+one\*{0,2}\s+cached\s+match/i, 'duplicate cached usernames must fail closed');
+ assert.match(builder, /Node 22|major.*22|22\+/i, 'the optional Power Apps CLI path must guard its Node requirement');
+ assert.match(builder, /UsGovHigh[\s\S]*usgovhigh/, 'sovereign cloud mapping must be explicit');
+ assert.match(builder, /unknown[\s\S]*cloud[\s\S]*needs_input|needs_input[\s\S]*unknown[\s\S]*cloud/i, 'unknown clouds must fail closed');
+});
+
+test('genpage orchestrator defines inline recovery for a worker missing declared tools', () => {
+ const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');
+ const editFlow = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'), 'utf8');
+ // No `s` flag and no unbounded `[\s\S]*`: with them, `.*` spans the whole document and any doc
+ // containing "missing" … "file" … "tool" anywhere passes. Anchor to the new sentence instead.
+ assert.match(skill, /declared\s+file\s+or\s+process-execution\s+tools\s+are\s+unavailable/i);
+ assert.match(skill, /inline fallback|run the worker workflow inline/i);
+ assert.match(skill, /do\s+(?:\*\*)?not(?:\*\*)?\s+(?:re-dispatch|retry the same worker)/i);
+ assert.match(skill, /genpage-planner[\s\S]*file tools[\s\S]*halt/i, 'create planner file-tool failure must preserve plan provenance');
+ // `genpage-edit-planner` is deliberately absent from this loop: it already passed against the
+ // pre-change doc, so including it advertised coverage the loop did not provide — the same trap
+ // that made the earlier assertions vacuous. The anchored assertion below owns that worker.
+ for (const worker of ['genpage-connector-builder', 'genpage-customapi-builder']) {
+ assert.match(editFlow, new RegExp(`${worker}[\\s\\S]{0,1200}(?:tool|unavailable|halt|inline)`, 'i'), `edit flow must define a missing-tool outcome for ${worker}`);
+ }
+ // Anchored to the edit-planner's own halt rule. A loose /edit-planner[\s\S]*halt/ matched
+ // unrelated prose elsewhere in the file and passed before this rule was written.
+ assert.match(
+ editFlow,
+ /genpage-edit-planner[\s\S]{0,160}declared\s+file\s+tools\s+are\s+unavailable[\s\S]{0,400}Halt\s+the\s+edit\s+flow/i,
+ 'edit planner failure must preserve plan provenance by halting',
+ );
+});
+
+test('page generation rejects Griffel borderWidth shorthand before deploy', () => {
+ const rules = fs.readFileSync(path.join(PLUGIN, 'references', 'rules.md'), 'utf8');
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');
+ const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), 'utf8');
+ const editFlow = fs.readFileSync(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'), 'utf8');
+ assert.match(rules, /borderWidth/i, 'rules must name the runtime-only Griffel failure');
+ assert.match(builder, /borderWidth/i, 'page-builder must scan its output for the shorthand');
+ assert.match(skill, /borderWidth/i, 'inline page generation must run the same scan');
+ assert.match(editFlow, /borderWidth/i, 'edited pages must run the same scan before upload');
+ const documentedPattern = `['"]?borderWidth['"]?\\s*:`;
+ for (const [name, text] of [['rules', rules], ['page-builder', builder], ['create flow', skill], ['edit flow', editFlow]]) {
+ assert.ok(text.includes(documentedPattern), `${name} must carry the complete Griffel key regex`);
+ }
+ const regex = /['"]?borderWidth['"]?\s*:/;
+ for (const source of ['borderWidth: 0', 'borderWidth : 0', '"borderWidth": 0', "'borderWidth' : 0"]) {
+ assert.match(source, regex, `guard must detect ${source}`);
+ }
+});
+
+// --- App Spec schema split -------------------------------------------------
+//
+// app-spec-schema.md is read IN FULL at the start of every /app-builder run, so the conditional
+// feature sections were moved to app-spec-schema-advanced.md and replaced by a pointer table.
+//
+// The pointer table is the ONLY thing that tells an agent those capabilities exist. If a section
+// is added to the advanced doc without a matching row — or a row survives a section being renamed
+// — the agent silently stops offering that capability, which shows up as under-building (an app
+// missing a business process flow nobody realised it could have) rather than as an error.
+
+test('every advanced schema section is named in the pointer table, and vice versa', () => {
+ const core = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema.md'), 'utf8');
+ const adv = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema-advanced.md'), 'utf8');
+
+ // Sections in the advanced doc: "## globalChoices[] (optional — …)" → "globalChoices[]"
+ const sections = [...adv.matchAll(/^## (\S+)/gm)].map((m) => m[1]);
+ assert.ok(sections.length >= 8, `expected the advanced doc to carry its sections, found ${sections.length}`);
+
+ // Rows in the core doc's pointer table: "| `globalChoices[]` | shared option sets |"
+ const tableBlock = core.split(/^## Conditional features[^\n]*$/m)[1] || '';
+ const rows = [...tableBlock.split(/^## /m)[0].matchAll(/^\|\s*`([^`]+)`\s*\|/gm)].map((m) => m[1]);
+ assert.ok(rows.length >= 8, `expected a pointer row per advanced section, found ${rows.length}`);
+
+ assert.deepEqual(
+ [...sections].sort(),
+ [...rows].sort(),
+ 'the pointer table in app-spec-schema.md and the sections in app-spec-schema-advanced.md have drifted'
+ );
+});
+
+test('the core schema no longer carries the moved sections', () => {
+ // A section left in BOTH docs is worse than in neither: the two copies drift and an author
+ // follows whichever they happened to read.
+ const core = fs.readFileSync(path.join(PLUGIN, 'references', 'app-spec-schema.md'), 'utf8');
+ const coreSections = [...core.matchAll(/^## (\S+)/gm)].map((m) => m[1]);
+ for (const moved of ['globalChoices[]', 'webResources[]', 'commands[]', 'businessRules[]', 'dashboards[]', 'roleGrants[]']) {
+ assert.ok(!coreSections.includes(moved), `${moved} must live only in app-spec-schema-advanced.md`);
+ }
+});
+
+test('the skill tells the agent when to read the advanced schema', () => {
+ // The split only stays safe while the skill body routes the reader to it. Without this line an
+ // agent reads the core doc, never opens the advanced one, and quietly cannot author half the
+ // conditional features.
+ const skill = fs.readFileSync(path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'), 'utf8');
+ assert.match(skill, /app-spec-schema-advanced\.md/, '/app-builder must point at the advanced schema');
+ assert.match(skill, /conditional feature/i, 'and say when to read it');
+});
+//
+// Every field below is produced by a SKILL.md dispatch template and consumed by
+// genpage-page-builder. `Connectors` drifted because nothing executed that contract; the same
+// hazard applies to each of the others, so pin them all rather than the one that happened to break.
+
+// Producer → the two /genpage templates plus the one /app-builder template.
+function dispatchTemplates() {
+ const out = [];
+ for (const [file, re] of [
+ [path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'), /^> - (.+)$/gm],
+ [path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'), /^\s+> - (.+)$/gm],
+ ]) {
+ const src = fs.readFileSync(file, 'utf8');
+ const lines = [...src.matchAll(re)].map((m) => m[1].trim());
+ // Split into blocks on "Target file", which starts each template.
+ let cur = null;
+ for (const l of lines) {
+ if (/^Target file:/.test(l)) { cur = { file: rel(file), fields: [] }; out.push(cur); }
+ if (cur) cur.fields.push(l);
+ }
+ }
+ return out;
+}
+
+test('every page-builder dispatch template carries the same required field set', () => {
+ const templates = dispatchTemplates();
+ assert.ok(templates.length >= 3, `expected 3 dispatch templates (2 genpage + 1 app-builder), found ${templates.length}`);
+ // RuntimeTypes is deliberately conditional (dataverse pages only), so it is not required.
+ const required = ['Target file', 'Plan document', 'Data mode', 'Connectors', 'Telemetry', 'Working directory', 'Plugin root'];
+ for (const t of templates) {
+ for (const field of required) {
+ const has = t.fields.some((l) => new RegExp(`^${field}:`).test(l));
+ assert.ok(has, `${t.file} dispatch template is missing the "${field}:" line — the page-builder reads it`);
+ }
+ }
+});
+
+test('every dispatch field the page-builder documents is one a template actually sends', () => {
+ // Catches the reverse drift: a consumer input bullet nobody produces is dead documentation that
+ // an agent will still try to honour.
+ const builder = fs.readFileSync(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'), 'utf8');
+ // The input spec is the bulleted block under "You will be invoked with a prompt that includes:".
+ const specBlock = builder.split(/You will be invoked with a prompt that includes:/)[1] || '';
+ const spec = specBlock.split(/\n#{2,}\s/)[0];
+ const documented = [...spec.matchAll(/^- \*\*([^*]+)\*\*/gm)].map((m) => m[1].trim());
+ assert.ok(documented.length >= 7, `expected the page-builder input spec to list its fields, found ${documented.length}`);
+
+ const produced = new Set();
+ for (const t of dispatchTemplates()) for (const l of t.fields) produced.add((l.split(':')[0] || '').trim());
+
+ // Map the consumer's prose labels onto the wire field names where they differ.
+ const alias = { 'Page name': 'Target file', 'Plan document path': 'Plan document', 'RuntimeTypes path': 'RuntimeTypes' };
+ for (const d of documented) {
+ const wire = alias[d] || d;
+ assert.ok(produced.has(wire), `page-builder documents input "${d}" but no dispatch template sends a "${wire}:" line`);
+ }
+});
+
+test('Telemetry uses enabled|disabled and is never conflated with the Connectors vocabulary', () => {
+ // The two fields are gated differently — Telemetry is still a live feature flag (custom-telemetry),
+ // Connectors is derived from the plan — so they must not converge on one vocabulary by accident.
+ for (const t of dispatchTemplates()) {
+ const tel = t.fields.find((l) => /^Telemetry:/.test(l));
+ assert.ok(tel, `${t.file} has no Telemetry line`);
+ assert.match(tel, /\b(enabled|disabled)\b/, `${t.file}: Telemetry must be enabled|disabled, got: ${tel}`);
+ assert.doesNotMatch(tel, /binding\(s\)|\bnone\b/, `${t.file}: Telemetry must not use the Connectors vocabulary: ${tel}`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt b/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
index ff8c08fc8..7da6e9a8d 100644
--- a/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
+++ b/plugins/model-apps/scripts/tests/golden/journal.project-tracker.txt
@@ -16,3 +16,4 @@ app-shell start app icon (generated) new_projecttracker_icon
app-shell ok app icon (generated) new_projecttracker_icon
app-shell start app "Project Tracker"
app-shell ok app "Project Tracker"
+pages skip finalize sitemap (genpage subareas) (fresh page-less app — sitemap written on create)
diff --git a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
index ead231f13..b602c1bac 100644
--- a/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
+++ b/plugins/model-apps/scripts/tests/golden/journal.support-desk.txt
@@ -60,3 +60,4 @@ app-shell start app icon (generated) new_supportdesk_icon
app-shell ok app icon (generated) new_supportdesk_icon
app-shell start app "Support Desk"
app-shell ok app "Support Desk"
+pages skip finalize sitemap (genpage subareas) (fresh page-less app — sitemap written on create)
diff --git a/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt b/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
index 52cb155a9..86873591b 100644
--- a/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
+++ b/plugins/model-apps/scripts/tests/golden/plan.project-tracker.txt
@@ -7,4 +7,5 @@ views enrich default views for new_project
forms form for new_project
app-shell app module "Project Tracker" + sitemap
app-shell app icon (generated) new_projecttracker_icon
+pages finalize sitemap (genpage subareas)
publish publish customizations
diff --git a/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt b/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
index 714dfb8f0..089c427ba 100644
--- a/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
+++ b/plugins/model-apps/scripts/tests/golden/plan.support-desk.txt
@@ -29,4 +29,5 @@ forms form for new_ticket (sub-grids: new_comment)
forms form for new_comment
app-shell app module "Support Desk" + sitemap
app-shell app icon (generated) new_supportdesk_icon
+pages finalize sitemap (genpage subareas)
publish publish customizations
diff --git a/plugins/model-apps/scripts/tests/helpers/cli-harness.js b/plugins/model-apps/scripts/tests/helpers/cli-harness.js
new file mode 100644
index 000000000..0fc8501f6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/cli-harness.js
@@ -0,0 +1,73 @@
+// plugins/model-apps/scripts/tests/helpers/cli-harness.js
+// Loads a model-apps CLI in an isolated VM context with injectable module stubs, so a test can
+// drive main() end to end and assert the WIRE CALLS it makes — rather than regex-matching source.
+'use strict';
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+
+/**
+ * @param {string} scriptPath absolute path to the CLI under test
+ * @param {object} [opts]
+ * @param {object} [opts.requires] map of require-id → stub module (e.g. './lib/dataverse-auth')
+ * @param {string[]} [opts.argv] args after `node script.js`
+ * @param {object} [opts.env] process.env for the run
+ * @returns {{ main: Function, stdout: string[], stderr: string[], exitCode: number|null }}
+ */
+function loadCli(scriptPath, { requires = {}, argv = [], env = {} } = {}) {
+ // The CLIs guard their entry with `if (require.main === module)`, which never fires here — so
+ // export main() explicitly instead of relying on that guard to run it.
+ const source = `${fs.readFileSync(scriptPath, 'utf8')}\nmodule.exports.__mainForTest = typeof main === 'function' ? main : undefined;\n`;
+ const stdout = [];
+ const stderr = [];
+ const state = { exitCode: null };
+ const mod = { exports: {} };
+
+ const customRequire = (id) => {
+ // Match on the id as written in the script, tolerating the optional .js suffix so a stub
+ // registered as './lib/dataverse-auth' also satisfies `require('./lib/dataverse-auth.js')`.
+ if (Object.prototype.hasOwnProperty.call(requires, id)) return requires[id];
+ const noExt = id.replace(/\.js$/, '');
+ if (Object.prototype.hasOwnProperty.call(requires, noExt)) return requires[noExt];
+ if (id.startsWith('.')) return require(path.resolve(path.dirname(scriptPath), id));
+ return require(id);
+ };
+
+ // process.exit must abort the CLI the way the real one does, so a test can prove that nothing
+ // after a usage error ran. A plain return would let execution continue and silently pass.
+ const sandboxProcess = {
+ argv: ['node', scriptPath, ...argv],
+ env,
+ platform: process.platform,
+ execPath: process.execPath,
+ exitCode: undefined,
+ exit: (code) => {
+ state.exitCode = code;
+ const err = new Error(`process.exit(${code})`);
+ err.exitCode = code;
+ throw err;
+ },
+ stdout: { write: (s) => { stdout.push(String(s)); return true; } },
+ stderr: { write: (s) => { stderr.push(String(s)); return true; } },
+ };
+
+ // compileFunction — NOT runInNewContext. A new VM context is a separate realm with its own
+ // Array/Object prototypes, so every array the script builds would fail assert.deepStrictEqual
+ // against a host array with "same structure but not reference-equal". Compiling the module body
+ // as a function in the CURRENT realm keeps the intrinsics shared, and shadowing `process` via a
+ // parameter still isolates the CLI's exit/stdout/stderr.
+ const fn = vm.compileFunction(source, ['require', 'module', 'exports', 'process'], { filename: scriptPath });
+ fn(customRequire, mod, mod.exports, sandboxProcess);
+
+ return {
+ exports: mod.exports,
+ main: mod.exports.__mainForTest,
+ stdout,
+ stderr,
+ get exitCode() { return state.exitCode; },
+ stdoutText: () => stdout.join(''),
+ stderrText: () => stderr.join(''),
+ };
+}
+
+module.exports = { loadCli };
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-auth.js b/plugins/model-apps/scripts/tests/helpers/fake-auth.js
new file mode 100644
index 000000000..fb3578158
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/fake-auth.js
@@ -0,0 +1,31 @@
+// plugins/model-apps/scripts/tests/helpers/fake-auth.js
+// Shared piece of the CLI test harnesses that stub lib/dataverse-auth.js.
+'use strict';
+const realAuth = require('../../lib/dataverse-auth.js');
+
+/**
+ * Builds a `validateFlags` stand-in for a harness that cans `parseArgs` to a fixed result.
+ *
+ * Those harnesses never populate process.argv, so the shipped flag contract would go unexercised —
+ * and a hand-written copy of the check inside each harness would be free to drift from the real
+ * one. Instead this rebuilds an argv that parses back to the same flags and runs the REAL
+ * validateFlags over it, so a CLI whose declared `known` list omits a flag its own tests pass still
+ * fails loudly.
+ *
+ * parseArgs only ever yields boolean `true` (bare flag) or a string, so the two forms below round
+ * trip exactly: `true` → `--flag`, anything else → `--flag=value` (which also preserves the empty
+ * string that `--flag=` and `--flag ""` both produce).
+ *
+ * @param {() => object} getFlags reads the harness's current canned flags object
+ * @returns {(argv: string[], contract: object) => string|null}
+ */
+function validateFlagsFromParsed(getFlags) {
+ return (_argv, contract) => {
+ const flags = getFlags() || {};
+ const argv = [];
+ for (const [k, v] of Object.entries(flags)) argv.push(v === true ? `--${k}` : `--${k}=${v}`);
+ return realAuth.validateFlags(argv, contract);
+ };
+}
+
+module.exports = { validateFlagsFromParsed, realAuth };
diff --git a/plugins/model-apps/scripts/tests/interaction-mode.test.js b/plugins/model-apps/scripts/tests/interaction-mode.test.js
new file mode 100644
index 000000000..9361bf1d6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/interaction-mode.test.js
@@ -0,0 +1,107 @@
+'use strict';
+
+// Guards the unattended-mode rule. `/app-builder` and `/genpage` both branch on it, and the
+// failure it prevents is silent in both directions: guess "attended" under Copilot autopilot or
+// Claude auto-accept and the run stalls on a prompt nobody can see; guess "unattended" in a real
+// session and the user's questions are skipped and answered by default without being asked.
+
+const test = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const {
+ envTruthy,
+ resolveInteractionMode,
+ NONINTERACTIVE_ENV,
+} = require('../lib/interaction-mode.js');
+
+const CLI = path.join(__dirname, '..', 'resolve-interaction-mode.js');
+
+test('envTruthy: only 1/true (case-insensitive) count as set', () => {
+ for (const v of ['1', 'true', 'TRUE', ' True ']) assert.strictEqual(envTruthy(v), true, v);
+ for (const v of ['0', 'false', 'yes', '', null, undefined]) assert.strictEqual(envTruthy(v), false, String(v));
+});
+
+// Defaulting to attended is the deliberate choice: a stall is reported, a skipped question is not.
+test('with no flag and no env var the run is treated as attended', () => {
+ const mode = resolveInteractionMode({ argv: [], env: {} });
+ assert.strictEqual(mode.interactive, true);
+ assert.match(mode.reason, /default/);
+});
+
+test('--non-interactive marks the run unattended', () => {
+ const mode = resolveInteractionMode({ argv: ['--non-interactive'], env: {} });
+ assert.strictEqual(mode.interactive, false);
+ assert.match(mode.reason, /--non-interactive/);
+});
+
+test('the env var marks the run unattended without any flag', () => {
+ const mode = resolveInteractionMode({ argv: [], env: { [NONINTERACTIVE_ENV]: '1' } });
+ assert.strictEqual(mode.interactive, false);
+ assert.match(mode.reason, new RegExp(NONINTERACTIVE_ENV));
+});
+
+// A non-truthy value must not be read as "set" — `...=0` is how someone turns it OFF, and
+// treating it as unattended would silently suppress every prompt in an attended session.
+test('a falsy env value leaves the run attended', () => {
+ for (const v of ['0', 'false', '']) {
+ assert.strictEqual(resolveInteractionMode({ argv: [], env: { [NONINTERACTIVE_ENV]: v } }).interactive, true, v);
+ }
+});
+
+test('the flag is reported in preference to the env var when both point the same way', () => {
+ const mode = resolveInteractionMode({ argv: ['--non-interactive'], env: { [NONINTERACTIVE_ENV]: '1' } });
+ assert.strictEqual(mode.interactive, false);
+ assert.match(mode.reason, /--non-interactive/, 'the more specific signal should be the reported reason');
+});
+
+// The reason travels into workflow-log.md, so it has to be a stable, human-readable string
+// rather than a boolean a reader has to decode.
+test('every resolved mode carries a non-empty reason', () => {
+ const cases = [
+ { argv: [], env: {} },
+ { argv: ['--non-interactive'], env: {} },
+ { argv: [], env: { [NONINTERACTIVE_ENV]: 'true' } },
+ ];
+ for (const c of cases) {
+ const mode = resolveInteractionMode(c);
+ assert.ok(typeof mode.reason === 'string' && mode.reason.length > 0, JSON.stringify(c));
+ }
+});
+
+test('resolveInteractionMode tolerates being called with nothing', () => {
+ const mode = resolveInteractionMode();
+ assert.strictEqual(typeof mode.interactive, 'boolean');
+});
+
+// The CLI is what the skill actually runs, so its contract is asserted end to end: one JSON
+// line on stdout and exit 0 even when the answer is "no user".
+test('the CLI emits one JSON line and exits 0 when unattended', () => {
+ const res = spawnSync(process.execPath, [CLI], {
+ encoding: 'utf8',
+ env: { ...process.env, [NONINTERACTIVE_ENV]: '1' },
+ });
+ assert.strictEqual(res.status, 0, res.stderr);
+ const lines = res.stdout.trim().split('\n');
+ assert.strictEqual(lines.length, 1, res.stdout);
+ const out = JSON.parse(lines[0]);
+ assert.strictEqual(out.ok, true);
+ assert.strictEqual(out.interactive, false);
+});
+
+test('the CLI reports attended when nothing marks the run unattended', () => {
+ const env = { ...process.env };
+ delete env[NONINTERACTIVE_ENV];
+ const res = spawnSync(process.execPath, [CLI], { encoding: 'utf8', env });
+ assert.strictEqual(res.status, 0, res.stderr);
+ assert.strictEqual(JSON.parse(res.stdout.trim()).interactive, true);
+});
+
+test('the CLI honours the flag', () => {
+ const env = { ...process.env };
+ delete env[NONINTERACTIVE_ENV];
+ const res = spawnSync(process.execPath, [CLI, '--non-interactive'], { encoding: 'utf8', env });
+ assert.strictEqual(res.status, 0, res.stderr);
+ assert.strictEqual(JSON.parse(res.stdout.trim()).interactive, false);
+});
diff --git a/plugins/model-apps/scripts/tests/lint-app-spec.test.js b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
index bab0ce14d..73fe6a23c 100644
--- a/plugins/model-apps/scripts/tests/lint-app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
@@ -156,6 +156,16 @@ test('CLI --profile deploy is available for gating a final, deployable spec', ()
assert.match(deploy.stdout, /FAIL \[profile: deploy\]/);
});
+test('CLI rejects an implemented page whose codeFile is missing on disk', () => {
+ const s = good();
+ s.pages = [{ key: 'ov', name: 'Overview', source: { kind: 'tsx', codeFile: 'missing.tsx' } }];
+ s.appShell = { areas: [{ label: 'M', groups: [{ label: 'M', subAreas: [{ title: 'Overview', page: 'ov' }] }] }] };
+ const out = runCli(s, ['--profile', 'deploy', '--json']);
+ assert.strictEqual(out.code, 1);
+ const payload = JSON.parse(out.stdout);
+ assert.ok(payload.errors.some((error) => /missing\.tsx.*does not exist or is not a file/.test(error)), out.stdout);
+});
+
// Regression contract. The JSON payload's `ok` must describe the COMMAND's outcome. A warnings-only
// --strict run exits 1, so emitting ok:true there would let a machine consumer read a failure as
// a success.
@@ -224,8 +234,8 @@ test('CLI rejects a value-taking flag given with no value', () => {
fs.writeFileSync(file, JSON.stringify(good()));
try {
for (const [args, expected] of [
- [[CLI, '--spec'], /--spec needs a path/],
- [[CLI, '--spec', '@' + file, '--profile'], /--profile needs one of: design, plan, deploy, structural/],
+ [[CLI, '--spec'], /--spec requires a value — a path/],
+ [[CLI, '--spec', '@' + file, '--profile'], /--profile requires a value — one of: design, plan, deploy, structural/],
]) {
let out;
try {
@@ -253,9 +263,9 @@ test('CLI rejects an EMPTY value-taking flag instead of silently taking the defa
fs.writeFileSync(file, JSON.stringify(good()));
try {
for (const [args, expected] of [
- [[CLI, '--spec', '@' + file, '--profile='], /--profile needs one of: design, plan, deploy, structural/],
- [[CLI, '--spec', '@' + file, '--profile', ''], /--profile needs one of: design, plan, deploy, structural/],
- [[CLI, '--spec='], /--spec needs a path/],
+ [[CLI, '--spec', '@' + file, '--profile='], /--profile requires a value — one of: design, plan, deploy, structural/],
+ [[CLI, '--spec', '@' + file, '--profile', ''], /--profile requires a value — one of: design, plan, deploy, structural/],
+ [[CLI, '--spec='], /--spec requires a value — a path/],
]) {
let out;
try {
diff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.js
index 67900a2ad..993bae11e 100644
--- a/plugins/model-apps/scripts/tests/list-connections.test.js
+++ b/plugins/model-apps/scripts/tests/list-connections.test.js
@@ -22,22 +22,33 @@ test('documents raw pac output parsed', () => {
});
test('missing args exits 1 with usage', () => {
- // Enable connectors so the run reaches arg validation instead of the feature gate.
- const res = spawnSync(process.execPath, [scriptPath], {
- encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
- });
+ const res = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });
assert.equal(res.status, 1);
assert.match(res.stderr, /Usage:/);
});
-test('exits 3 with a disabled message when the connectors flag is OFF', () => {
- // Gate runs before any pac/Dataverse call, so a valid-looking env URL still bails.
- const res = spawnSync(process.execPath, [scriptPath, 'https://example.crm.dynamics.com'], {
+test('an unknown flag is a usage error, not a token the CLI silently swallows', () => {
+ // Without validateFlags, parseArgs drops `--environment` AND eats the URL after it, so this
+ // typo left `positional` empty and the CLI reported a MISSING envUrl the caller had supplied.
+ const res = spawnSync(
+ process.execPath,
+ [scriptPath, '--environment', 'https://contoso.crm.dynamics.com'],
+ { encoding: 'utf8' }
+ );
+ assert.equal(res.status, 1, 'a usage error is exit 1, distinct from the exit 3 rollback gate');
+ assert.match(res.stderr, /unknown flag\(s\): --environment/);
+ assert.match(res.stderr, /Usage:/);
+});
+
+test('the rollback switch still works end to end (exit 3, distinct from a usage error)', () => {
+ // connectors ships ON, so this is the path that only runs if someone turns it off. Exercise it
+ // for real: a gate that has quietly stopped working is worthless as a rollback, and nothing else
+ // would notice until it was needed.
+ const res = spawnSync(process.execPath, [scriptPath, 'https://contoso.crm.dynamics.com'], {
encoding: 'utf8',
env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' },
});
- assert.equal(res.status, 3);
+ assert.equal(res.status, 3, 'exit 3 = feature off, distinct from 1 = usage/runtime error');
assert.match(res.stderr, /disabled/i);
});
@@ -82,3 +93,112 @@ test('pacFailureMessage distinguishes a missing PAC CLI (spawn error) from a com
assert.match(failed, /exit 1/);
assert.match(failed, /Access denied/);
});
+
+// --- `pac connection list` output parsing -----------------------------------
+//
+// This is the highest-risk code in the script: PAC emits three different shapes across builds,
+// and a mis-parse is SILENT — it yields "no connections found", which reads as an environment
+// with no connectors rather than as a parser that stopped working.
+
+const {
+ parsePacConnectionList, parseJsonConnections, parseWhitespaceTable, mapConnectionRow, extractConnectorId,
+} = require(scriptPath);
+
+const SP_CONN = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline/connections/abc';
+
+test('parses the fixed-width table PAC emits by default', () => {
+ // Connection Name Connector Id Connection Id
+ // --------------------- ------------------------------- ------------------
+ // Contoso SharePoint /providers/.../shared_sharepoint /providers/.../connections/abc
+ const raw = [
+ 'Connection Name Connector Id Connection Id',
+ '--------------------- ----------------------------------------------------------- ------------------------------------',
+ `Contoso SharePoint ${SP_API} ${SP_CONN}`,
+ ].join('\n');
+ assert.deepEqual(parsePacConnectionList(raw), [
+ { connectorId: SP_API, connectionId: SP_CONN, displayName: 'Contoso SharePoint' },
+ ]);
+});
+
+test('parses a bare JSON array and derives the connector id from the connection id', () => {
+ // Older/newer PAC builds emit JSON without a Connector Id column at all, so the connector has
+ // to be recovered from the connection resource path or every row loses its binding target.
+ const raw = JSON.stringify([
+ { 'Connection Name': 'Weather', 'Connection Id': '/providers/Microsoft.PowerApps/apis/shared_msnweather/connections/z' },
+ ]);
+ assert.deepEqual(parsePacConnectionList(raw), [{
+ connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather',
+ connectionId: '/providers/Microsoft.PowerApps/apis/shared_msnweather/connections/z',
+ displayName: 'Weather',
+ }]);
+});
+
+test('parses the { value: [...] } JSON envelope as well as a bare array', () => {
+ const raw = JSON.stringify({ value: [{ connectionId: SP_CONN, connectorId: SP_API, displayName: 'SP' }] });
+ assert.deepEqual(parsePacConnectionList(raw), [{ connectorId: SP_API, connectionId: SP_CONN, displayName: 'SP' }]);
+});
+
+test('falls back to a whitespace-separated table when there is no dashed separator row', () => {
+ const raw = [
+ 'Connection Name Connector Id Connection Id',
+ `Contoso SP ${SP_API} ${SP_CONN}`,
+ ].join('\n');
+ assert.deepEqual(parseWhitespaceTable(raw), [
+ { connectorId: SP_API, connectionId: SP_CONN, displayName: 'Contoso SP' },
+ ]);
+});
+
+test('parses current PAC Id/Name/API Id/Status output without a separator row', () => {
+ const raw = [
+ 'Id Name API Id Status',
+ '00000000000000000000000000000001 [email protected] /providers/Microsoft.PowerApps/apis/shared_commondataservice Connected',
+ '00000000000000000000000000000002 Contoso Smoke Test - Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps Connected',
+ ].join('\n');
+
+ assert.deepEqual(parsePacConnectionList(raw), [
+ {
+ connectorId: '/providers/Microsoft.PowerApps/apis/shared_commondataservice',
+ connectionId: '00000000000000000000000000000001',
+ displayName: '[email protected]',
+ },
+ {
+ connectorId: '/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps',
+ connectionId: '00000000000000000000000000000002',
+ displayName: 'Contoso Smoke Test - Dataverse',
+ },
+ ]);
+});
+
+test('header matching is case- and punctuation-insensitive', () => {
+ // normalizeHeader strips non-alphanumerics and lower-cases, so "Connection Id", "connectionId"
+ // and "CONNECTION-ID" are the same column. Without that, a cosmetic CLI header change silently
+ // empties every row.
+ for (const row of [
+ { 'Connection Name': 'N', 'Connector Id': 'C', 'Connection Id': 'I' },
+ { connectionName: 'N', connectorId: 'C', connectionId: 'I' },
+ { 'CONNECTION-NAME': 'N', 'CONNECTOR_ID': 'C', 'connection id': 'I' },
+ ]) {
+ assert.deepEqual(mapConnectionRow(row), { connectorId: 'C', connectionId: 'I', displayName: 'N' });
+ }
+});
+
+test('extractConnectorId returns the api path, or empty string when there is none', () => {
+ assert.equal(extractConnectorId(SP_CONN), SP_API);
+ // Empty string (not null/undefined) — mapConnectionRow ORs through this value, so a nullish
+ // return would fall through to a different field and mislabel the row.
+ assert.equal(extractConnectorId('garbage'), '');
+});
+
+test('unparseable output yields no rows rather than throwing', () => {
+ // The caller reports "no connections found"; a throw here would abort a /genpage run that could
+ // still proceed with mock data.
+ assert.deepEqual(parsePacConnectionList('no table here'), []);
+ assert.deepEqual(parsePacConnectionList(''), []);
+ assert.equal(parseJsonConnections('{not json'), null, 'invalid JSON defers to the table parsers');
+ assert.equal(parseJsonConnections('"a string"'), null, 'non-array JSON defers too');
+});
+
+test('rows with no identifying field at all are dropped', () => {
+ const raw = JSON.stringify([{ 'Connection Name': '', 'Connection Id': '' }, { 'Connection Name': 'Real', 'Connection Id': SP_CONN }]);
+ assert.deepEqual(parsePacConnectionList(raw).map((r) => r.displayName), ['Real']);
+});
diff --git a/plugins/model-apps/scripts/tests/live-plan.test.js b/plugins/model-apps/scripts/tests/live-plan.test.js
new file mode 100644
index 000000000..c092b8bba
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/live-plan.test.js
@@ -0,0 +1,437 @@
+'use strict';
+// #559 — the live dry-run plan. `runSdkBuild` used to print planFor's static, spec-derived listing
+// and exit before any discovery, so the SAME plan appeared for a spec whose artifacts all exist and
+// for one that would create everything from nothing.
+//
+// These drive `annotateLivePlan` directly with a purpose-built reader so each artifact kind and each
+// failure mode is exercised on its own. The end-to-end behaviour (states reaching the CLI result) is
+// covered in sdk-build.test.js.
+
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+const { annotateLivePlan, planFor } = require(path.join(__dirname, '..', 'lib', 'sdk-build.js'));
+const { relationshipSchemaName, manyToManySchemaName } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));
+
+// A minimal provision double. `tables` maps logical -> { columns: [], relationships: [] }; `rows`
+// maps an entity set to the rows a query should return. Records every read so the tests can assert
+// on CACHING as well as on outcomes.
+function reader({ tables = {}, rows = {}, failMetadata = false, failQuery = false } = {}) {
+ const reads = [];
+ const provision = {
+ dataverse: {
+ get: async (url) => {
+ reads.push(url);
+ if (failMetadata) throw new Error('metadata service unavailable');
+ // Relationship collections: /EntityDefinitions(LogicalName='x')/OneToManyRelationships?$select=SchemaName
+ const rel = /EntityDefinitions\(LogicalName='([^']+)'\)\/(OneToMany|ManyToMany)Relationships/.exec(url);
+ if (rel) {
+ const t = tables[rel[1]];
+ if (!t) return { status: 404, body: {} };
+ return { status: 200, body: { value: (t.relationships || []).map((s) => ({ SchemaName: s })) } };
+ }
+ // /EntityDefinitions(LogicalName='x')?$select=... and .../Attributes?$select=...
+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)(\/Attributes)?/.exec(url);
+ const logical = m && m[1];
+ const t = tables[logical];
+ if (!t) return { status: 404, body: {} };
+ if (m[2]) {
+ return { status: 200, body: { value: (t.columns || []).map((c) => ({ LogicalName: c, RequiredLevel: { Value: 'None' } })) } };
+ }
+ return { status: 200, body: { LogicalName: logical, EntitySetName: `${logical}s` } };
+ },
+ },
+ queryRecords: async (set, o) => {
+ reads.push(`${set}:${(o && o.filter) || ''}`);
+ if (failQuery) throw new Error('query refused');
+ return rows[set] || [];
+ },
+ fetchEntityMetadata: async (logical) => {
+ reads.push(`fetchEntityMetadata:${logical}`);
+ const t = tables[logical];
+ if (!t) throw new Error('not found');
+ return { logicalName: logical, entitySetName: `${logical}s`, attributes: (t.columns || []).map((c) => ({ logicalName: c })), relationships: (t.relationships || []).map((s) => ({ schemaName: s, type: 'OneToMany' })) };
+ },
+ findTables: async (q) => {
+ reads.push(`findTables:${q}`);
+ const logical = String(q).toLowerCase();
+ return tables[logical] ? [{ logicalName: logical, entitySetName: `${logical}s` }] : [];
+ },
+ };
+ return { provision, reads };
+}
+
+const stateOf = (plan, frag) => (plan.find((p) => p.label.includes(frag)) || {}).state;
+
+test('#559 a table reads reuse when present and create when absent', async () => {
+ const plan = [
+ { phase: 'data-model', label: 'table new_here', key: { kind: 'table', entity: 'new_here' } },
+ { phase: 'data-model', label: 'table new_gone', key: { kind: 'table', entity: 'new_gone' } },
+ ];
+ const { provision } = reader({ tables: { new_here: { columns: [] } } });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'new_here'), 'reuse');
+ assert.strictEqual(stateOf(plan, 'new_gone'), 'create');
+});
+
+test('#559 a column on a MISSING table is create without reading its attributes', async () => {
+ const plan = [
+ { phase: 'data-model', label: 'table new_gone', key: { kind: 'table', entity: 'new_gone' } },
+ { phase: 'data-model', label: 'column new_gone.new_x', key: { kind: 'column', entity: 'new_gone', name: 'new_x' } },
+ ];
+ const { provision, reads } = reader({ tables: {} });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'column new_gone.new_x'), 'create');
+ assert.ok(!reads.some((r) => /\/Attributes/.test(r)),
+ 'asking for the attributes of a table that does not exist only produces a metadata-cache error');
+});
+
+test('#559 columns on an existing table resolve individually', async () => {
+ const plan = [
+ { phase: 'data-model', label: 'column new_t.new_a', key: { kind: 'column', entity: 'new_t', name: 'new_a' } },
+ { phase: 'data-model', label: 'column new_t.new_b', key: { kind: 'column', entity: 'new_t', name: 'new_b' } },
+ ];
+ const { provision } = reader({ tables: { new_t: { columns: ['new_a'] } } });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'new_t.new_a'), 'reuse');
+ assert.strictEqual(stateOf(plan, 'new_t.new_b'), 'create');
+});
+
+// A plan routinely carries dozens of columns per table. Re-reading the table's metadata per column
+// would turn a dry run into a slow, rate-limit-prone crawl.
+test('#559 table and attribute metadata are read ONCE per entity however many columns are planned', async () => {
+ const plan = [{ phase: 'data-model', label: 'table new_t', key: { kind: 'table', entity: 'new_t' } }];
+ for (let i = 0; i < 12; i++) plan.push({ phase: 'data-model', label: `column new_t.c${i}`, key: { kind: 'column', entity: 'new_t', name: `c${i}` } });
+ const { provision, reads } = reader({ tables: { new_t: { columns: ['c0'] } } });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ const defs = reads.filter((r) => /EntityDefinitions\(LogicalName='new_t'\)\?/.test(r)).length;
+ const attrs = reads.filter((r) => /\/Attributes/.test(r)).length;
+ assert.strictEqual(defs, 1, `table metadata read ${defs} times`);
+ assert.strictEqual(attrs, 1, `attribute metadata read ${attrs} times`);
+});
+
+test('#559 a relationship resolves from the entity metadata', async () => {
+ const plan = [
+ { phase: 'data-model', label: 'relationship 1:N a->b', key: { kind: 'relationship', entity: 'new_child', name: 'new_a_b', relType: 'OneToMany' } },
+ { phase: 'data-model', label: 'relationship 1:N a->c', key: { kind: 'relationship', entity: 'new_child', name: 'new_missing', relType: 'OneToMany' } },
+ ];
+ const { provision } = reader({ tables: { new_child: { columns: [], relationships: ['new_a_b'] } } });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'a->b'), 'reuse');
+ assert.strictEqual(stateOf(plan, 'a->c'), 'create');
+});
+
+test('#559 views, charts and forms resolve through the identity query the BUILD uses', async () => {
+ const plan = [
+ { phase: 'views', label: 'view "Open" for new_t', key: { kind: 'view', entity: 'new_t', name: 'Open' } },
+ { phase: 'charts', label: 'chart "By Status" for new_t', key: { kind: 'chart', entity: 'new_t', name: 'By Status' } },
+ { phase: 'forms', label: 'form for new_t', key: { kind: 'form', entity: 'new_t', name: 'Main', formType: 'Main' } },
+ ];
+ const { provision, reads } = reader({
+ tables: { new_t: { columns: [] } },
+ rows: { savedquery: [{ savedqueryid: 'v1' }], savedqueryvisualization: [], systemform: [{ formid: 'f1' }] },
+ });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'view "Open"'), 'reuse');
+ assert.strictEqual(stateOf(plan, 'chart "By Status"'), 'create');
+ assert.strictEqual(stateOf(plan, 'form for new_t'), 'reuse');
+ // The form query must scope by TYPE, or a same-named Quick View would answer for the Main form.
+ assert.ok(reads.some((r) => /^systemform:.*type eq 2/.test(r)), JSON.stringify(reads));
+});
+
+test('#559 a view/form/chart on a table that does not exist is create, with no artifact query', async () => {
+ const plan = [{ phase: 'views', label: 'view "Open" for new_gone', key: { kind: 'view', entity: 'new_gone', name: 'Open' } }];
+ const { provision, reads } = reader({ tables: {} });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'view "Open"'), 'create');
+ assert.ok(!reads.some((r) => r.startsWith('savedquery:')), 'the filter would 400 on the metadata cache');
+});
+
+test('#559 the app module resolves by its deterministic unique name', async () => {
+ const present = [{ phase: 'app-shell', label: 'app module "X" + sitemap', key: { kind: 'app', uniqueName: 'new_x' } }];
+ const absent = [{ phase: 'app-shell', label: 'app module "Y" + sitemap', key: { kind: 'app', uniqueName: 'new_y' } }];
+ await annotateLivePlan(present, { spec: {}, provision: reader({ rows: { appmodule: [{ appmoduleid: 'a1' }] } }).provision });
+ await annotateLivePlan(absent, { spec: {}, provision: reader({ rows: {} }).provision });
+ assert.strictEqual(present[0].state, 'reuse');
+ assert.strictEqual(absent[0].state, 'create');
+});
+
+// The three-state contract. Collapsing a failed read into either decision presents a guess as a
+// fact: "create" overstates the work, "reuse" understates it.
+test('#559 a read that fails on BOTH paths is unknown and carries the reason', async () => {
+ const plan = [{ phase: 'data-model', label: 'table new_t', key: { kind: 'table', entity: 'new_t' } }];
+ const { provision } = reader({ failMetadata: true });
+ // findExistingTable falls back to findTables when the narrow metadata read is inconclusive, so a
+ // genuine "cannot read" has to fail that too — otherwise the fallback legitimately answers.
+ provision.findTables = async () => { throw new Error('metadata service unavailable'); };
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, 'unknown');
+ assert.match(plan[0].stateWhy, /metadata service unavailable/);
+});
+
+// Documents the fallback rather than treating it as a failure: an inconclusive NARROW read followed
+// by a conclusive findTables is a real answer, and reporting it as `unknown` would be needlessly
+// pessimistic on an environment that answered the question.
+test('#559 an inconclusive narrow read still resolves when findTables answers', async () => {
+ const plan = [
+ { phase: 'data-model', label: 'table new_here', key: { kind: 'table', entity: 'new_here' } },
+ { phase: 'data-model', label: 'table new_gone', key: { kind: 'table', entity: 'new_gone' } },
+ ];
+ const { provision } = reader({ tables: { new_here: { columns: [] } }, failMetadata: true });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(stateOf(plan, 'new_here'), 'reuse', 'findTables found it');
+ assert.strictEqual(stateOf(plan, 'new_gone'), 'create', 'findTables conclusively did not');
+});
+
+test('#559 a failed artifact query is unknown, not a silent create', async () => {
+ const plan = [{ phase: 'views', label: 'view "Open" for new_t', key: { kind: 'view', entity: 'new_t', name: 'Open' } }];
+ const { provision } = reader({ tables: { new_t: { columns: [] } }, failQuery: true });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, 'unknown');
+ assert.match(plan[0].stateWhy, /query refused/);
+});
+
+test('#559 an item with no key is left unprobed rather than guessed', async () => {
+ const plan = [{ phase: 'publish', label: 'publish customizations' }];
+ const { provision, reads } = reader({});
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, undefined, 'no state at all — the plan line still prints');
+ assert.deepStrictEqual(reads, [], 'and nothing is read for it');
+});
+
+// Review finding. `findExistingColumns` is written for the APPLY path, where a failed read safely
+// means "assume every column is new" (the create absorbs duplicates). A dry run has nothing to
+// absorb anything, so the same `[]` would print `+ create` for columns that exist.
+test('#559 a failed ATTRIBUTE read is unknown, not "every column is new"', async () => {
+ const plan = [{ phase: 'data-model', label: 'column new_t.new_a', key: { kind: 'column', entity: 'new_t', name: 'new_a' } }];
+ const { provision } = reader({ tables: { new_t: { columns: ['new_a'] } } });
+ const realGet = provision.dataverse.get;
+ provision.dataverse.get = async (url) => (/\/Attributes/.test(url) ? { status: 503, body: {} } : realGet(url));
+ provision.findColumns = undefined;
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, 'unknown');
+ assert.match(plan[0].stateWhy, /attributes could not be read/);
+});
+
+// Review finding. `relationshipExists` returns null when inconclusive. The apply path treats that as
+// absent because its create absorbs the race; a plan must say it does not know.
+test('#559 an inconclusive RELATIONSHIP probe is unknown, not create', async () => {
+ const plan = [{ phase: 'data-model', label: 'relationship 1:N a->b', key: { kind: 'relationship', entity: 'new_p', name: 'new_a_b', relType: 'OneToMany' } }];
+ const { provision } = reader({ tables: { new_p: { columns: [], relationships: [] } } });
+ provision.dataverse.get = async () => ({ status: 503, body: {} });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, 'unknown');
+});
+
+// Review finding. The BROAD `fetchEntityMetadata` fallback inside relationshipExists writes the
+// fetched metadata into the on-disk workspace, which a read-only dry run must not do — it would
+// change cached state a later apply reads.
+test('#559 the relationship probe never takes the workspace-writing fetchEntityMetadata fallback', async () => {
+ const plan = [{ phase: 'data-model', label: 'relationship 1:N a->b', key: { kind: 'relationship', entity: 'new_p', name: 'new_a_b', relType: 'OneToMany' } }];
+ const { provision, reads } = reader({ tables: { new_p: { columns: [], relationships: ['new_a_b'] } } });
+ provision.dataverse.get = async () => ({ status: 503, body: {} }); // force the inconclusive path
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.ok(!reads.some((r) => r.startsWith('fetchEntityMetadata:')), JSON.stringify(reads));
+});
+
+// Review finding. A pinned `formId` that is stale/foreign makes the APPLY halt. Reporting that as a
+// confident create or reuse hides it; `resolveExistingFormId` raises, and the reason is actionable.
+test('#559 a stale pinned formId surfaces as unknown with the resolver\'s own message', async () => {
+ const plan = [{ phase: 'forms', label: 'form for new_t', key: { kind: 'form', entity: 'new_t', name: 'Main', formType: 'Main', formId: '11111111-1111-1111-1111-111111111111' } }];
+ const { provision } = reader({ tables: { new_t: { columns: [] } }, rows: { systemform: [] } });
+ await annotateLivePlan(plan, { spec: {}, provision });
+ assert.strictEqual(plan[0].state, 'unknown');
+ assert.match(plan[0].stateWhy, /does not exist on this environment/);
+});
+
+// planFor must attach the keys the annotator joins on. A key silently dropped from a plan line turns
+// that line permanently unprobed — which looks exactly like the bug #559 fixed.
+// Review finding, HIGH. The probe identity must match the one the APPLY path uses, or an existing
+// relationship is confidently reported as `create`. `provisionDataModel` queries the REFERENCED
+// (parent) entity's OneToManyRelationships — the child's collection does not contain it — and builds
+// the schema name WITH the publisher prefix. Both were wrong here, and both are invisible for a
+// SELF-referencing relationship (referenced === referencing), which is the shape this was first
+// tested on: the live run that "verified" it could not have caught either.
+test('#559 the relationship key matches the identity the apply path probes', () => {
+ const spec = {
+ solution: { uniqueName: 'S', publisherPrefix: 'zzz' },
+ app: { name: 'A' },
+ entities: [
+ { schemaName: 'zzz_parent', displayName: 'P', pluralName: 'Ps', primaryAttribute: { schemaName: 'zzz_name', displayName: 'N' }, columns: [] },
+ { schemaName: 'zzz_child', displayName: 'C', pluralName: 'Cs', primaryAttribute: { schemaName: 'zzz_name', displayName: 'N' }, columns: [] },
+ ],
+ relationships: [
+ { type: 'OneToMany', referenced: 'zzz_parent', referencing: 'zzz_child', lookup: { schemaName: 'zzz_ParentId', displayName: 'P' } },
+ { type: 'ManyToMany', entity1: 'zzz_parent', entity2: 'zzz_child' },
+ ],
+ };
+ const plan = planFor(spec, { sampleData: false, publish: false, phases: undefined });
+ const oneToMany = plan.find((p) => p.label.includes('relationship 1:N')).key;
+ const manyToMany = plan.find((p) => p.label.includes('relationship N:N')).key;
+
+ assert.strictEqual(oneToMany.entity, 'zzz_parent',
+ 'the 1:N probe targets the REFERENCED entity — the child holds no OneToManyRelationships entry');
+ assert.strictEqual(manyToMany.entity, 'zzz_parent', 'N:N probes entity1, as the apply path does');
+ // The schema names must be the prefixed ones the apply path builds, or the probe looks for a name
+ // Dataverse never created.
+ assert.strictEqual(oneToMany.name, relationshipSchemaName(spec.relationships[0], 'zzz'));
+ assert.strictEqual(manyToMany.name, manyToManySchemaName(spec.relationships[1], 'zzz'));
+});
+
+test('#559 planFor attaches keys to the probeable artifact classes', () => {
+ const spec = {
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'App' },
+ entities: [{ schemaName: 'new_t', displayName: 'T', pluralName: 'Ts', primaryAttribute: { schemaName: 'new_name', displayName: 'N' }, columns: [{ schemaName: 'new_c', displayName: 'C', type: 'Text' }] }],
+ relationships: [],
+ views: [{ entity: 'new_t', name: 'Open', columns: ['new_name'] }],
+ charts: [{ entity: 'new_t', name: 'By', chartType: 'Column', groupBy: 'new_c', aggregate: 'count' }],
+ forms: [{ entity: 'new_t', formType: 'Main' }],
+ };
+ const plan = planFor(spec, { sampleData: false, publish: false, phases: undefined });
+ const kindOf = (frag) => (plan.find((p) => p.label.includes(frag)) || {}).key;
+ assert.strictEqual(kindOf('table new_t').kind, 'table');
+ assert.strictEqual(kindOf('column new_t.new_c').kind, 'column');
+ assert.strictEqual(kindOf('view "Open"').kind, 'view');
+ assert.strictEqual(kindOf('chart "By"').kind, 'chart');
+ assert.strictEqual(kindOf('form for new_t').kind, 'form');
+ assert.strictEqual(kindOf('app module').kind, 'app');
+});
+
+// The dry run must decide localization the way the APPLY path decides it: per entity. Two defects
+// are pinned here at once.
+//
+// 1) The flag was read via `typeof localizedLabelLcidsInSpec === 'function'` on an identifier that
+// was never imported (it lives in entity-provision.js, not app-spec.js). `typeof` on an
+// undeclared name is legal and yields 'undefined', so the guard silently evaluated to false on
+// every run and the fail-closed path was unreachable.
+// 2) It was computed once for the WHOLE spec. A single localized table anywhere would then force
+// every plain-label table down the fail-closed path, and the plan would contradict the apply.
+//
+// Localizing a label changes what an INCONCLUSIVE narrow read may do: for a plain-label table the
+// broad `findTables` read may resolve it (the apply reuses the table, nothing is poisoned), but for
+// a localized one that read is what makes Dataverse keep only the base-language label, so it is
+// refused and the answer stays unknown.
+test('#559 localization is per ENTITY, not per spec, when an existence probe is inconclusive', async () => {
+ const spec = {
+ entities: [
+ { schemaName: 'new_loc', displayName: { 1033: 'Localized', 3082: 'Localizada' }, columns: [] },
+ { schemaName: 'new_plain', displayName: 'Plain', columns: [] },
+ ],
+ };
+ // Both narrow reads are inconclusive (500). Both tables DO exist, so findTables can prove it.
+ const reads = [];
+ const provision = {
+ dataverse: { get: async () => ({ status: 500, body: {} }) },
+ findTables: async (q) => { reads.push(`findTables:${q}`); return [{ logicalName: String(q).toLowerCase(), entitySetName: `${String(q).toLowerCase()}s` }]; },
+ queryRecords: async () => [],
+ };
+ const plan = [
+ { phase: 'data-model', label: 'table new_loc', key: { kind: 'table', entity: 'new_loc' } },
+ { phase: 'data-model', label: 'table new_plain', key: { kind: 'table', entity: 'new_plain' } },
+ ];
+ await annotateLivePlan(plan, { spec, provision });
+
+ assert.strictEqual(stateOf(plan, 'new_plain'), 'reuse',
+ 'a plain-label table may be resolved by the broad read, exactly as the apply path resolves it');
+ assert.strictEqual(stateOf(plan, 'new_loc'), 'unknown',
+ 'a localized table must NOT be resolved by the broad read — that read is what drops the translations');
+
+ // The state is the symptom; the SAFETY property is that the poisoning read never goes on the
+ // wire. Asserting only the state would pass a change that takes the broad read and then reports
+ // unknown anyway — by which point Dataverse has already been told to keep one language.
+ assert.ok(!reads.includes('findTables:new_loc'),
+ `the broad read must never be issued for a localized table: ${JSON.stringify(reads)}`);
+ assert.ok(reads.includes('findTables:new_plain'),
+ 'the plain-label table SHOULD still use the fallback — otherwise this test would pass by doing nothing');
+});
+
+// The complement: with NO localized labels anywhere, nothing is forced into unknown.
+test('#559 a spec with no localized labels resolves inconclusive probes through the broad read', async () => {
+ const spec = { entities: [{ schemaName: 'new_plain', displayName: 'Plain', columns: [] }] };
+ const provision = {
+ dataverse: { get: async () => ({ status: 500, body: {} }) },
+ findTables: async (q) => [{ logicalName: String(q).toLowerCase(), entitySetName: `${String(q).toLowerCase()}s` }],
+ queryRecords: async () => [],
+ };
+ const plan = [{ phase: 'data-model', label: 'table new_plain', key: { kind: 'table', entity: 'new_plain' } }];
+ await annotateLivePlan(plan, { spec, provision });
+ assert.strictEqual(stateOf(plan, 'new_plain'), 'reuse');
+});
+
+// An inconclusive TABLE probe makes everything on that table unknowable too. Without this, the plan
+// contradicts itself in adjacent lines — `? unknown` for the table and a confident `+ create` for
+// every view and form on it — and the apply never reaches them: findExistingTable raises BuildHalt
+// for exactly this state, outside any runner.run, so the build aborts in `data-model`.
+//
+// The form arm is the one that hides best: resolveExistingFormId deliberately swallows the
+// MetadataCache 400 and returns null, and `!!null` is a confident "absent".
+test('#559 a view/chart/form on a table whose probe was INCONCLUSIVE is unknown, not create', async () => {
+ const spec = { entities: [{ schemaName: 'new_loc', displayName: { 1033: 'Localized', 3082: 'Localizada' }, columns: [] }] };
+ const artifactReads = [];
+ const provision = {
+ dataverse: { get: async () => ({ status: 500, body: {} }) },
+ findTables: async () => [{ logicalName: 'new_loc', entitySetName: 'new_locs' }],
+ // Deliberately answer ABSENT rather than throwing. A throw is caught by annotateLivePlan's own
+ // handler and also produces 'unknown', so a throwing double would make this test pass with or
+ // without the guard under test — it has to be able to produce the WRONG answer ('create').
+ queryRecords: async (set, o) => { artifactReads.push(`${set}:${(o && o.filter) || ''}`); return []; },
+ findArtifact: async (kind, q) => { artifactReads.push(`findArtifact:${kind}:${q && q.name}`); return null; },
+ };
+ const plan = [
+ { phase: 'data-model', label: 'table new_loc', key: { kind: 'table', entity: 'new_loc' } },
+ { phase: 'views', label: 'view "V" for new_loc', key: { kind: 'view', entity: 'new_loc', name: 'V' } },
+ { phase: 'forms', label: 'form for new_loc', key: { kind: 'form', entity: 'new_loc', name: 'F', formType: 'Main' } },
+ ];
+ await annotateLivePlan(plan, { spec, provision });
+
+ assert.strictEqual(stateOf(plan, 'table new_loc'), 'unknown');
+ assert.strictEqual(stateOf(plan, 'view "V"'), 'unknown', 'a view on an unknown table cannot be a confident create');
+ assert.strictEqual(stateOf(plan, 'form for new_loc'), 'unknown', 'a form on an unknown table cannot be a confident create');
+ assert.deepStrictEqual(artifactReads, [],
+ `no artifact read should be issued for a table whose own probe was inconclusive: ${JSON.stringify(artifactReads)}`);
+});
+
+// The same arm must keep answering from the table when the table is genuinely ABSENT — that is a
+// real create, and the fix above must not turn it into unknown.
+test('#559 a view/form on a table that is genuinely absent stays create', async () => {
+ const spec = { entities: [{ schemaName: 'new_gone', displayName: 'Gone', columns: [] }] };
+ const provision = {
+ dataverse: { get: async () => ({ status: 404, body: {} }) },
+ findTables: async () => [],
+ queryRecords: async () => { throw new Error('must not query artifacts for a missing table'); },
+ };
+ const plan = [
+ { phase: 'data-model', label: 'table new_gone', key: { kind: 'table', entity: 'new_gone' } },
+ { phase: 'views', label: 'view "V" for new_gone', key: { kind: 'view', entity: 'new_gone', name: 'V' } },
+ { phase: 'forms', label: 'form for new_gone', key: { kind: 'form', entity: 'new_gone', name: 'F', formType: 'Main' } },
+ ];
+ await annotateLivePlan(plan, { spec, provision });
+ assert.strictEqual(stateOf(plan, 'table new_gone'), 'create');
+ assert.strictEqual(stateOf(plan, 'view "V"'), 'create');
+ assert.strictEqual(stateOf(plan, 'form for new_gone'), 'create');
+});
+
+// The halt text is a ~390-character remediation paragraph. It belongs on the table's own line, once
+// — not copied onto every column/view/form of that table, which for a 20-column table would emit
+// kilobytes of identical prose into the plan output.
+test('#559 the long halt reason is printed on the table line only; dependents get a short one', async () => {
+ const spec = { entities: [{ schemaName: 'new_loc', displayName: { 1033: 'Localized', 3082: 'Localizada' }, columns: [] }] };
+ const provision = {
+ dataverse: { get: async () => ({ status: 500, body: {} }) },
+ findTables: async () => [{ logicalName: 'new_loc', entitySetName: 'new_locs' }],
+ queryRecords: async () => [],
+ };
+ const plan = [
+ { phase: 'data-model', label: 'table new_loc', key: { kind: 'table', entity: 'new_loc' } },
+ { phase: 'data-model', label: 'column new_loc.new_a', key: { kind: 'column', entity: 'new_loc', name: 'new_a' } },
+ { phase: 'views', label: 'view "V" for new_loc', key: { kind: 'view', entity: 'new_loc', name: 'V' } },
+ ];
+ await annotateLivePlan(plan, { spec, provision });
+
+ const why = (frag) => (plan.find((p) => p.label.includes(frag)) || {}).stateWhy || '';
+ assert.ok(why('table new_loc').length > 100, 'the table line keeps the actionable halt text');
+ assert.ok(why('column new_loc.new_a').length < 100, `a column must not repeat it: ${why('column new_loc.new_a')}`);
+ assert.ok(why('view "V"').length < 100, `a view must not repeat it: ${why('view "V"')}`);
+ assert.ok(why('column new_loc.new_a').length > 0 && why('view "V"').length > 0, 'but they still say WHY they are unknown');
+});
diff --git a/plugins/model-apps/scripts/tests/provision-solution.test.js b/plugins/model-apps/scripts/tests/provision-solution.test.js
index a9fa8f55a..283098f93 100644
--- a/plugins/model-apps/scripts/tests/provision-solution.test.js
+++ b/plugins/model-apps/scripts/tests/provision-solution.test.js
@@ -271,3 +271,120 @@ test('runProvisionSolution: valid uniqueName with underscores', async () => {
assert.equal(result.ok, true);
assert.equal(result.uniqueName, 'Good_Name_123');
});
+
+// --- CLI main(): temp-workspace lifecycle -----------------------------------
+//
+// main() creates a throwaway SDK workspace with mkdtempSync. The SDK is only needed for its
+// Dataverse client here — the workspace persists nothing — so it MUST be removed on every exit
+// path. A leak is invisible per-run and only shows up as an ever-growing temp directory, which is
+// exactly the kind of bug a test has to pin because nobody notices it manually.
+
+const path = require('node:path');
+const { loadCli } = require('./helpers/cli-harness.js');
+
+const scriptPath = path.join(__dirname, '..', 'provision-solution.js');
+const ENVU = 'https://contoso.crm.dynamics.com';
+
+function solutionHarness({ argv, sdkFactoryThrows = null, initThrows = null, rmThrows = null, createSolution } = {}) {
+ const fsCalls = [];
+ const real = require('../lib/dataverse-auth.js');
+ const emitted = [];
+ const cli = loadCli(scriptPath, {
+ argv: argv || [ENVU, 'my_solution', 'My Solution'],
+ requires: {
+ fs: {
+ mkdtempSync: (p) => { fsCalls.push({ op: 'mkdtemp', p }); return p + 'XXXX'; },
+ rmSync: (p, o) => {
+ fsCalls.push({ op: 'rm', p, o });
+ if (rmThrows) throw new Error(rmThrows);
+ },
+ },
+ './lib/dataverse-auth': {
+ parseArgs: real.parseArgs,
+ validateFlags: real.validateFlags,
+ emitResult: (ok, payload) => { emitted.push({ ok, payload }); },
+ },
+ './lib/sdk-http-client': { createAzHttpClient: () => ({}) },
+ './vendor/cds-maker-sdk.cjs': {
+ createMakerSdk: () => {
+ if (sdkFactoryThrows) throw new Error(sdkFactoryThrows);
+ return {
+ initWorkspace: () => { if (initThrows) throw new Error(initThrows); },
+ queryRecords: async (entity) => (entity === 'publisher'
+ ? [{ publisherid: 'pub-1', uniquename: 'contoso', customizationprefix: 'new' }]
+ : []),
+ createSolution: createSolution || (async () => ({ id: 'sol-1' })),
+ };
+ },
+ },
+ },
+ });
+ return { cli, fsCalls, emitted };
+}
+
+test('main removes the throwaway workspace after a successful provision', async () => {
+ const h = solutionHarness({});
+ await h.cli.main();
+ const made = h.fsCalls.find((c) => c.op === 'mkdtemp');
+ const removed = h.fsCalls.find((c) => c.op === 'rm');
+ assert.ok(made, 'a temp workspace is created');
+ assert.ok(removed, 'and removed');
+ assert.equal(removed.p, made.p + 'XXXX', 'the SAME directory mkdtempSync returned is removed');
+ assert.deepEqual(removed.o, { recursive: true, force: true });
+ assert.equal(h.emitted[0].ok, true);
+});
+
+test('main removes the workspace even when SDK CONSTRUCTION throws', async () => {
+ // The documented hazard: a failing constructor happens after mkdtempSync, so construction must
+ // sit inside the try or the directory leaks.
+ const h = solutionHarness({ sdkFactoryThrows: 'bundle missing' });
+ await h.cli.main();
+ assert.ok(h.fsCalls.some((c) => c.op === 'rm'), 'workspace removed despite the constructor throwing');
+ assert.equal(h.emitted[0].ok, false);
+ assert.match(String(h.emitted[0].payload.message), /bundle missing/);
+});
+
+test('main removes the workspace even when initWorkspace throws', async () => {
+ const h = solutionHarness({ initThrows: 'workspace init failed' });
+ await h.cli.main();
+ assert.ok(h.fsCalls.some((c) => c.op === 'rm'));
+ assert.equal(h.emitted[0].ok, false);
+ assert.match(String(h.emitted[0].payload.message), /workspace init failed/);
+});
+
+test('a cleanup failure does not mask the real provisioning error', async () => {
+ // Windows can hold a transient handle on the temp dir; losing the Dataverse error behind an
+ // EBUSY would leave the operator with nothing actionable.
+ const h = solutionHarness({ sdkFactoryThrows: 'real failure', rmThrows: 'EBUSY' });
+ await h.cli.main();
+ assert.equal(h.emitted[0].ok, false);
+ assert.match(String(h.emitted[0].payload.message), /real failure/);
+ assert.doesNotMatch(String(h.emitted[0].payload.message), /EBUSY/);
+});
+
+test('a cleanup failure does not turn a SUCCESSFUL provision into a failure', async () => {
+ const h = solutionHarness({ rmThrows: 'EBUSY' });
+ await h.cli.main();
+ assert.equal(h.emitted[0].ok, true, 'the solution was created; a temp-dir handle must not undo that');
+ assert.equal(h.emitted[0].payload.solutionId, 'sol-1');
+});
+
+test('optional flags are forwarded to the solution record', async () => {
+ let seen = null;
+ const h = solutionHarness({
+ argv: [ENVU, 'my_solution', 'My Solution', '--description', 'D', '--version', '2.0.0.0', '--publisher', 'contoso'],
+ createSolution: async (args) => { seen = args; return { id: 'sol-2' }; },
+ });
+ await h.cli.main();
+ assert.equal(seen.description, 'D');
+ assert.equal(seen.version, '2.0.0.0');
+ assert.equal(seen.publisherId, 'pub-1');
+});
+
+test('an omitted --version defaults to 1.0.0.0 and description is generated', async () => {
+ let seen = null;
+ const h = solutionHarness({ createSolution: async (args) => { seen = args; return { id: 'sol-3' }; } });
+ await h.cli.main();
+ assert.equal(seen.version, '1.0.0.0');
+ assert.match(seen.description, /My Solution/);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.js
index 3d679f16d..e0656f70f 100644
--- a/plugins/model-apps/scripts/tests/run-tests.test.js
+++ b/plugins/model-apps/scripts/tests/run-tests.test.js
@@ -22,6 +22,28 @@ test('pluginTestFiles covers the real tests directory (all 18+ suites)', () => {
assert.ok(files.every((f) => f.endsWith('.test.js')));
});
+// Discovery used to be a FLAT readdir, so a test file in `scripts/tests/<subdir>/` was committed,
+// reviewed, reported green — and never executed. Nothing downstream notices, because the runner
+// reports success over the files it did find. Every suite happens to be top-level today, which is
+// exactly why this needs a test rather than an observation.
+test('pluginTestFiles descends into subdirectories (a nested suite must not be silently skipped)', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'runtests-nested-'));
+ fs.mkdirSync(path.join(dir, 'sub', 'deeper'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'top.test.js'), '');
+ fs.writeFileSync(path.join(dir, 'sub', 'mid.test.js'), '');
+ fs.writeFileSync(path.join(dir, 'sub', 'deeper', 'low.test.js'), '');
+ fs.writeFileSync(path.join(dir, 'sub', 'fixture.js'), ''); // not a test
+ fs.mkdirSync(path.join(dir, 'helpers'));
+ fs.writeFileSync(path.join(dir, 'helpers', 'mock.js'), ''); // helpers hold fixtures, not tests
+ const files = pluginTestFiles(dir);
+ assert.deepStrictEqual(files, [
+ path.join('scripts', 'tests', 'sub', 'deeper', 'low.test.js'),
+ path.join('scripts', 'tests', 'sub', 'mid.test.js'),
+ path.join('scripts', 'tests', 'top.test.js'),
+ ]);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
test('sdkTestSpec resolves the package dir and reports presence', () => {
const spec = sdkTestSpec('D:/nope', 'D:/also-nope');
assert.ok(spec.pkgDir.endsWith(path.join('packages', 'cds-maker-sdk')));
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index e3376c09b..f8ed0761e 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -352,14 +352,72 @@ const cellsFromAdd = (v) => {
return [];
};
+// Every mutating SDK call the engine can make. A dry run must issue NONE of them — but it now does
+// issue READS (#559), so "wrote nothing" can no longer be spelled `calls.length === 0`.
+const MUTATING_CALLS = new Set([
+ 'createPublisher', 'createSolution', 'createTable', 'updateTable', 'createColumn', 'createRelationship',
+ 'createGlobalOptionSet', 'createCustomerColumn', 'insertStatusValue', 'createAlternateKey',
+ 'createRecordsBulk', 'seedRecordGraph', 'enrichDefaultViews', 'createArtifact', 'createWebResource',
+ 'pushArtifact', 'publishArtifact', 'addElement', 'updateElement', 'removeElement', 'updateRecord',
+ 'addSolutionComponent', 'associateRecords', 'disassociateRecords', 'deleteAppCascade',
+ 'setColumnVisualization', 'setAppAiFeatures', 'configureRowSummary', 'createSecurityRole',
+ 'createPersonaRole', 'addEntityPrivilegesToRole', 'deleteSecurityRole',
+]);
+
test('dry-run emits a plan and writes nothing', async () => {
const { sdk, calls } = mockSdk();
const events = [];
const r = await runSdkBuild(makeSpec(), { sdk, apply: false, sampleData: true, publish: true, emit: (e) => events.push(e) });
assert.strictEqual(r.dryRun, true);
- assert.strictEqual(calls.length, 0);
+ const wrote = calls.filter((c) => MUTATING_CALLS.has(c.name));
+ assert.deepStrictEqual(wrote.map((c) => c.name), [], 'a dry run must not mutate the environment');
assert.ok(r.plan.some((l) => l.includes('solution ContosoSD')));
- assert.ok(events.every((e) => e.status === 'skip'));
+ assert.ok(events.every((e) => e.status === 'skip' || e.status === 'warn'));
+});
+
+// #559: the dry run used to print planFor's static listing and exit before any discovery, so the
+// SAME plan appeared for a spec whose artifacts all exist and for one that would create everything.
+test('#559 dry-run resolves create vs reuse against the live environment', async () => {
+ // new_customer exists and already has new_tier; new_ticket does not exist at all.
+ const { sdk } = mockSdk({ existingTables: { new_customer: { entitySetName: 'new_customers', columns: ['new_name', 'new_tier'] } } });
+ const r = await runSdkBuild(makeSpec(), { sdk, apply: false, emit: () => {} });
+ assert.strictEqual(r.livePlan, true, 'the plan was resolved live');
+ const find = (frag) => r.planItems.find((p) => p.label.includes(frag));
+
+ assert.strictEqual(find('table new_customer').state, 'reuse', 'an existing table reads as reuse');
+ assert.strictEqual(find('table new_ticket').state, 'create', 'a missing table reads as create');
+ assert.strictEqual(find('column new_customer.new_tier').state, 'reuse', 'an existing column reads as reuse');
+ // A column on a table that does not exist is unambiguously a create, with no metadata read needed.
+ assert.strictEqual(find('column new_ticket.new_priority').state, 'create');
+ // The distinction the issue is about: the two tables must NOT report the same thing.
+ assert.notStrictEqual(find('table new_customer').state, find('table new_ticket').state);
+});
+
+test('#559 the plan labels carry the state so a printed plan is readable', async () => {
+ const { sdk } = mockSdk({ existingTables: { new_customer: { entitySetName: 'new_customers', columns: ['new_name'] } } });
+ const r = await runSdkBuild(makeSpec(), { sdk, apply: false, emit: () => {} });
+ assert.ok(r.plan.some((l) => /table new_customer .*\[reuse\]/.test(l)), JSON.stringify(r.plan.slice(0, 6)));
+ assert.ok(r.plan.some((l) => /table new_ticket .*\[create\]/.test(l)), JSON.stringify(r.plan.slice(0, 6)));
+});
+
+test('#559 livePlan:false keeps the offline, spec-only listing', async () => {
+ const { sdk, calls } = mockSdk();
+ const r = await runSdkBuild(makeSpec(), { sdk, apply: false, livePlan: false, emit: () => {} });
+ assert.strictEqual(r.livePlan, false);
+ assert.ok(r.plan.every((l) => !/\[(create|reuse|unknown)\]/.test(l)), 'no states without a live probe');
+ assert.deepStrictEqual(calls.map((c) => c.name), [], 'and no calls of any kind');
+});
+
+// A read that FAILS must not be reported as either create or reuse: guessing "create" overstates the
+// work and "reuse" understates it, and both read as certainty the run does not have.
+test('#559 a failed probe reports unknown, never a guess', async () => {
+ const { sdk } = mockSdk();
+ sdk.findTables = async () => { throw new Error('metadata service unavailable'); };
+ sdk.dataverse = { get: async () => { throw new Error('metadata service unavailable'); } };
+ const r = await runSdkBuild(makeSpec(), { sdk, apply: false, emit: () => {} });
+ const tbl = r.planItems.find((p) => p.label.includes('table new_customer'));
+ assert.strictEqual(tbl.state, 'unknown');
+ assert.match(tbl.stateWhy, /metadata service unavailable/);
});
test('fresh build runs phases in order and creates everything', async () => {
@@ -636,6 +694,68 @@ test('Tier 2: planFor and totals account for web resources and event wiring', as
assert.ok(onlyWr.length && onlyWr.every((p) => p === 'web-resources'));
});
+test('apply progress total includes existing-column reconciliation steps', async () => {
+ const spec = makeSpec();
+ spec.entities[0].columns[0].required = true;
+ spec.entities[0].columns.push({
+ schemaName: 'new_score',
+ displayName: 'Score',
+ type: 'Integer',
+ visualization: 'StarRating',
+ });
+ const { sdk } = mockSdk({
+ existingTables: {
+ new_customer: {
+ entitySetName: 'new_customers',
+ columns: ['new_name', 'new_tier', 'new_score'],
+ relationships: ['new_customer_new_ticket'],
+ },
+ new_ticket: {
+ entitySetName: 'new_tickets',
+ columns: ['new_subject', 'new_priority'],
+ },
+ },
+ });
+ sdk.setColumnVisualization = async () => ({});
+ const events = [];
+
+ await runSdkBuild(spec, { sdk, apply: true, phases: ['data-model'], emit: (event) => events.push(event) });
+
+ const terminal = events.filter((event) => ['ok', 'skip', 'error'].includes(event.status));
+ assert.ok(terminal.length > 0);
+ assert.ok(terminal.every((event) => event.n <= event.total), 'a step index must never exceed its advertised total');
+ assert.equal(terminal.at(-1).n, terminal.at(-1).total, 'the final step index must equal the advertised total');
+});
+
+// Live-reproduced on a real environment: a page-LESS spec rebuilt against an app that already
+// exists ran `finalize sitemap (genpage subareas)` and overran its own denominator ([37/36]).
+// The runtime finalizes whenever `appHasPageSubareas(spec) || appWasExisting`, but the plan only
+// counted the step when the SPEC had page subareas — so the `appWasExisting` branch, which is a
+// live fact planFor cannot see, was never budgeted for. Same family as the [75/62] overrun, and
+// invisible on a create run because that path ends exactly on total.
+test('apply progress total covers the existing-app sitemap finalize on a page-less spec', async () => {
+ const spec = makeSpec();
+ assert.equal((spec.pages || []).length, 0, 'this case is specifically the page-LESS spec');
+ const { sdk } = mockSdk({ artifactsExist: true }); // findArtifact('app') -> existing, so appWasExisting
+ const events = [];
+
+ await runSdkBuild(spec, {
+ sdk,
+ apply: true,
+ phases: ['app-shell', 'pages'],
+ genpageCli: { enumerateEnv: async () => ({ ok: true, ids: [] }) },
+ emit: (event) => events.push(event),
+ });
+
+ const terminal = events.filter((event) => ['ok', 'skip', 'error'].includes(event.status));
+ assert.ok(terminal.length > 0);
+ assert.ok(
+ terminal.every((event) => event.n <= event.total),
+ `a step index must never exceed its advertised total: ${terminal.map((e) => `${e.n}/${e.total} ${e.label}`).join(' | ')}`
+ );
+ assert.equal(terminal.at(-1).n, terminal.at(-1).total, 'the final step index must equal the advertised total');
+});
+
// --- Tier 2.x: SDK fix uptake (AutoNumber primary, N:N sub-grids) + folded build steps ----
test('AutoNumber primary column flows to createTable.primaryColumnAutoNumberFormat', async () => {
const spec = makeSpec();
diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
index d8b548dbb..cda36463a 100644
--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
@@ -228,6 +228,65 @@ test('plan is ordered app -> dashboards -> commands -> forms -> charts -> views
assert.deepStrictEqual(kinds, ['app', 'genpage', 'dashboard', 'commands', 'form', 'form', 'form', 'chart', 'chart', 'view', 'view', 'view', 'resetDefaultViews', 'resetDefaultViews', 'relationship', 'relationship', 'table', 'table', 'table', 'webResource', 'webResource', 'webResource', 'solution']);
});
+// Regression (found by LIVE teardown of a self-referencing hierarchy): a 1:N whose referenced and
+// referencing tables are the SAME table is removed by the table delete. Deleting it on its own first
+// fails — its lookup sits on the same table that hosts the form still referencing it — so teardown
+// printed `✗ relationship … referenced by 2 other components` and exited NON-ZERO on a run that then
+// deleted the table and left the environment completely clean. Self-referencing hierarchies became a
+// mainstream shape once sample data could seed them (#544), so this cry-wolf is now routine.
+test('#544 a SELF-referencing relationship is deleted AFTER its table, not before', () => {
+ const spec = {
+ solution: { uniqueName: 'HierSln', publisherPrefix: 'new' },
+ app: { name: 'Hier App' },
+ entities: [{ schemaName: 'new_org', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],
+ relationships: [{ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_ParentOrgId' } }],
+ appShell: { areas: [{ label: 'A', groups: [{ label: 'G', subAreas: [{ entity: 'new_org' }] }] }] },
+ };
+ const steps = planTeardown(spec);
+ const kinds = steps.map((s) => s.kind);
+ const relIdx = kinds.indexOf('relationship');
+ const tblIdx = kinds.indexOf('table');
+ assert.ok(relIdx !== -1, 'it is still planned — deferring, not skipping, is what keeps it safe');
+ assert.ok(tblIdx !== -1 && tblIdx < relIdx, 'the table delete (which cascades it) comes first');
+});
+
+// If the table is RETAINED, the deferred delete is what stops the relationship leaking. The spec
+// cannot tell a retained table from a deleted one (live discovery also skips non-custom tables),
+// which is why this is an ordering change rather than a skip.
+test('#544 a self-referencing relationship on an EXISTING (retained) table is still planned', () => {
+ const spec = {
+ solution: { uniqueName: 'HierSln', publisherPrefix: 'new' },
+ app: { name: 'Hier App' },
+ entities: [{ schemaName: 'new_org', primaryAttribute: { schemaName: 'new_name' }, columns: [], existing: true }],
+ relationships: [{ type: 'OneToMany', referenced: 'new_org', referencing: 'new_org', lookup: { schemaName: 'new_ParentOrgId' } }],
+ appShell: { areas: [{ label: 'A', groups: [{ label: 'G', subAreas: [{ entity: 'new_org' }] }] }] },
+ };
+ assert.strictEqual(planTeardown(spec).filter((s) => s.kind === 'relationship').length, 1);
+});
+
+// The `relationship` kind already tolerates not-found, which is what makes the deferral safe when
+// the table delete cascaded it away. Asserting it here so a future change to that flag is caught.
+test('#544 the relationship kind tolerates not-found (what makes the deferral safe)', () => {
+ assert.strictEqual(KIND_HANDLERS.relationship.tolerateNotFound, true);
+});
+
+// And a normal two-table relationship is untouched by the narrowing — still BEFORE the tables.
+test('#544 a relationship between two DIFFERENT tables is still planned before the tables', () => {
+ const spec = {
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'A' },
+ entities: [
+ { schemaName: 'new_parent', primaryAttribute: { schemaName: 'new_name' }, columns: [] },
+ { schemaName: 'new_child', primaryAttribute: { schemaName: 'new_name' }, columns: [] },
+ ],
+ relationships: [{ type: 'OneToMany', referenced: 'new_parent', referencing: 'new_child', lookup: { schemaName: 'new_ParentId' } }],
+ appShell: { areas: [{ label: 'A', groups: [{ label: 'G', subAreas: [{ entity: 'new_parent' }] }] }] },
+ };
+ const kinds = planTeardown(spec).map((s) => s.kind);
+ assert.strictEqual(kinds.filter((k) => k === 'relationship').length, 1);
+ assert.ok(kinds.indexOf('relationship') < kinds.indexOf('table'), 'unchanged ordering for a two-table relationship');
+});
+
// Regression (found by live teardown): a table's icon web resource is referenced by the table, so
// it must be planned AFTER the table; and the build's generated default app icon web resource must
// be cleaned up or it leaks as an orphan the spec never declared.
@@ -381,6 +440,71 @@ test('deleteStep does NOT swallow a dependency block ("referenced by N component
);
});
+// A blocked relationship delete must name what is holding it. Dataverse returns only a COUNT, which
+// is a dead end on the retained-table path (`existing: true`), where the blocker is typically a form
+// the build authored but the CURRENT spec no longer declares — so teardown cannot plan its deletion.
+function dependencyBlockSdk({ dataverse } = {}) {
+ return {
+ deleteRelationship: async () => {
+ const e = new Error('The EntityRelationship(cc5fe264-1fb1-f111-aaad-70a8a59c16bf) component cannot be deleted because it is referenced by 2 other components. For a list of referenced components, use the RetrieveDependenciesForDeleteRequest.');
+ e.statusCode = 400;
+ throw e;
+ },
+ ...(dataverse ? { dataverse } : {}),
+ };
+}
+
+test('a dependency-blocked relationship names the blocking components instead of just a count', async () => {
+ // Mirrors the live shapes: RelationshipDefinitions resolves the MetadataId, the dependency read
+ // returns componenttype 60 (SystemForm), and the form's name comes from `systemforms`.
+ const seen = [];
+ const dataverse = {
+ get: async (p) => {
+ seen.push(p);
+ if (p.startsWith('/RelationshipDefinitions')) return { status: 200, body: { value: [{ MetadataId: 'cc5fe264-1fb1-f111-aaad-70a8a59c16bf' }] } };
+ if (p.startsWith('/RetrieveDependenciesForDelete')) return { status: 200, body: { value: [{ dependentcomponenttype: 60, dependentcomponentobjectid: '5bebe418-1cbd-47c9-91b3-c5a3a31edcb2' }] } };
+ if (p.startsWith('/systemforms(')) return { status: 200, body: { name: 'Self Ref Acct Form' } };
+ return { status: 404, body: null };
+ },
+ };
+ await assert.rejects(
+ () => deleteStep(dependencyBlockSdk({ dataverse }), KIND_HANDLERS.relationship, [{ id: 'pp668_account_account', schemaName: 'pp668_account_account' }]),
+ (err) => {
+ assert.match(err.message, /referenced by 2 other components/, 'keeps the platform text so isDependencyBlocked still matches');
+ assert.match(err.message, /Still referenced by: form "Self Ref Acct Form" \(5bebe418-1cbd-47c9-91b3-c5a3a31edcb2\)/);
+ assert.match(err.message, /re-run teardown/, 'tells the operator what to do next');
+ return true;
+ }
+ );
+ assert.ok(seen.some((p) => p.includes("SchemaName eq 'pp668_account_account'")), 'resolves the relationship by schema name');
+ assert.ok(seen.some((p) => p.includes('ComponentType=10')), 'asks for EntityRelationship dependencies');
+});
+
+test('the dependency diagnostic is fail-quiet: without a raw client the platform error is unchanged', async () => {
+ // Diagnostics layered on an already-failing delete must never replace a real error with a worse
+ // one, so an SDK with no `dataverse` (older callers, unit-test doubles) rethrows verbatim.
+ await assert.rejects(
+ () => deleteStep(dependencyBlockSdk(), KIND_HANDLERS.relationship, [{ id: 'r1', schemaName: 'r1' }]),
+ (err) => {
+ assert.match(err.message, /referenced by 2 other components/);
+ assert.ok(!/Still referenced by/.test(err.message), 'no half-built diagnostic is appended');
+ return true;
+ }
+ );
+});
+
+test('the dependency diagnostic falls back to the raw error when the dependency read fails', async () => {
+ const dataverse = { get: async () => { throw new Error('metadata read unavailable'); } };
+ await assert.rejects(
+ () => deleteStep(dependencyBlockSdk({ dataverse }), KIND_HANDLERS.relationship, [{ id: 'r1', schemaName: 'r1' }]),
+ (err) => {
+ assert.match(err.message, /referenced by 2 other components/);
+ assert.ok(!/metadata read unavailable/.test(err.message), 'the diagnostic failure never masks the real one');
+ return true;
+ }
+ );
+});
+
test('KIND_HANDLERS.form resolve is type-scoped so teardown never deletes a same-named sibling of another type', async () => {
const queries = [];
const sdk = {
diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
index 7ae065a9d..f6c63ddaf 100644
--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
@@ -8,6 +8,7 @@ const path = require('node:path');
const fs = require('node:fs');
const vm = require('node:vm');
const { teardownModelApp, cliEmit } = require(path.join(__dirname, '..', 'teardown-model-app.js'));
+const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');
const desk = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json'), 'utf8'));
@@ -248,6 +249,7 @@ function loadTeardownCli({
if (id === './lib/dataverse-auth.js') {
return {
parseArgs: () => parseResult,
+ validateFlags: validateFlagsFromParsed(() => parseResult.flags),
readJsonArg: (arg) => {
events.push({ type: 'readJsonArg', arg });
return { app: { name: 'Support Desk' }, solution: { publisherPrefix: 'new' } };
diff --git a/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js b/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js
new file mode 100644
index 000000000..f6431c3e0
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/unattended-skill-contract.test.js
@@ -0,0 +1,80 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8');
+
+test('app-builder and genpage both define unattended authoring behavior', () => {
+ for (const [name, text] of [
+ ['app-builder', read('skills', 'app-builder', 'SKILL.md')],
+ ['genpage', read('skills', 'genpage', 'SKILL.md')],
+ ]) {
+ assert.match(text, /resolve-interaction-mode\.js/, `${name} must resolve attended vs unattended once`);
+ assert.match(text, /POWER_PLATFORM_SKILLS_NONINTERACTIVE/, `${name} must honor the shared automation switch`);
+ assert.match(text, /do not call `AskUserQuestion`|do not call AskUserQuestion/i, `${name} must suppress questions when unattended`);
+ // Anchored to the unattended *decision*. A loose /plan.*approved/ also matches the ATTENDED
+ // gate ("the build plan was already presented and approved"), so it passed before this rule
+ // existed and asserted nothing. `\s+` rather than literal spaces: the phrase sits mid-paragraph
+ // on hard-wrapped prose, so a pure re-wrap must not break CI.
+ assert.match(text, /treat\s+the\s+plan\s+as\s+approved|as\s+the\s+approved\s+plan/i, `${name} must define unattended plan approval`);
+ assert.match(text, /does not authorize destructive|never authorizes destructive/i, `${name} must keep destructive authority separate`);
+ }
+ const appBuilder = read('skills', 'app-builder', 'SKILL.md');
+ // The general destructive-authority assertion above is satisfied by pre-existing prose, so
+ // assert the concrete new rule: suppression does not grant `--allow-destructive`.
+ assert.match(
+ appBuilder,
+ /still\s+requires\s+`--allow-destructive`/i,
+ 'unattended apply must still require explicit destructive authority',
+ );
+ assert.match(appBuilder, /append[\s\S]*`--non-interactive` to every `build-model-app\.js` invocation/i);
+ assert.match(appBuilder, /resolve-interaction-mode\.js" \[--non-interactive\]/);
+});
+
+test('genpage planner prompt delimits binding contracts from upload-file status', () => {
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ assert.match(skill, /BEGIN CONNECTOR BINDINGS[\s\S]*END CONNECTOR BINDINGS/);
+ assert.match(skill, /BEGIN CUSTOM API BINDINGS[\s\S]*END CUSTOM API BINDINGS/);
+ assert.match(skill, /upload file[\s\S]*not part of[\s\S]*section/i);
+ // The delimiters only help if the planner is told they are framing. Without this the prompt
+ // reads "use this as the entire section" over a block whose first/last lines are the
+ // delimiters, and a verbatim copy yields a `missing-connector-table` schema error.
+ for (const kind of ['CONNECTOR BINDINGS', 'CUSTOM API BINDINGS']) {
+ // `[\s>]+` spans the blockquote wrap (`BEGIN/END\n> CONNECTOR BINDINGS`) and `\*{0,2}`
+ // tolerates the bold `Do **not** copy`.
+ assert.match(
+ skill,
+ new RegExp(`BEGIN/END[\\s>]+${kind}[^\\n]*-----[\\s\\S]{0,240}not\\*{0,2} copy them into`, 'i'),
+ `${kind} delimiters must be marked as prompt framing, not plan content`,
+ );
+ }
+ const planner = read('agents', 'genpage-planner.md');
+ assert.match(
+ planner,
+ /prompt\s+delimiters,\s+not\s+content:\s+copy\s+only\s+what\s+is\s+between\s+them/i,
+ 'planner must be told the delimiters are not part of the section body',
+ );
+});
+
+// These two markers are a literal-string contract between a doc in plugins/ and an evaluator in
+// evals/, and nothing else reads them: the eval unit tests use hand-written log strings rather than
+// the doc, and no fixture records an interaction mode, so the unattended branch never executes in
+// the harness. Without these assertions the doc could be reworded and every suite would stay green
+// while the contract silently died. Counterpart: evals/model-apps/genpage/lib/assertions-layer-1.js
+// (`isUnattendedLog`, and the plan-approval check in the EnterPlanMode workflow assertion).
+test('the genpage unattended markers satisfy the evaluator patterns they are pinned to', () => {
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ assert.match(
+ skill,
+ /Unattended default:\s*plan approval\s*→\s*approved\b/i,
+ 'the pinned plan-approval marker must satisfy the evaluator plan-approval pattern',
+ );
+ assert.match(
+ skill,
+ /Unattended default:\s*interaction mode\s*→\s*unattended\b/i,
+ 'the pinned mode marker must start with `Unattended default:` so isUnattendedLog detects it',
+ );
+});
diff --git a/plugins/model-apps/scripts/tests/validate-flags.test.js b/plugins/model-apps/scripts/tests/validate-flags.test.js
new file mode 100644
index 000000000..c824bb748
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/validate-flags.test.js
@@ -0,0 +1,114 @@
+// plugins/model-apps/scripts/tests/validate-flags.test.js
+// Contract for the shared CLI flag validator and the "did you mean" matcher behind it.
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert');
+const { execFileSync } = require('node:child_process');
+const path = require('node:path');
+
+const { validateFlags, parseArgs } = require('../lib/dataverse-auth.js');
+const { nearestName } = require('../lib/nearest-name.js');
+
+const PLUGIN = path.join(__dirname, '..', '..');
+const script = (n) => path.join(PLUGIN, 'scripts', n);
+const SPEC = path.join(PLUGIN, 'samples', 'app-spec.project-tracker.json');
+
+function run(args) {
+ try {
+ const stdout = execFileSync(process.execPath, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ return { code: 0, stdout, stderr: '' };
+ } catch (err) {
+ return { code: err.status, stdout: err.stdout || '', stderr: err.stderr || '' };
+ }
+}
+
+test('validateFlags accepts a declared flag set', () => {
+ assert.strictEqual(validateFlags(['--env', 'https://x', '--apply'], { known: ['env', 'apply'], needValue: ['env'] }), null);
+});
+
+test('validateFlags rejects an unknown flag and names it', () => {
+ const msg = validateFlags(['--nope', 'x'], { known: ['env'], needValue: ['env'] });
+ assert.match(msg, /unknown flag\(s\): --nope/);
+});
+
+test('validateFlags suggests the near miss that caused the swallowed token', () => {
+ // The bug this exists for: `--stagee ui` is silently dropped AND eats `ui`.
+ const msg = validateFlags(['--stagee', 'ui'], { known: ['stage', 'env'], needValue: ['stage'] });
+ assert.match(msg, /did you mean --stage\?/);
+});
+
+test('validateFlags reports an unknown flag BEFORE a value-less one it may have caused', () => {
+ // `--stagee ui --workspace` leaves --workspace looking bare; naming that would hide the typo.
+ const msg = validateFlags(['--stagee', 'ui', '--workspace'], { known: ['stage', 'workspace'], needValue: ['stage', 'workspace'] });
+ assert.match(msg, /unknown flag/);
+ assert.doesNotMatch(msg, /--workspace requires/);
+});
+
+test('validateFlags rejects a bare value-bearing flag', () => {
+ assert.match(validateFlags(['--stage'], { known: ['stage'], needValue: ['stage'] }), /--stage requires a value/);
+});
+
+test('validateFlags rejects --flag= and --flag "" as value-less', () => {
+ assert.match(validateFlags(['--stage='], { known: ['stage'], needValue: ['stage'] }), /--stage requires a value/);
+ assert.match(validateFlags(['--stage', ' '], { known: ['stage'], needValue: ['stage'] }), /--stage requires a value/);
+});
+
+test('validateFlags leaves a bare BOOLEAN flag alone', () => {
+ assert.strictEqual(validateFlags(['--apply'], { known: ['apply'], needValue: [] }), null);
+});
+
+test('validateFlags treats an absent flag as acceptable — requiredness is the CLI\'s call', () => {
+ assert.strictEqual(validateFlags([], { known: ['env'], needValue: ['env'] }), null);
+});
+
+test('validateFlags catches --__proto__, which never becomes an own property of flags', () => {
+ // parseArgs accumulates into a plain {}, so Object.keys() cannot see this one.
+ assert.strictEqual(Object.keys(parseArgs(['--__proto__', 'x']).flags).length, 0);
+ assert.match(validateFlags(['--__proto__', 'x'], { known: ['env'] }), /unknown flag/);
+});
+
+test('validateFlags fails loudly when needValue names a flag missing from known', () => {
+ // Guards the rename-one-list-not-the-other drift that would silently stop enforcing the value.
+ assert.throws(() => validateFlags([], { known: ['env'], needValue: ['stage'] }), /needValue but not in known/);
+});
+
+test('nearestName prefers an exact case-insensitive match over a near one', () => {
+ assert.strictEqual(nearestName('STAGE', ['stage', 'stages']), 'stage');
+});
+
+test('nearestName declines a suggestion beyond a single edit', () => {
+ assert.strictEqual(nearestName('stgee', ['stage']), null);
+});
+
+// --- End-to-end: the dangerous case this whole change exists for -------------------------------
+
+test('build-model-app rejects a typo\'d phase selector instead of planning every phase', () => {
+ const base = ['--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan'];
+ const good = run([script('build-model-app.js'), ...base, '--stage', 'ui']);
+ assert.strictEqual(good.code, 0, good.stderr);
+ const planned = JSON.parse(good.stdout).planItems.length;
+
+ const typo = run([script('build-model-app.js'), ...base, '--stagee', 'ui']);
+ assert.notStrictEqual(typo.code, 0, 'a typo\'d phase selector must not exit 0');
+ assert.match(typo.stderr, /unknown flag\(s\): --stagee \(did you mean --stage\?\)/);
+ // The regression being pinned: before this guard the typo planned strictly MORE than --stage ui.
+ assert.ok(planned > 0 && planned < 9, `--stage ui should plan a subset, planned ${planned}`);
+});
+
+test('teardown-model-app rejects an unknown flag rather than ignoring it', () => {
+ const r = run([script('teardown-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--allow-destructiv']);
+ assert.notStrictEqual(r.code, 0);
+ assert.match(r.stderr, /unknown flag\(s\): --allow-destructiv \(did you mean --allow-destructive\?\)/);
+});
+
+test('verify-model-app rejects an unknown flag rather than ignoring it', () => {
+ const r = run([script('verify-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--workspce', 'x']);
+ assert.notStrictEqual(r.code, 0);
+ assert.match(r.stderr, /unknown flag\(s\): --workspce \(did you mean --workspace\?\)/);
+});
+
+test('a correct invocation still succeeds after the guard', () => {
+ const r = run([script('build-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan', '--stage', 'ui']);
+ assert.strictEqual(r.code, 0, r.stderr);
+ assert.strictEqual(JSON.parse(r.stdout).dryRun, true);
+});
diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
index 696159ea1..b7017e928 100644
--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
@@ -420,7 +420,57 @@ test('CONTRACT: vendored seedRecordGraph returns { createdIds: { <entity>: [ids]
assert.deepStrictEqual(result.createdIds.new_widget, ['wid-0', 'wid-1'], 'createdIds[<entity>] lists the new row ids in order');
});
-// --- SDK backlog capability fills (re-vendored from cds-maker-sdk hardening-3) -------------------
+// #544 relies on two properties of the REAL bundle, neither of which a mock can prove. If a
+// re-vendor changed either, the wave seeding in entity-provision.js would silently link sample rows
+// to the wrong parents (or start failing again), so they are pinned here against the shipped bundle.
+test('CONTRACT: seedRecordGraph resolves a bind against options.createdIds BY INDEX, and cannot resolve one into its own group', async () => {
+ const posts = [];
+ const client = {
+ get: async (url) => {
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ if (meta) return { status: 200, headers: {}, body: { EntitySetName: `${meta[1]}s`, LogicalName: meta[1] } };
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async (url, body) => {
+ if (/CreateMultiple/.test(url)) {
+ posts.push(body);
+ const n = ((body && body.Targets) || []).length;
+ return { status: 200, headers: {}, body: { Ids: Array.from({ length: n }, (_, i) => `oid-${posts.length}-${i}`) } };
+ }
+ return { status: 204, headers: {}, body: {} };
+ },
+ patch: async () => ({ status: 204, headers: {}, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = sdkWith(client);
+ const selfBind = { navProperty: 'new_ParentOrgId', parentEntity: 'new_org', parentIndex: 0 };
+
+ // (1) A self-bind whose parent is in the SAME group cannot resolve — the ids are published only
+ // after the group completes. This is the #544 failure, and it is a property of the SDK, not a bug
+ // in the plugin: it is why the plugin must split the rows into waves itself.
+ await assert.rejects(
+ sdk.seedRecordGraph([{ entityLogical: 'new_org', records: [{ body: { new_name: 'Root' }, binds: [] }, { body: { new_name: 'Child' }, binds: [selfBind] }] }], { createdIds: {} }),
+ /has no created id/,
+ 'a same-group self-bind must still fail — the wave split is what makes it work'
+ );
+
+ // (2) The same bind DOES resolve when the parent id is supplied via options.createdIds, indexed
+ // by the parent's ORIGINAL position. A SPARSE array is what the plugin passes between waves
+ // (index 0 filled, later indices still empty), so the lookup must be positional, not dense.
+ const sparse = [];
+ sparse[0] = '11111111-1111-1111-1111-111111111111';
+ const res = await sdk.seedRecordGraph(
+ [{ entityLogical: 'new_org', records: [{ body: { new_name: 'Child' }, binds: [selfBind] }] }],
+ { createdIds: { new_org: sparse } }
+ );
+ const target = posts[posts.length - 1].Targets[0];
+ assert.strictEqual(target['[email protected]'], `/new_orgs(${sparse[0]})`,
+ 'the bind resolves to the id at options.createdIds[entity][parentIndex]');
+ assert.strictEqual(res.createdIds.new_org.length, 1, 'the returned ids cover only the rows in THIS call');
+});
+
+
// These lock the four NEW behaviors the skill now wires: quick-create table flag, OData pagination,
// idempotent global choice, and authored-column full width. Each drives the real vendored bundle so a
// future re-vendor that regresses the behavior fails HERE (the mock-based engine tests can't catch it).
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index 7d1fb1821..fb7a50b89 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -6,6 +6,7 @@ const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { readerFor, appIdFor } = require('../verify-model-app.js');
+const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');
const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';
@@ -214,6 +215,7 @@ function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResul
if (id === './lib/dataverse-auth.js') {
return {
parseArgs: () => parseResult,
+ validateFlags: validateFlagsFromParsed(() => parseResult.flags),
readJsonArg: (arg) => {
events.push({ type: 'readJsonArg', arg });
return { app: { name: 'Support Desk' }, solution: { publisherPrefix: 'new' } };
@@ -519,3 +521,132 @@ test('rolePrivileges paginates and never caps with top', async () => {
assert.strictEqual(q.options.paginate, true, 'must follow @odata.nextLink to completion');
assert.strictEqual('top' in q.options, false, 'must NOT cap with top -- Dataverse treats it as a hard cap and drops nextLink');
});
+
+// ---------------------------------------------------------------------------
+// appEntityComponents(): the app's TABLE (type-1) components.
+//
+// These drive the REAL reader through readerFor(), not a hand-fed fake handed to verify-spec — the
+// consumer tests in verify-spec.test.js prove the CHECK, these prove the Dataverse plumbing it
+// depends on (the componenttype filter, pagination, resolution direction and failure modes).
+// ---------------------------------------------------------------------------
+
+const META = { new_order: 'aaaa0000-0000-0000-0000-000000000001', new_line: 'aaaa0000-0000-0000-0000-000000000002', entity: 'eeee0000-0000-0000-0000-00000000000e' };
+
+// `componentIds` are the type-1 rows the app carries. `calls` records every query/metadata read.
+function componentsSdk({ componentIds = [], calls = [], resolve = META, noApp = false } = {}) {
+ return {
+ queryRecords: async (set, opts) => {
+ calls.push({ set, opts });
+ if (noApp) return [];
+ if (set === 'appmodule') return [{ appmoduleid: 'app-uuid-1', appmoduleidunique: 'uid-1' }];
+ if (set === 'appmodulecomponent') return componentIds.map((id) => ({ objectid: id, componenttype: 1 }));
+ return [];
+ },
+ findTables: async () => [],
+ findColumns: async () => [],
+ dataverse: {
+ get: async (url) => {
+ calls.push({ url });
+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
+ const logical = m && m[1];
+ if (typeof resolve === 'function') return resolve(logical);
+ const id = resolve[logical];
+ return id ? { status: 200, headers: {}, body: { MetadataId: id } } : { status: 404, headers: {}, body: null };
+ },
+ },
+ };
+}
+const readerWith = (sdk) => readerFor(sdk, 'contoso_app', { workspaceDir: os.tmpdir() });
+
+test('appEntityComponents(): filters componenttype 1 and PAGINATES rather than capping with top', async () => {
+ // `top` is a HARD cap in Dataverse and suppresses @odata.nextLink, so a capped page truncates
+ // silently — and for a MEMBERSHIP check a row that fell off the end reads as NOT PRESENT, i.e.
+ // verify would report a correctly built app as broken. The same trap was already found live on
+ // roleprivileges in this file. It would also hide the `entity` placeholder rows this check exists
+ // to find, since those are exactly what accumulates in a corrupted app.
+ const calls = [];
+ const sdk = componentsSdk({ componentIds: [META.new_order], calls });
+ await readerWith(sdk).appEntityComponents(['new_order']);
+ const q = calls.find((c) => c.set === 'appmodulecomponent');
+ assert.ok(q, 'the component query must run');
+ assert.match(q.opts.filter, /componenttype eq 1/);
+ assert.strictEqual(q.opts.paginate, true, 'must paginate to completion');
+ assert.strictEqual(q.opts.top, undefined, 'must NOT cap with top — a truncated page reads as "missing"');
+});
+
+test('appEntityComponents(): reports present vs absent for the WANTED tables', async () => {
+ const sdk = componentsSdk({ componentIds: [META.new_order] });
+ const r = await readerWith(sdk).appEntityComponents(['new_order', 'new_line']);
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.present, ['new_order']);
+ assert.strictEqual(r.placeholder, false);
+});
+
+test('appEntityComponents(): detects an `entity` placeholder component', async () => {
+ const sdk = componentsSdk({ componentIds: [META.new_order, META.entity] });
+ const r = await readerWith(sdk).appEntityComponents(['new_order']);
+ assert.strictEqual(r.placeholder, true, 'a component pointing at the `entity` metadata table must be reported');
+ assert.deepStrictEqual(r.present, ['new_order'], 'and the real table is still present');
+});
+
+test('appEntityComponents(): cost is bounded by the WANTED set, not by the component count', async () => {
+ // Resolving every COMPONENT instead would scale with the app and reintroduce the need for a cap.
+ const many = Array.from({ length: 300 }, (_, i) => `bbbb0000-0000-0000-0000-${String(i).padStart(12, '0')}`);
+ const calls = [];
+ const sdk = componentsSdk({ componentIds: many.concat(META.new_order), calls });
+ const r = await readerWith(sdk).appEntityComponents(['new_order']);
+ const metadataReads = calls.filter((c) => c.url).length;
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.present, ['new_order']);
+ // one per wanted table + one for the `entity` placeholder probe
+ assert.strictEqual(metadataReads, 2, `expected 2 metadata reads for 301 components, got ${metadataReads}`);
+});
+
+test('appEntityComponents(): a wanted table that does not exist is ABSENT, not a read failure', async () => {
+ // A 404 means the table is not in the environment at all, which the separate entity-existence
+ // check already reports. Failing the whole answer would mask it behind an unrelated error.
+ const sdk = componentsSdk({ componentIds: [META.new_order] });
+ const r = await readerWith(sdk).appEntityComponents(['new_order', 'new_ghost']);
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.present, ['new_order']);
+});
+
+test('appEntityComponents(): a non-404 resolution error fails closed and names the TABLE, not a GUID', async () => {
+ const sdk = componentsSdk({ componentIds: [META.new_order], resolve: (logical) => (logical === 'new_line' ? { status: 403, headers: {}, body: null } : { status: 200, headers: {}, body: { MetadataId: META[logical] } }) });
+ const r = await readerWith(sdk).appEntityComponents(['new_order', 'new_line']);
+ assert.strictEqual(r.ok, false);
+ assert.match(r.reason, /new_line/, 'the reason must name the table so an operator can act on it');
+ assert.match(r.reason, /403/);
+});
+
+test('appEntityComponents(): an unresolvable app fails closed', async () => {
+ const r = await readerWith(componentsSdk({ noApp: true })).appEntityComponents(['new_order']);
+ assert.strictEqual(r.ok, false);
+ assert.match(r.reason, /contoso_app/);
+});
+
+test('appEntityComponents(): an app with NO table components answers ok with nothing present', async () => {
+ // This is the reported defect itself (a sitemap naming tables the app does not contain), not a
+ // read failure — and it cannot mask a permissions problem, because the sitemap is read from the
+ // same appmodulecomponent table and would fail visibly first.
+ const r = await readerWith(componentsSdk({ componentIds: [] })).appEntityComponents(['new_order']);
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.present, []);
+});
+
+test('appEntityComponents(): memoized per wanted-set — one live read per verify run', async () => {
+ const calls = [];
+ const reader = readerWith(componentsSdk({ componentIds: [META.new_order], calls }));
+ await reader.appEntityComponents(['new_order']);
+ await reader.appEntityComponents(['new_order']);
+ assert.strictEqual(calls.filter((c) => c.set === 'appmodulecomponent').length, 1, 'the component query must not repeat');
+});
+test('appEntityComponents(): matches an objectid whose CASING differs from the resolved MetadataId', async () => {
+ // Dataverse does not guarantee that a component `objectid` and the table's `MetadataId` come back
+ // in the same casing, and a GUID is case-insensitive. Comparing raw strings would report a
+ // correctly pinned table as MISSING — a false red build on a healthy app.
+ const sdk = componentsSdk({ componentIds: [META.new_order.toUpperCase()] });
+ const r = await readerWith(sdk).appEntityComponents(['new_order']);
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.present, ['new_order'], 'an upper-cased objectid must still match');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index abc2cf950..ea1ed5d23 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -807,3 +807,83 @@ test('verifySpec: a failing context read cannot flip a proven feature to FAIL',
assert.strictEqual(r.ok, true, JSON.stringify(r.missing));
});
});
+
+// ---------------------------------------------------------------------------
+// App-module TABLE (type-1) membership.
+// ---------------------------------------------------------------------------
+
+// A spec whose sitemap shows two tables.
+function membershipSpec() {
+ return {
+ entities: [{ schemaName: 'new_order', columns: [] }, { schemaName: 'new_line', columns: [] }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'R', subAreas: [
+ { entity: 'new_order', title: 'Orders' },
+ { entity: 'new_line', title: 'Lines' },
+ ] }] }] },
+ };
+}
+function membershipRead(appEntityComponents) {
+ return {
+ findTable: async (l) => ({ logicalName: l }),
+ findColumns: async () => [],
+ queryRecords: async () => [],
+ sitemapXml: async () => '<SiteMap><Area><Group><SubArea Entity="new_order"/><SubArea Entity="new_line"/></Group></Area></SiteMap>',
+ ...(appEntityComponents ? { appEntityComponents } : {}),
+ };
+}
+const checkFor = (res, name) => res.checks.find((c) => c.kind === 'app-table-component' && c.name === name);
+
+test('app table membership: verify FAILS when a sitemap-visible table is absent from the app module components', async () => {
+ // The reported failure was invisible precisely because verify passed: it confirmed the table
+ // EXISTS and that the sitemap names it, but never that the app module actually CONTAINS it. An app
+ // can show a table in navigation while omitting it from its Tables list, which is an internally
+ // inconsistent definition and breaks consumers that read app-module membership.
+ const res = await verifySpec(membershipSpec(), membershipRead(async () => ({ ok: true, present: ['new_order'] })));
+ assert.strictEqual(checkFor(res, 'new_order').present, true);
+ const missing = checkFor(res, 'new_line');
+ assert.ok(missing && missing.present === false, 'the absent table must be reported by name');
+ assert.strictEqual(res.ok, false, 'verify must NOT pass while a sitemap table is missing from the app');
+});
+
+test('app table membership: verify passes when every sitemap table is a real app component', async () => {
+ const res = await verifySpec(membershipSpec(), membershipRead(async () => ({ ok: true, present: ['new_order', 'NEW_LINE'] })));
+ // Case-insensitive: Dataverse does not guarantee the casing of a resolved logical name.
+ assert.strictEqual(checkFor(res, 'new_line').present, true);
+ assert.ok(res.checks.filter((c) => c.kind === 'app-table-component').every((c) => c.present));
+});
+
+test('app table membership: an invalid `entity` placeholder component is reported', async () => {
+ // The known corruption: a table pinned as an `entity` INSTANCE pins the `entity` metadata table
+ // itself, so the component resolves to the logical name `entity` rather than to a real table.
+ // Those rows are junk and accumulate, so name them even when every declared table is present.
+ const res = await verifySpec(membershipSpec(), membershipRead(async () => ({ ok: true, present: ['new_order', 'new_line'], placeholder: true })));
+ const bad = res.checks.find((c) => c.kind === 'app-table-component' && /placeholder/i.test(c.name));
+ assert.ok(bad && bad.present === false, 'the `entity` placeholder must be reported');
+ assert.strictEqual(res.ok, false);
+});
+
+test('app table membership: an unreadable component list FAILS CLOSED rather than passing silently', async () => {
+ // "We could not look" must never read as "the app is fine" — that is the exact shape of the bug.
+ const res = await verifySpec(membershipSpec(), membershipRead(async () => ({ ok: false, reason: 'HTTP 403' })));
+ const c = res.checks.find((x) => x.kind === 'app-table-component');
+ assert.ok(c && c.present === false && /403/.test(c.detail), 'the reason must travel with the failure');
+ assert.strictEqual(res.ok, false);
+});
+
+test('app table membership: a reader without the capability is skipped, not crashed', async () => {
+ // verify-spec is also used with minimal readers; an optional capability must never become a
+ // TypeError for them (the established rule for columnVisualization).
+ const res = await verifySpec(membershipSpec(), membershipRead(null));
+ assert.deepStrictEqual(res.checks.filter((c) => c.kind === 'app-table-component'), []);
+ assert.strictEqual(res.ok, true);
+});
+
+test('app table membership: only SITEMAP-visible tables are required to be components', async () => {
+ // A spec entity with no subarea is a legitimate data-model-only table (the build does not pin it),
+ // so requiring it would fail every app that declares a supporting table.
+ const spec = membershipSpec();
+ spec.entities.push({ schemaName: 'new_audit', columns: [] });
+ const res = await verifySpec(spec, membershipRead(async () => ({ ok: true, present: ['new_order', 'new_line'] })));
+ assert.strictEqual(checkFor(res, 'new_audit'), undefined, 'a table with no subarea must not be required');
+ assert.ok(res.checks.filter((c) => c.kind === 'app-table-component').every((c) => c.present));
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index d39c052ca..4f9820b06 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -10,7 +10,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { verifySpec } = require('./lib/verify-spec.js');
const { appUniqueName } = require('./lib/sdk-build.js');
@@ -52,6 +52,67 @@ async function appIdFor(sdk, appUnique) {
return rows && rows[0] && rows[0].appmoduleid;
}
+// Which of `wanted` (table logical names) are real TABLE components of the app
+// (`appmodulecomponent` componenttype 1), plus whether the app carries an `entity` PLACEHOLDER row.
+//
+// Returns `{ ok: true, present, placeholder }` or `{ ok: false, reason }`. The caller fails the check
+// on `ok: false` rather than passing, because "we could not look" and "the app is fine" must never be
+// the same answer here.
+//
+// Direction matters, and an earlier version had it backwards. Resolving every COMPONENT id to a
+// logical name meant: a read per component (unbounded by anything the spec controls), a whole-answer
+// failure whenever one foreign id would not resolve — reported as an opaque GUID an operator cannot
+// act on — and a cap on the component query. This resolves only the tables the SPEC asks about, so
+// the cost is bounded by the spec (LIVE-MEASURED ~100 ms per table), a component pointing at a
+// deleted table is simply not one of ours, and every message names a table.
+//
+// `paginate: true`, never `top`. Dataverse honours `$top` as a HARD cap and omits
+// `@odata.nextLink`, so a capped page silently truncates — and for a membership check a row that
+// fell off the end reads as NOT PRESENT, i.e. verify reports a correctly built app as broken. The
+// same trap was already found live on `roleprivileges` in this file (see `rolePrivileges` below);
+// using `top` here would have reintroduced it, and would additionally have hidden the placeholder
+// rows this check exists to find, since those are exactly what accumulates in a corrupted app.
+//
+// An EMPTY component list is returned as `ok: true` with nothing present, NOT as a read failure:
+// that is the reported defect itself (a sitemap naming tables the app does not contain). It cannot
+// mask a permissions problem, because the sitemap is read from the SAME `appmodulecomponent` table
+// (componenttype 62) and would fail visibly first.
+async function appEntityComponentsFor(sdk, appUnique, wanted) {
+ try {
+ const apps = await sdk.queryRecords('appmodule', { select: ['appmoduleid', 'appmoduleidunique'], filter: `uniquename eq '${odataLit(appUnique)}'`, top: 1 });
+ const app = apps && apps[0];
+ if (!app || !app.appmoduleidunique) return { ok: false, reason: `app '${appUnique}' could not be resolved` };
+ const rows = await sdk.queryRecords('appmodulecomponent', {
+ select: ['objectid', 'componenttype'],
+ filter: `_appmoduleidunique_value eq ${app.appmoduleidunique} and componenttype eq 1`,
+ paginate: true,
+ });
+ const ids = new Set((rows || []).map((r) => r && r.objectid).filter(Boolean).map((s) => String(s).toLowerCase()));
+ // A type-1 `objectid` is a table's MetadataId, not a row id. `fetchEntityMetadata` resolves by
+ // LOGICAL NAME and is a disk-cached projection, so this goes through the raw client instead.
+ // A 404 means the table does not exist at all, which the separate `entity` existence check
+ // already reports — so it is "not a component", not a read failure.
+ const metadataId = async (logical) => {
+ const res = await sdk.dataverse.get(`/EntityDefinitions(LogicalName='${odataLit(logical)}')?$select=MetadataId`);
+ if (res && res.status === 404) return null;
+ if (!res || res.status < 200 || res.status >= 300 || !res.body || !res.body.MetadataId) {
+ throw new Error(`could not resolve table '${logical}' (HTTP ${res && res.status})`);
+ }
+ return String(res.body.MetadataId).toLowerCase();
+ };
+ const present = [];
+ for (const logical of wanted || []) {
+ const id = await metadataId(logical);
+ if (id && ids.has(id)) present.push(logical);
+ }
+ // The known corruption: a table pinned as an `entity` INSTANCE pins the `entity` METADATA table.
+ const entityId = await metadataId('entity');
+ return { ok: true, present, placeholder: !!(entityId && ids.has(entityId)) };
+ } catch (err) {
+ return { ok: false, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };
+ }
+}
+
function readerFor(sdk, appUnique, opts) {
opts = opts || {};
const genpageCli = opts.genpageCli;
@@ -66,6 +127,8 @@ function readerFor(sdk, appUnique, opts) {
// Memoize fetchSitemap: both sitemapXml and sitemapPageIds share one live query (Imp7 — one snapshot).
let sitemapP;
const memoSitemap = () => (sitemapP || (sitemapP = _fetchSitemap(sdk, appUnique)));
+ // Memoized app TABLE components — one live read per verify run, keyed by the wanted-table set.
+ const appComponentsP = new Map();
// Per-id page code cache. Downloads by specific id on demand rather than pulling all pages at once
// (the old all-pages downloadP). Each id gets its own output dir to avoid directory collision.
@@ -137,6 +200,13 @@ function readerFor(sdk, appUnique, opts) {
// sitemapXml (string, fail-closed '') for entity/icon hasElement checks — from the discriminated sitemap
// read. Returning '' on failure suppresses entity/icon checks without aborting the whole verify.
sitemapXml: async () => { const r = await memoSitemap(); return r.ok ? r.xml : ''; },
+ // The app's TABLE components, so verify can tell "the sitemap shows this table" from
+ // "the app module actually contains it". Memoized per wanted-set — one live read per verify run.
+ appEntityComponents: (wanted) => {
+ const key = (wanted || []).join(',');
+ if (!appComponentsP.has(key)) appComponentsP.set(key, appEntityComponentsFor(sdk, appUnique, wanted));
+ return appComponentsP.get(key);
+ },
};
// entityPrivileges(logical): the privilege set a table exposes, as [{ PrivilegeId, PrivilegeType, ... }].
@@ -230,15 +300,24 @@ function readerFor(sdk, appUnique, opts) {
}
async function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- // parseArgs sets a value-less flag to boolean `true`; treat those as missing so a bare
- // `--env`/`--spec`/`--workspace` fails with the usage message instead of crashing later in
- // createAzHttpClient / path.resolve / fs.mkdirSync when a boolean value reaches them.
- const env = typeof flags.env === 'string' ? flags.env : undefined;
- const specArg = typeof flags.spec === 'string' ? flags.spec : positional[0];
- const workspaceArg = typeof flags.workspace === 'string' ? flags.workspace : undefined;
- if (!env || !specArg || flags.workspace === true) {
- process.stderr.write('Usage: node verify-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--workspace <dir>]\n');
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node verify-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--workspace <dir>]';
+ // Reject an unknown or value-less flag before any network work: an unrecognised flag is dropped
+ // by parseArgs AND swallows the token after it, so `--workspce x` would silently verify against
+ // the default workspace and report drift the caller cannot explain.
+ const flagError = validateFlags(argv, { known: ['env', 'spec', 'workspace'], needValue: ['env', 'spec', 'workspace'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ // Each is now either absent or a non-empty string, so a boolean can no longer reach
+ // createAzHttpClient / path.resolve / fs.mkdirSync.
+ const env = flags.env;
+ const specArg = flags.spec || positional[0];
+ const workspaceArg = flags.workspace;
+ if (!env || !specArg) {
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
const specPath = path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg);
diff --git a/plugins/model-apps/scripts/write-app-spec-doc.js b/plugins/model-apps/scripts/write-app-spec-doc.js
index adae390ed..53b3b07a7 100644
--- a/plugins/model-apps/scripts/write-app-spec-doc.js
+++ b/plugins/model-apps/scripts/write-app-spec-doc.js
@@ -17,7 +17,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const { migrateAppSpec } = require('./lib/app-spec.js');
const { renderAppSpecDoc } = require('./lib/app-spec-doc.js');
@@ -53,11 +53,17 @@ function designGaps(spec) {
}
function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- const str = (v) => (typeof v === 'string' ? v : undefined);
- const specArg = str(flags.spec) || (typeof positional[0] === 'string' ? positional[0] : undefined);
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE = 'Usage: node scripts/write-app-spec-doc.js --spec @<app-folder>/app-spec.json [--env <orgUrl>] [--out <path>]';
+ const flagError = validateFlags(argv, { known: ['spec', 'env', 'out'], needValue: ['spec', 'env', 'out'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const specArg = flags.spec || positional[0];
if (!specArg) {
- process.stderr.write('Usage: node scripts/write-app-spec-doc.js --spec @<app-folder>/app-spec.json [--env <orgUrl>] [--out <path>]\n');
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
@@ -70,12 +76,12 @@ function main() {
return;
}
- const markdown = renderAppSpecDoc(spec, { envUrl: str(flags.env) });
+ const markdown = renderAppSpecDoc(spec, { envUrl: flags.env });
// Compute the gaps BEFORE writing: a failure here used to leave a written document behind and then
// exit with a raw stack, so the caller saw a crash next to a file that looked fine.
const warnings = designGaps(spec);
// Default next to the spec, which is the working directory the skill created in Phase 0.
- const docPath = str(flags.out) ? path.resolve(str(flags.out)) : path.join(path.dirname(specPath), 'model-app-plan.md');
+ const docPath = flags.out ? path.resolve(flags.out) : path.join(path.dirname(specPath), 'model-app-plan.md');
fs.mkdirSync(path.dirname(docPath), { recursive: true });
fs.writeFileSync(docPath, markdown, 'utf8');
diff --git a/plugins/model-apps/scripts/write-page-plan.js b/plugins/model-apps/scripts/write-page-plan.js
index b194d03a2..de8451df8 100644
--- a/plugins/model-apps/scripts/write-page-plan.js
+++ b/plugins/model-apps/scripts/write-page-plan.js
@@ -23,22 +23,30 @@
const fs = require('node:fs');
const path = require('node:path');
-const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
+const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');
const { migrateAppSpec } = require('./lib/app-spec.js');
const { buildPagePlan, pageKey, pageFile, pageDataMode, mdText } = require('./lib/page-plan.js');
function main() {
- const { positional, flags } = parseArgs(process.argv.slice(2));
- // parseArgs yields boolean `true` for a value-less flag; treat those as missing so a bare flag
- // fails with usage instead of reaching path.resolve/readFile as a boolean.
- const str = (v) => (typeof v === 'string' ? v : undefined);
- const specArg = str(flags.spec) || (typeof positional[0] === 'string' ? positional[0] : undefined);
- const workingDir = str(flags['working-dir']);
+ const argv = process.argv.slice(2);
+ const { positional, flags } = parseArgs(argv);
+ const USAGE =
+ 'Usage: node scripts/write-page-plan.js --spec @<app-folder>/app-spec.json --working-dir <dir> '
+ + '[--env <orgUrl>] [--app <label>] [--languages <text>] [--out <path>]';
+ // Every flag here carries a value, so all of them go in needValue; a bare one would otherwise
+ // reach path.resolve/readFile as a boolean.
+ const flagError = validateFlags(argv, {
+ known: ['spec', 'working-dir', 'env', 'app', 'languages', 'out'],
+ needValue: ['spec', 'working-dir', 'env', 'app', 'languages', 'out'],
+ });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ const specArg = flags.spec || positional[0];
+ const workingDir = flags['working-dir'];
if (!specArg || !workingDir) {
- process.stderr.write(
- 'Usage: node scripts/write-page-plan.js --spec @<app-folder>/app-spec.json --working-dir <dir> '
- + '[--env <orgUrl>] [--app <label>] [--languages <text>] [--out <path>]\n'
- );
+ process.stderr.write(USAGE + '\n');
process.exit(1);
}
@@ -47,9 +55,9 @@ function main() {
const absWorkingDir = path.resolve(workingDir);
const markdown = buildPagePlan(spec, {
- envUrl: str(flags.env),
- appLabel: str(flags.app),
- languages: str(flags.languages),
+ envUrl: flags.env,
+ appLabel: flags.app,
+ languages: flags.languages,
// Forward slashes: the plan schema requires them on Windows because downstream agents embed the
// path in shell commands where a backslash is an escape character.
workingDir: absWorkingDir.replace(/\\/g, '/'),
@@ -59,7 +67,7 @@ function main() {
pluginRoot: path.resolve(__dirname, '..').replace(/\\/g, '/'),
});
- const planPath = str(flags.out) ? path.resolve(str(flags.out)) : path.join(absWorkingDir, 'app-builder-page-plan.md');
+ const planPath = flags.out ? path.resolve(flags.out) : path.join(absWorkingDir, 'app-builder-page-plan.md');
// Fail BEFORE writing if the plan names a sample that does not exist — the worker's Step 3 reads
// `${PLUGIN_ROOT}/samples/<name>` and a missing file derails generation with a confusing error.
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index 111c3e9e6..46e952e7c 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -1,21 +1,17 @@
---
name: app-builder
-version: 0.8.1
-description: (Preview) Builds and edits a model-driven Power Apps app from a natural-language intent — tables, columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, business rules, business process flows, generative page intents for overview/dashboard surfaces (page `.tsx` generated in generate-pages after plan approval), and an app module + sitemap — via the headless cds-maker-sdk. Runs an interactive, multi-turn authoring flow (env selection, jobs-to-be-done first, then design-only App Spec authoring across confirmed levels, guardrail lint, plan-mode approval, generate-pages, full build) and a narrated build, and can download a deployed app back into an editable spec to change it. Use when the user says "build an app for X", "create a model-driven app", "make me an app to manage Y", "add a business process flow", or "edit/add to my app". This skill stands alone and does not require /genpage — but for a standalone generative page added to an app that already exists, use /genpage instead.
+version: 1.0.0
+description: Builds and edits a model-driven Power Apps app from a natural-language intent — tables, columns, relationships, adaptive forms with sub-grids, views, Choice-column charts, business rules, business process flows, generative page intents for overview/dashboard surfaces (page `.tsx` generated in generate-pages after plan approval), and an app module + sitemap — via the headless cds-maker-sdk. Runs an interactive, multi-turn authoring flow (env selection, jobs-to-be-done first, then design-only App Spec authoring across confirmed levels, guardrail lint, plan-mode approval, generate-pages, full build) and a narrated build, and can download a deployed app back into an editable spec to change it. Use when the user says "build an app for X", "create a model-driven app", "make me an app to manage Y", "add a business process flow", or "edit/add to my app". This skill stands alone and does not require /genpage — but for a standalone generative page added to an app that already exists, use /genpage instead.
author: Microsoft Corporation
argument-hint: "<app description>"
user-invocable: true
-allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Task, AskUserQuestion, EnterPlanMode, ExitPlanMode, TaskCreate, TaskUpdate, TaskList
+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Task, AskUserQuestion, EnterPlanMode, ExitPlanMode, TaskCreate, TaskUpdate, TaskList, read, edit, execute, search, agent, todo
---
> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
# app-builder — intent → model-driven app
-> ⚠️ **Preview.** This skill is in preview — its App Spec shape, flags, and build behavior may change
-> between versions. Review the plan-mode summary before applying, and prefer a non-production
-> environment while it stabilizes.
-
Turn a natural-language intent into a deployed model-driven app. You author a reviewable **App Spec**
(JSON) with the user across confirmed turns, then a deterministic engine (`cds-maker-sdk`, vendored)
builds it — tables/columns/relationships, sample data, views, Choice-column charts, adaptive forms
@@ -64,7 +60,7 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces
nothing: a command handler is handed the record (`function doThing(primaryControl)`) — the build
supplies the parameter, so write that signature; and **never hardcode Choice values** like
`100000003`, because they are assigned per publisher. Resolve by label via `getOptions()`
- (see `references/app-spec-schema.md` → webResources). Note also that command and web-resource
+ (see `references/app-spec-schema-advanced.md` → webResources). Note also that command and web-resource
**edits do not redeploy on rebuild** — the phases reuse what exists, so changing a button or a
script means deleting it first.
- **Form logic without code** — `businessRules[]`: show/hide, lock/unlock, set-required and
@@ -153,6 +149,39 @@ Rules:
Follow **[references/authoring-flow.md](../../references/authoring-flow.md)** step by step, running
every prompt yourself via `AskUserQuestion`. In short:
+#### Unattended runs (Copilot autopilot / automation)
+
+Resolve the interaction mode once before the first authoring question:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/resolve-interaction-mode.js" [--non-interactive]
+```
+
+`POWER_PLATFORM_SKILLS_NONINTERACTIVE=1`/`true` (or the equivalent
+`--non-interactive` invocation) means there is no user waiting for prompts. In
+that mode:
+
+- do not call `AskUserQuestion`, `EnterPlanMode`, or `ExitPlanMode`;
+- use explicit requirements and supplied existing specs as authoritative, and
+ use documented defaults only where the request leaves a non-destructive
+ choice open;
+- record each skipped gate as
+ `Unattended default: <question> → <answer> (<reason>)` in `workflow-log.md`;
+- treat the completed lint, preview, rendered design document, and build dry-run
+ as the approved plan, then continue with the normal approved path;
+- halt rather than guessing an ambiguous environment, app identity, or
+ destructive structural edit.
+
+Suppressing interaction never authorizes destructive work. An unattended
+existing-app apply still requires `--allow-destructive` wherever the build
+normally requires it; `POWER_PLATFORM_SKILLS_NONINTERACTIVE` only suppresses
+prompts.
+
+Carry the resolved mode through subprocesses: when it is unattended, append
+`--non-interactive` to every `build-model-app.js` invocation (dry-run, data
+pre-build, recovery rerun, and full apply). Do not append `--allow-destructive`
+unless destructive authority was supplied independently.
+
1. **Prereqs** — `node --version`, `pac help` (≥ 2.7.0).
2. **Environment (PAC)** — `pac auth list`. If exactly one / an active profile, **confirm it
(FYI), don't ask**. If several and none active, **ask** which to use. If none, ask the user
@@ -162,7 +191,14 @@ every prompt yourself via `AskUserQuestion`. In short:
4. **Levelled authoring** — **first read the App Spec format** so you author to the exact
shape (do this once; don't go spelunking through scripts):
[`references/app-spec-schema.md`](../../references/app-spec-schema.md) and the worked sample
- [`samples/app-spec.support-desk.json`](../../samples/app-spec.support-desk.json). Phase 1 is
+ [`samples/app-spec.support-desk.json`](../../samples/app-spec.support-desk.json). That document
+ covers everything an app always has. **Additionally read
+ [`references/app-spec-schema-advanced.md`](../../references/app-spec-schema-advanced.md) once your
+ design calls for a conditional feature** — business rules, a business process flow, command-bar
+ buttons, web resources, global choices, classic dashboards, or `roleGrants[]`. Its pointer table
+ is in the main schema, and the toolbox above tells you when to reach for each; read the detail
+ only for the ones you are actually using, and never skip a capability just to avoid the read.
+ Phase 1 is
**design-only**: never emit page `.tsx` here. Each level is confirmed via `AskUserQuestion` before
the next begins, and `app-spec.json` is persisted after each — full prompts in the playbook.
- **Level (a0) — personas & jobs-to-be-done** (`personas[]`): **before proposing any tables**, ask
@@ -263,7 +299,8 @@ After plan-mode approval (before the full build):
> - Target file: [file from step 3 — already includes .tsx; do NOT append another]
> - Plan document: [absolute path to the app-builder-page-plan.md written in step 3]
> - Data mode: **[dataMode from step 3 — `dataverse` or `mock`]**
- > - Connectors: **disabled**
+ > - Connectors: **none**
+ > - Telemetry: **disabled**
> - RuntimeTypes: [absolute path to RuntimeTypes.ts] ← omit this line when Data mode is `mock`
> - Working directory: [absolute working-dir path]
> - Plugin root: ${PLUGIN_ROOT}
@@ -273,8 +310,11 @@ After plan-mode approval (before the full build):
The plan's `## Environment` carries `Mode: app-builder` and every page row carries a **Key**, so
the worker emits `"PAGEREF_<key>"` for cross-page navigation (never a file-derived token — a
downloaded page's `codeFile` is a path, not its identity). Custom nav ids go in `data:` — never
- `recordId`. `Connectors: disabled` is a constant here: the App Spec has no connector-binding
- concept, so the projected plan always says `No connector bindings.`
+ `recordId`. `Connectors: none` and `Telemetry: disabled` are constants here: the App Spec has no
+ connector-binding concept (so the projected plan always says `No connector bindings.`), and
+ `/app-builder` never runs the Phase 4.7 `custom-telemetry` probe. Both are stated explicitly
+ rather than omitted — the page-builder treats a missing line as the same fail-closed value, but
+ an explicit line is what makes the dispatch contract checkable.
5. **Validate + commit the transition (transactional)** — never flip `source` by hand, and never
flip pages one at a time as workers return. Run:
@@ -607,5 +647,7 @@ child view id. Each step emits `[n/total]`.
**custom grid rendering** (`entities[].columns[].visualization` — radial dial / line chart /
heat map / star rating, preview); web resources + form JS event handlers; sample data with
**multi-parent `$parents`** + **`statusReason`**. See [`docs/app-builder-capabilities.md`](../../docs/app-builder-capabilities.md) and
- [`references/app-spec-schema.md`](../../references/app-spec-schema.md) — author from that **single**
- doc; you should not need to read the SDK, lint, or engine to write a spec.
+ [`references/app-spec-schema.md`](../../references/app-spec-schema.md) (plus
+ [`app-spec-schema-advanced.md`](../../references/app-spec-schema-advanced.md) for the conditional
+ fields it points at) — author from those docs; you should not need to read the SDK, lint, or
+ engine to write a spec.
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index e631ca98d..610210ecc 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -6,7 +6,7 @@ author: Microsoft Corporation
argument-hint: "<page description> | edit"
user-invocable: true
model: sonnet
-allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebFetch, Task, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebFetch, Task, AskUserQuestion, EnterPlanMode, ExitPlanMode, TaskCreate, TaskUpdate, TaskList, read, edit, execute, search, web, agent, todo
---
> **Plugin check**: Run `node "${PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
@@ -23,12 +23,15 @@ This skill orchestrates specialist agents across the create and edit flows:
**Create flow:**
1. **`genpage-planner`** — validates prerequisites, gathers requirements, detects what
- entities and apps exist, presents a plan for approval, writes `genpage-plan.md`.
+ entities and apps exist, and returns a proposed plan for the orchestrator to present.
+ Writes `genpage-plan.md` once the orchestrator re-invokes it with the approval outcome.
May pause and return `connector_discovery_required` (see 2).
2. **`genpage-connector-builder`** — top-level orchestrator dispatch for connector
feature-gating and discovery; writes `connector-bindings.md` + `connectors.json`.
Runs **after** the planner has resolved create-vs-edit and the target environment
(discovery is mutating), then the planner is re-invoked with its contract.
+ **`genpage-customapi-builder`** — the same top-level dispatch for server-side
+ Custom API (Action/Function) needs; writes `custom-api-bindings.md` + `actions.json`.
3. **`genpage-entity-builder`** — creates Dataverse entities (tables, columns,
relationships, choices, sample data) via the plugin's Node.js Web API scripts
4. **`genpage-page-builder`** — generates one complete `.tsx` file per page; multiple
@@ -37,13 +40,15 @@ This skill orchestrates specialist agents across the create and edit flows:
**Edit flow:**
5. **`genpage-connector-builder`** — top-level orchestrator dispatch when an edit adds,
- replaces, discovers, or clears connector bindings; preserves unchanged bindings
- when the feature gate is OFF
+ replaces, discovers, removes, or clears connector bindings; preserves unchanged bindings
+ when the edit does not touch them, or when the `connectors` rollback gate is off.
+ **`genpage-customapi-builder`** — the same top-level dispatch when an edit adds, replaces,
+ discovers, removes, or clears Custom API bindings.
6. **`genpage-edit-planner`** — reads the downloaded page artifacts, gathers change
requirements, presents an edit plan, writes `genpage-edit-plan.md`
-You (the skill) coordinate the agents and own connector dispatch, app creation,
-RuntimeTypes generation, deployment, browser verification, and the inline
+You (the skill) coordinate the agents and own connector and Custom API dispatch, app
+creation, RuntimeTypes generation, deployment, browser verification, and the inline
application of planned edits.
## References
@@ -103,50 +108,156 @@ node "${PLUGIN_ROOT}/scripts/generate-page-manifest.js" <working-dir> <kebab-slu
### Phase 1: Plan
-> **⚠️ CRITICAL — you MUST invoke `genpage-planner` via the `Task` tool. You MUST
-> NOT inline the planner's questions yourself with `AskUserQuestion`.**
+> **⚠️ CRITICAL — the interactive steps run HERE, in the main conversation loop.
+> You MUST NOT dispatch them to a `Task` subagent.**
>
-> The planner is not optional or skippable. It runs:
+> A `Task` subagent is **headless**: `AskUserQuestion`, `EnterPlanMode` and
+> `ExitPlanMode` never reach the user from inside one. A flow that specifies them
+> there cannot complete — the question is never answered and the approval never
+> given. This is the same rule `/app-builder` follows, and the reason its
+> subagents are headless workers only.
+>
+> `genpage-planner` is therefore a **headless discovery agent**. It runs the
+> read-only work and returns what it found; **you** ask the questions and present
+> the plan.
+>
+> Run in the main loop (never delegated):
> 1. Prerequisite validation (`node --version`, `pac help` version > 2.10.0)
> 2. Auth verification (`pac auth list`, environment selection)
-> 3. The structured "Create new / Edit existing" question (via `AskUserQuestion`
-> inside the planner subagent, not here)
+> 3. The structured "Create new / Edit existing" question (`AskUserQuestion`)
> 4. Language detection (`pac model list-languages`) — only on new-page path
> 5. Entity existence detection (`pac model list-tables --search`)
> 6. App detection (`pac model list`) with proper selection prompts
-> 7. Plan-mode presentation and approval
-> 8. Writes `genpage-plan.md` to the working directory
+> 7. Plan-mode presentation and approval (`EnterPlanMode` / `ExitPlanMode`)
+> 8. Telling `genpage-planner` the approval outcome — it writes `genpage-plan.md`
+> itself — and confirming the file exists before Phase 2
+>
+> Steps 1, 2, 4, 5, 6 are read-only discovery and **may** be delegated to
+> `genpage-planner`; steps 3, 7 and 8 never can. Delegating the discovery is an
+> optimisation, not a requirement — running it inline is equally correct, but
+> `genpage-plan.md` is still written by the planner either way (see step 6 of the
+> Steps list): its section headings are a machine-readable contract every
+> downstream phase parses by name, so it has exactly one author. If you ran the
+> discovery inline, dispatch the planner once with what you found, so it has the
+> context to produce the plan without repeating your reads.
>
-> Reasons to **NEVER** ask "new or edit?" yourself before invoking the planner:
-> - You would skip prereq + auth (the planner is the only thing that runs them)
-> - The structured question gives the user labeled options; an inline free-text
-> prompt forces them to guess
-> - The planner returns `{ "action": "edit" }` as a contract — your inline
-> question can't produce that signal cleanly
+> **Never skip the prereq/auth steps**, even when `$ARGUMENTS` already states the
+> intent. A stated intent lets you skip *question 3*; it does not establish that
+> the CLI is present, authenticated, or pointed at the right environment.
>
-> Even if `$ARGUMENTS` looks like it tells you the intent, **still invoke the
-> planner**. Pass the intent in the prompt — the planner uses it to skip its
-> own Question 1 if appropriate, but the prereq/auth/env steps still run.
+> **Whoever runs a step records it in `workflow-log.md`** in the documented
+> format — `AskUserQuestion: <question> → <answer>`, `EnterPlanMode called`
+> followed by the response. The log is the contract the eval harness reads, and
+> it does not care which loop made the call.
+
+#### Unattended runs (Copilot autopilot / Claude auto-accept)
+
+Copilot CLI autopilot and Claude Code auto-accept drive this skill with **no user
+watching**. Every gate below is written as "ask the user", and in those modes
+there is nobody to answer: the run either stalls on a question no one sees or,
+worse, records an answer nobody gave. Resolve the mode **once, at the start of
+Phase 1**, and carry it through every gate:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/resolve-interaction-mode.js"
+```
+
+One JSON line, always exit 0 — "there is no user" is a fact about the run, not a
+failure of it:
+
+```json
+{ "ok": true, "interactive": false, "reason": "POWER_PLATFORM_SKILLS_NONINTERACTIVE is set" }
+```
+
+A run is unattended when `--non-interactive` is passed or
+`POWER_PLATFORM_SKILLS_NONINTERACTIVE` is `1`/`true` — the same switch
+`/app-builder` already uses, so one setting covers both skills.
+
+When `interactive` is `false`, do not call `AskUserQuestion`, `EnterPlanMode` or
+`ExitPlanMode` at all. Take the documented default and record it in
+`workflow-log.md` as `Unattended default: <question> → <answer> (<reason>)`, so
+the log still shows what decided the run:
+
+| Gate | Attended | Unattended |
+| --- | --- | --- |
+| Recording the resolved mode | Nothing to record | Write the mode itself as `Unattended default: interaction mode → unattended (<reason>)` before the first gate. Record it with this marker, not as free prose such as `Interaction mode: unattended` — the evaluator keys on the marker, and prose forms are indistinguishable from an attended log that merely mentions the word (`Mode: unattended = false`, `not unattended`). |
+| Create new / edit existing (step 2) | `AskUserQuestion` | Whatever `$ARGUMENTS` states. With nothing stated, **create new** — the only additive choice. |
+| An agent returns `needs_input` (step 4) | Ask, then re-invoke | Re-invoke with the option the agent marked `"default": true`. If it marked none, **halt**. |
+| Plan approval (step 5) | `EnterPlanMode` / `ExitPlanMode` | Treat the plan as approved and continue to step 6, which still writes `genpage-plan.md` through the planner. The plan is recorded, just not presented. Log this gate as `Unattended default: plan approval → approved (<reason>)` — the evaluator looks for the plan/approval wording and `approved` on that one line, so a paraphrase such as `→ auto-approve` is read as a missing approval record. |
+| Browser verification (Phase 7) | Offer it | Skip it. |
+
+**Suppressing a prompt never authorizes destructive work.** Editing an existing
+page overwrites source nobody reviewed, so on the **edit** path an unattended run
+requires the page to be named explicitly in `$ARGUMENTS`. Do not infer the target
+from a search result and do not fall back to "the only page that matched". If the
+target is ambiguous, **halt and say so** — an unattended run that guesses which
+page to overwrite is the one failure this table exists to prevent.
+
+Halting is a normal outcome here, not an error to route around: report what was
+missing and stop, so the run can be re-driven with the decision supplied.
#### Steps
-1. Invoke `genpage-planner` via `Task` with the prompt below. Connector discovery
- has **not** run yet, so tell the planner the contract is the literal
- `No connector bindings.` and that discovery is available on request (see 1a).
-2. Wait for it to finish (it returns a summary).
-3. If the return includes `{ "action": "connector_discovery_required" }`, invoke
- `genpage-connector-builder` with the returned intent — **Mode: `create`** for a
- new page, **Mode: `edit`** if the planner also reported an edit — using the
- environment URL the planner resolved, then invoke `genpage-planner` again with
- the builder's `## Connector Bindings` contract and `connectors.json` status.
-4. If the return includes `{ "action": "edit" }`, jump to the **Edit Flow** section.
-5. Otherwise the planner has written `genpage-plan.md`. Proceed to Phase 2.
+1. Run the prerequisite, auth and discovery steps (inline, or via
+ `genpage-planner` as a headless worker). Connector discovery has **not** run
+ yet, so the contract is the literal `No connector bindings.`, with discovery
+ available on request (see 1a). Custom API discovery is likewise orchestrator-
+ owned and has not run either, so its contract starts as the literal
+ `No custom API bindings.`, with discovery available on request (see 1b).
+2. Ask question 3 (**create new / edit existing**) with `AskUserQuestion`, unless
+ `$ARGUMENTS` already settles it. On **edit**, jump to the **Edit Flow** section.
+3. If discovery reports `{ "action": "connector_discovery_required" }`, invoke
+ `genpage-connector-builder` with the intent — **Mode: `create`** for a new
+ page, **Mode: `edit`** for an edit — using the resolved environment URL, then
+ re-run discovery with the builder's `## Connector Bindings` contract and
+ `connectors.json` status. If it instead reports
+ `{ "action": "custom_api_discovery_required" }`, invoke `genpage-customapi-builder`
+ the same way (same mode, resolved environment URL, plus the returned `pageTables`),
+ then re-run the planner with the builder's `## Custom API Bindings` contract and
+ `actions.json` status (see 1b).
+ If `genpage-connector-builder` or `genpage-customapi-builder` instead reports
+ that its declared file or process-execution tools are unavailable, do **not**
+ retry the same worker. Record the worker failure, read that worker's agent
+ file, and run the discovery-builder workflow inline in this orchestrator
+ using the same resolved mode, environment, intent, and safety gates. This
+ inline fallback is recovery from task-runtime tool exposure only; it does not
+ bypass connector/custom-API feature gates or user decisions.
+4. If any agent returns `{ "action": "needs_input", … }`, ask its questions here
+ with `AskUserQuestion`, record them in `workflow-log.md`, and re-invoke that
+ agent with the answers. Agents never prompt; they request.
+5. Present the plan with `EnterPlanMode` and get approval via `ExitPlanMode`.
+ On a revision request, re-invoke the planner with the requested revisions and
+ present the revised plan again.
+6. **On approval, re-invoke `genpage-planner` with the approval outcome _plus
+ the plan body it returned and everything it already discovered_.** The planner
+ writes `genpage-plan.md` in its own final step, and it only reaches that step
+ when it is told the plan was approved — a `Task` subagent is headless, so it
+ cannot see the `ExitPlanMode` result any other way. A re-invocation is a fresh
+ run with no memory of the last one: carry the state forward or it will re-ask
+ questions the user has already answered, or re-derive a plan that is not the
+ one they approved. Same rule as Phase 2b. Do not write the file yourself — its
+ section headings are a machine-readable contract that every downstream phase
+ parses by name.
+
+ If `genpage-planner` reports that the file tools needed to write the approved
+ `genpage-plan.md` are unavailable, do not retry it and do not write the plan
+ inline. **Halt** with the approved plan body and failure recorded. Planner
+ authorship is the provenance gate for every downstream phase.
+7. Confirm `<working-dir>/genpage-plan.md` exists before starting Phase 2.
+ Reaching Phase 2 without it means building from a plan nobody approved, and
+ Phase 2 reads that file as its first action.
+
+ **If it is missing, do not proceed and do not write it yourself.** Re-invoke
+ the planner once more with the approval outcome and the plan body. If it is
+ still missing, stop and tell the user what was approved and what failed to be
+ written — a hand-written substitute is a plan with no provenance, and every
+ later phase will treat it as approved.
#### 1a. Connector discovery is orchestrator-owned and never speculative
`genpage-connector-builder` is dispatched only by this top-level orchestrator,
-not by `genpage-planner`. This keeps the connectors feature gate in one agent
-while avoiding nested `Task` calls from the planner.
+not by `genpage-planner`. This keeps connector discovery and its rollback gate in one
+agent while avoiding nested `Task` calls from the planner.
**Never run discovery before the planner returns** — not even when `$ARGUMENTS`
obviously mentions SharePoint, Teams, Office 365 or a custom REST source.
@@ -169,9 +280,35 @@ So the sequence is always: plan first, then discover, then re-plan.
`<working-dir>/connector-bindings.md` and verify `<working-dir>/connectors.json`
is a bare JSON array, then re-run the planner with the refreshed contract.
-The builder remains the single owner of the connectors flag: it probes first,
-writes `No connector bindings.` + `[]` when the flag is OFF, and performs all
-connection discovery only when the flag is ON.
+The builder remains the single owner of connector discovery and of the `connectors`
+rollback gate: it probes first, writes `No connector bindings.` + `[]` when the gate
+is off or the page needs no connector, and performs all connection discovery only
+when one is required.
+
+#### 1b. Custom API discovery is orchestrator-owned too
+
+`genpage-customapi-builder` is likewise dispatched only by this top-level orchestrator,
+not by `genpage-planner` — the planner has no `Task` tool, and the builder may need to ask
+the user which Custom API to bind, which only the main loop can do. Custom API discovery is
+**read-only** (a Web API query over the Custom API tables), so unlike connector discovery it
+carries no "wrong environment / wrong mode cannot be undone" hazard. It still runs after the
+planner so it targets the environment the planner resolved and binds to the page tables it
+detected.
+
+- Every first planner invocation gets the literal contract `No custom API bindings.` and is
+ told discovery has not run.
+- When the planner determines a server-side Custom API (Action/Function) is needed — from
+ `$ARGUMENTS` or from its own user clarification — it returns
+ `{ "action": "custom_api_discovery_required", "intent": "...", "resolvedAction": "create",
+ "envUrl": "...", "pageTables": "..." }`.
+- Only then dispatch `genpage-customapi-builder` with that mode, environment URL, page tables,
+ the working directory and `${PLUGIN_ROOT}`. Read `<working-dir>/custom-api-bindings.md` and
+ verify `<working-dir>/actions.json` is a bare JSON array, then re-run the planner with the
+ refreshed contract.
+
+The builder remains the single owner of the `custom-api` feature gate: it probes first, writes
+`No custom API bindings.` + `[]` when the gate is off or the page needs no Custom API, and
+performs discovery only when one is required.
#### Invocation prompt
@@ -181,10 +318,13 @@ Pass a prompt that includes:
- The working directory (absolute path from Phase 0)
- The plugin root path: `${PLUGIN_ROOT}`
- The connector contract: the full body of `<working-dir>/connector-bindings.md`,
- or the literal `No connector bindings.` when discovery was not needed or the
- feature gate was OFF
+ or the literal `No connector bindings.` when discovery was not needed
- The connector upload file status: `<working-dir>/connectors.json` exists and is
a bare JSON array, or `no connectors.json; omit --connectors`
+- The Custom API contract: the full body of `<working-dir>/custom-api-bindings.md`,
+ or the literal `No custom API bindings.` when discovery was not needed
+- The Custom API upload file status: `<working-dir>/actions.json` exists and is
+ a bare JSON array, or `no actions.json; omit --actions`
Example:
@@ -196,12 +336,19 @@ Example:
> Plugin root: ${PLUGIN_ROOT}
>
> Connector discovery is orchestrator-owned. Do **not** invoke
-> `genpage-connector-builder` from inside the planner. Use this as the entire
-> `## Connector Bindings` section of the plan:
+> `genpage-connector-builder` from inside the planner. The `----- BEGIN/END
+> CONNECTOR BINDINGS -----` lines below are delimiters for **this prompt only**:
+> they mark where the contract starts and ends. Do **not** copy them into
+> `genpage-plan.md`. The `## Connector Bindings` section of the plan is exactly
+> the text between them:
>
+> ----- BEGIN CONNECTOR BINDINGS -----
> [paste connector-bindings.md body, or `No connector bindings.`]
+> ----- END CONNECTOR BINDINGS -----
>
-> Connector upload file: [absolute path to connectors.json, or `none — omit --connectors`]
+> Connector upload file (orchestration metadata; not part of the
+> `## Connector Bindings` section): [absolute path to connectors.json, or
+> `none — omit --connectors`]
>
> If your clarification questions reveal connector-backed data that is not covered
> by the connector contract above, stop and return
@@ -210,10 +357,34 @@ Example:
> instead of trying to discover connectors yourself. `resolvedAction` and `envUrl`
> are required — discovery is dispatched against exactly those.
>
-> Follow the instructions in your agent file. Validate prereqs, confirm auth, ask
-> the new/edit question via AskUserQuestion, then proceed accordingly. Write
-> genpage-plan.md to the working directory if creating. Return the page list,
-> entity status, app selection, and any `{ "action": "edit" }` signal when complete.
+> Custom API discovery is orchestrator-owned too. Do **not** invoke
+> `genpage-customapi-builder` from inside the planner. The `----- BEGIN/END
+> CUSTOM API BINDINGS -----` lines below are delimiters for **this prompt only**:
+> they mark where the contract starts and ends. Do **not** copy them into
+> `genpage-plan.md`. The `## Custom API Bindings` section of the plan is exactly
+> the text between them:
+>
+> ----- BEGIN CUSTOM API BINDINGS -----
+> [paste custom-api-bindings.md body, or `No custom API bindings.`]
+> ----- END CUSTOM API BINDINGS -----
+>
+> Custom API upload file (orchestration metadata; not part of the
+> `## Custom API Bindings` section): [absolute path to actions.json, or
+> `none — omit --actions`]
+>
+> If your clarification questions reveal a server-side Custom API (Action/Function)
+> not covered by the Custom API contract above, stop and return
+> `{ "action": "custom_api_discovery_required", "intent": "<operation>",
+> "resolvedAction": "create" | "edit", "envUrl": "<the environment you resolved>",
+> "pageTables": "<page tables or none>" }` instead of trying to discover it yourself.
+>
+> Follow the instructions in your agent file. Validate prereqs and confirm auth.
+> The create/edit decision and the resolved environment are supplied to you by the
+> orchestrator (it asks; you are headless) — use them rather than prompting. If you
+> need any further decision, return `{ "action": "needs_input", … }`. Write
+> genpage-plan.md to the working directory once the orchestrator reports the plan
+> approved. Return the page list, entity status, app selection, and any
+> `{ "action": "edit" }` signal when complete.
### Phase 2: Create Entities (Conditional)
@@ -277,6 +448,23 @@ plan's `## Environment` — no need to re-thread them here.
Wait for completion. The builder writes a transactional log at
`<working-dir>/genpage-entity-creation-log.md` for recovery on failure.
+**The builder is headless and will ask for the sample-data decision by returning
+`{ "action": "needs_input", … }`** (it has no way to prompt). Handle it here, in
+this loop, exactly as Phase 1 step 4 does:
+
+- Ask each question with `AskUserQuestion`.
+- Record every exchange in `workflow-log.md` as `AskUserQuestion: <question> → <answer>`.
+- Re-invoke the builder with the answers plus everything it already returned, so
+ it can carry out the step that depended on them (sample data is created by a
+ second pass of its own CLI, not by anything here). A re-invocation restarts the
+ agent at its first step, which is safe — `provision-entities.js` is idempotent
+ and re-reports the existing tables rather than recreating them — but say which
+ decision has now been answered so it goes on to the sample-data step instead of
+ asking again.
+
+Repeat until it returns a completion rather than a request. Proceeding to Phase 3
+on a `needs_input` return silently drops the decision the user was asked to make.
+
### Phase 3: App Creation/Selection
Read `genpage-plan.md` for the app decision and the `Solution` line in
@@ -321,32 +509,32 @@ After generating, read the RuntimeTypes.ts file to verify it generated correctly
### Phase 4.5: Connector Bindings (Conditional)
-**Re-probe the feature gate here — do not rely on the plan content alone.** A plan
-authored while the flag was ON must not deploy connectors after it is turned OFF:
+**Re-probe the rollback gate here — do not rely on the plan content alone.** Connectors
+are GA and the flag ships ON, so this normally passes; it exists so a plan authored
+while the feature was on cannot deploy connectors after it has been turned off:
```powershell
node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors
```
-**If it prints `disabled`:** connectors are OFF. Skip this phase entirely — do not
-create or pass `connectors.json`, and never add `--connectors` on upload —
-**regardless of what the plan's `## Connector Bindings` section says**. (Backstop:
-`list-connections.js` / `create-connection-reference.js` also fail closed with
-exit 3 if invoked while OFF.)
-
-**Carry this decision into code generation.** The probe result is `Connectors:
-disabled` / `Connectors: enabled` for the rest of the run, and Phase 5 **must** pass
-it verbatim in every page-builder dispatch. When it is `disabled`, every downstream
-step treats the plan's `## Connector Bindings` section as if it read
-`No connector bindings.` — otherwise the generated page would call a connector that
-this run deliberately never binds, and the page fails at runtime instead of simply
-omitting the feature.
-
-**If it prints `enabled`:** read the plan's `## Connector Bindings` section and
-treat it as bindings **only when it contains an actual binding table** (a
-`| Logical Name | …` header with at least one data row). If the section is
-`No connector bindings.`, empty, missing, or malformed, treat the page as having
-no connectors and skip this phase.
+**If it prints `disabled`:** the outcome is `Connectors: none` **regardless of what the
+plan's `## Connector Bindings` section says**. Skip the rest of this phase — do not
+create or pass `connectors.json`, and do not add `--connectors` on upload. (Backstop:
+`list-connections.js` / `create-connection-reference.js` also fail closed with exit 3.)
+
+**If it prints `enabled`:** read the plan's `## Connector Bindings` section and treat it
+as bindings **only when it contains an actual binding table** (a `| Logical Name | …`
+header with at least one data row). If the section is `No connector bindings.`, empty,
+missing, or malformed, the page has no connectors: skip this phase entirely — do not
+create or pass `connectors.json`, and do not add `--connectors` on upload.
+
+**Carry this decision into code generation.** The outcome is `Connectors: <n>
+binding(s)` or `Connectors: none` for the rest of the run, and Phase 5 **must** pass
+it verbatim in every page-builder dispatch — otherwise the generated page could call
+a connector this run never binds, and the page fails at runtime instead of simply
+omitting the feature. Note the dispatch value is the **binding count**, not the flag
+state: a disabled gate and an empty binding table both produce `none`, because the
+page-builder only ever needs to know how many bindings it may call.
When there are real bindings, the `genpage-connector-builder` agent already wrote
`<working-dir>/connectors.json` during planning — verify it exists and matches the
@@ -471,7 +659,11 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
`${PLUGIN_ROOT}/references/verified-icons.txt` (one Grep per name).
Rewrite any unverified names with the closest verified alternative; do not
load the full icon list into context
-9. Proceed to Phase 6
+9. Grep the generated file with `['"]?borderWidth['"]?\s*:`. Griffel rejects
+ that shorthand only at runtime; the regex catches unquoted, quoted, and
+ whitespace-separated property syntax. Replace every match with the four
+ explicit border-side widths before deployment.
+10. Proceed to Phase 6
This saves ~5-15s of Task overhead and ~3K tokens that would otherwise be
duplicated in a subagent context.
@@ -488,7 +680,7 @@ For each page, pass a prompt that includes:
- Target file name (e.g., "candidate-tracker.tsx")
- Absolute path to `genpage-plan.md`
- Data mode (see below) — either a RuntimeTypes path or an explicit mock flag
-- **Connectors: `enabled` or `disabled`** — the Phase 4.5 probe result, verbatim
+- **Connectors: `none` or `<n> binding(s)`** — the Phase 4.5 outcome, verbatim
- **Telemetry: `enabled` or `disabled`** — the Phase 4.7 probe result, verbatim
- Working directory
- Plugin root: `${PLUGIN_ROOT}`
@@ -500,7 +692,7 @@ For each page, pass a prompt that includes:
> - Target file: [filename].tsx
> - Plan document: [absolute path to genpage-plan.md]
> - Data mode: **dataverse**
-> - Connectors: **[enabled|disabled from Phase 4.5]**
+> - Connectors: **[none|<n> binding(s) from Phase 4.5]**
> - Telemetry: **[enabled|disabled from Phase 4.7]**
> - RuntimeTypes: [absolute path to RuntimeTypes.ts]
> - Working directory: [absolute path from Phase 0]
@@ -516,7 +708,7 @@ For each page, pass a prompt that includes:
> - Target file: [filename].tsx
> - Plan document: [absolute path to genpage-plan.md]
> - Data mode: **mock**
-> - Connectors: **[enabled|disabled from Phase 4.5]**
+> - Connectors: **[none|<n> binding(s) from Phase 4.5]**
> - Telemetry: **[enabled|disabled from Phase 4.7]**
> - Working directory: [absolute path from Phase 0]
> - Plugin root: ${PLUGIN_ROOT}
@@ -526,6 +718,13 @@ For each page, pass a prompt that includes:
Wait for all page-builder tasks to complete before proceeding.
+After the parallel workers return, confirm every target file exists. If a worker
+reported missing declared file/process tools or produced no file, do not
+re-dispatch that worker. Run the Phase 5b page-builder workflow inline for only
+the failed page, preserving the same plan and dispatch inputs. Then Grep every
+generated page with `['"]?borderWidth['"]?\s*:` and replace the unsupported
+Griffel shorthand before Phase 6.
+
### Phase 6: Deploy
For each `.tsx` file produced, deploy to Power Apps.
@@ -681,15 +880,17 @@ target solution so they travel cross-environment.
`node ${PLUGIN_ROOT}/scripts/add-page-to-solution.js <envUrl> <solutionUniqueName> <app-id> --page-ids "<page-id1,page-id2>" --connection-refs "<logicalName1,logicalName2>"`
3. Log the command + result to `workflow-log.md`.
-Cross-env note (verified 2026-07-10): the app (80) pulls the sitemap (62); the
-GenPage `uxagentproject` (10372) is added explicitly and pulls its
-`uxagentprojectfile` rows (10373, incl. `config.json` with `connectorBindings`);
-each `connectionreference` (10158) is added so bindings resolve. At import the
+Cross-env note: the app (80) pulls the sitemap (62); the GenPage
+`uxagentproject` is added explicitly and pulls its `uxagentprojectfile` rows
+(including `config.json` with `connectorBindings`); each `connectionreference`
+is added so bindings resolve. The script discovers both custom-table component
+types from `EntityDefinitions(...).ObjectTypeCode` in the target environment —
+their numeric values are environment-specific and must never be hardcoded. At import the
deployer supplies env-specific `ConnectionId` per connection reference via
`pac solution create-settings` + `pac solution import --settings-file`.
Custom API bindings need **no** extra ALM step: `config.json`'s `actionBindings` travels
-automatically in the `uxagentprojectfile` (10373) rows already pulled with the GenPage. The
+automatically in the `uxagentprojectfile` rows already pulled with the GenPage. The
referenced Custom APIs are a separate deployment prerequisite (bound by `name`), not added here.
### Phase 7: Verify in Browser (Optional)
diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.md
index 0b1cf6c8c..bd8f96a78 100644
--- a/plugins/model-apps/skills/genpage/edit-flow.md
+++ b/plugins/model-apps/skills/genpage/edit-flow.md
@@ -10,6 +10,18 @@ to `genpage-edit-planner`, then applies the edit inline.
> sample app names, or anywhere else. Always run the commands first, then
> present what the commands returned to the user.
+> **⚠️ Unattended runs cannot select a target.** This flow **overwrites an
+> existing page**, and every selection step below is an `AskUserQuestion`. Under
+> Copilot autopilot or Claude auto-accept there is nobody to answer, and the one
+> thing an unattended run must never do is guess which page to overwrite.
+>
+> Resolve the mode as described in SKILL.md ("Unattended runs") before Phase 1.
+> When `interactive` is `false`, the app **and** the page must both be named
+> explicitly in `$ARGUMENTS`. Never substitute a search result, and never fall
+> back to "the only match" — a single match is still a guess when nobody asked
+> for it. If either is missing or ambiguous, **halt** and report what was needed.
+> Suppressing a prompt never authorizes an overwrite.
+
## Edit Phase 1: Discover and Select Target App + Page
The planner has already validated prereqs and confirmed auth.
@@ -106,7 +118,7 @@ pac model genpage generate-types `
Pass the exact entity list from `config.json.dataSources`. If `dataSources` is an
empty array, the page is mock-data only — skip this phase.
-Also read `config.json.connectorBindings`.
+Also read `config.json.connectorBindings` and `config.json.actionBindings`.
> **Connectors are owned by `genpage-connector-builder`, dispatched by this
> top-level edit orchestrator.** Unlike the create flow, the mode here is already
@@ -120,10 +132,17 @@ Also read `config.json.connectorBindings`.
> - **Add / replace / discover connector data:** invoke `genpage-connector-builder`
> via `Task` with **Mode: `edit`**, the working directory, `${PLUGIN_ROOT}`, the
> `envUrl` from Edit Phase 1, the existing bindings, and the edit intent. The
-> builder owns the feature gate: when connectors are OFF it preserves existing
-> bindings and adds none; when ON it discovers and returns the updated set. It
+> builder owns the rollback gate: when connectors are off it preserves existing
+> bindings and adds none; otherwise it discovers and returns the updated set. It
> writes `<working-dir>/connectors.json` (bare array) and
> `<working-dir>/connector-bindings.md`.
+> - **Remove one (or some) connectors:** invoke `genpage-connector-builder` the
+> same way with the remove intent and the existing bindings. The builder
+> reconciles the existing set **minus** the named binding(s) and writes the full
+> desired `connectors.json` (the remaining bindings, or `[]` if that removed the
+> last one) plus the matching `connector-bindings.md`. Pass `--connectors` on
+> upload — this is a full replace, so omitting it would leave the removed binding
+> deployed.
> - **Preserve connectors unchanged:** do not invoke the builder and do not create
> a replacement `connectors.json`; omit `--connectors` on upload so pac preserves
> deployed bindings. Still pass the existing `connectorBindings` summary into the
@@ -131,10 +150,65 @@ Also read `config.json.connectorBindings`.
> - **Clear all connectors:** write `[]` to `<working-dir>/connectors.json` and a
> `connector-bindings.md` body of exactly `No connector bindings.`, then pass
> `--connectors` during upload so pac clears `config.json.connectorBindings`.
+>
+> **The builder is headless and may return `{ "action": "needs_input", … }`** (for
+> example, an ambiguous connection or operation choice). When it does, drive the
+> same loop the create flow uses: ask each question with `AskUserQuestion`, record
+> every exchange in `workflow-log.md` as `AskUserQuestion: <question> → <answer>`,
+> and re-invoke the builder with the answers plus everything it already returned.
+> Do **not** continue to Edit Phase 4 until the builder returns its binding files —
+> proceeding on a `needs_input` return ships connector code with no matching binding.
+>
+> If `genpage-connector-builder` instead reports that its declared
+> process-execution or file tools are unavailable, do **not** retry the same worker. Record the failure,
+> read `agents/genpage-connector-builder.md`, and run the worker workflow inline
+> in this orchestrator with the already-captured edit mode, `envUrl`, existing
+> bindings, and edit intent. This inline fallback preserves every feature gate,
+> discovery rule, and mutation boundary from the agent file.
- Do not add or persist connection IDs. Env-specific `ConnectionId` values belong
to the connectionreference row and ALM deployment settings, not the page config.
+> **Custom APIs are owned by `genpage-customapi-builder`, dispatched by this same
+> top-level edit orchestrator.** Read the existing `config.json.actionBindings`
+> (the current Custom API bindings) and decide the Custom API action from the edit
+> intent. Custom API discovery is read-only, so like connectors it can run here,
+> before edit planning, when the intent already names a server-side Action/Function.
+> (If the need only surfaces during the edit planner's clarification, it returns
+> `custom_api_discovery_required` and discovery runs then — see Edit Phase 4.)
+>
+> - **Add / replace / discover a Custom API call:** invoke `genpage-customapi-builder`
+> via `Task` with **Mode: `edit`**, the working directory, `${PLUGIN_ROOT}`, the
+> `envUrl` from Edit Phase 1, the page tables from `config.json.dataSources` (or
+> `none`), the existing `actionBindings`, and the edit intent. The builder owns the
+> `custom-api` feature gate: when it is off it preserves existing bindings and adds
+> none; otherwise it discovers and returns the updated set. It writes
+> `<working-dir>/actions.json` (bare array) and `<working-dir>/custom-api-bindings.md`.
+> - **Remove one (or some) Custom API calls:** invoke the builder the same way with the
+> remove intent and the existing bindings. It reconciles the existing set **minus**
+> the named binding(s) and writes the full desired `actions.json` (the remaining
+> bindings, or `[]`) plus the matching `custom-api-bindings.md`. Pass `--actions` on
+> upload — a full replace, so omitting it would leave the removed binding deployed.
+> - **Preserve Custom APIs unchanged:** do not invoke the builder and do not create a
+> replacement `actions.json`; omit `--actions` on upload so pac preserves deployed
+> bindings. Still pass the existing `actionBindings` summary into the edit planner so
+> it can preserve Custom-API-backed code correctly.
+> - **Clear all Custom APIs:** write `[]` to `<working-dir>/actions.json` and a
+> `custom-api-bindings.md` body of exactly `No custom API bindings.`, then pass
+> `--actions` during upload so pac clears `config.json.actionBindings`.
+>
+> **The builder is headless and may return `{ "action": "needs_input", … }`** (for
+> example, when more than one discovered Custom API matches the intent). Drive the same
+> ask/record/re-invoke loop as for the connector builder above, and do **not** continue
+> to Edit Phase 4 until it returns its binding files — proceeding on a `needs_input`
+> return ships `executeAction`/`executeFunction` calls with no matching binding.
+>
+> If `genpage-customapi-builder` reports unavailable declared file or
+> process-execution tools, do **not** retry the same worker. Record the failure,
+> read `agents/genpage-customapi-builder.md`, and run its read-only discovery and
+> binding-output workflow inline with the same feature gate, environment, page
+> tables, existing bindings, and intent.
+
## Edit Phase 4: Plan the Edit
Invoke the `genpage-edit-planner` agent via the `Task` tool. Pass:
@@ -153,9 +227,16 @@ Invoke the `genpage-edit-planner` agent via the `Task` tool. Pass:
`config.json.connectorBindings` when preserving unchanged connectors
- The connector upload file status: `<working-dir>/connectors.json` when upload
must replace/clear bindings, or `none — omit --connectors` when preserving
+- The Custom API action: preserve, add, replace, discover, remove, or clear
+- The Custom API contract: the full body of `<working-dir>/custom-api-bindings.md`
+ when written by the builder/clear path, or a faithful summary of the existing
+ `config.json.actionBindings` when preserving unchanged Custom APIs
+- The Custom API upload file status: `<working-dir>/actions.json` when upload
+ must replace/clear bindings, or `none — omit --actions` when preserving
-Tell the planner that connector discovery is orchestrator-owned: it must use the
-forwarded connector contract and must not invoke `genpage-connector-builder`.
+Tell the planner that connector and Custom API discovery are both orchestrator-owned:
+it must use the forwarded connector and Custom API contracts and must not invoke
+`genpage-connector-builder` or `genpage-customapi-builder`.
**If the planner returns `{ "action": "connector_discovery_required", … }`** instead
of an edit plan, a connector need surfaced during its clarification — after the
@@ -166,9 +247,48 @@ contract, and upload-file status (`<working-dir>/connectors.json`). Skipping thi
ships connector code with no deployed binding, because upload would still omit
`--connectors`.
-The planner reads `page.tsx`, `config.json`, and `prompt.txt` for context, gathers
-any clarification from the user, presents the edit plan via plan mode, and writes
-`<working-dir>/genpage-edit-plan.md` on approval. Wait for it to finish.
+**If the planner returns `{ "action": "custom_api_discovery_required", … }`** instead
+of an edit plan, a Custom API need surfaced during its clarification — after the Custom
+API action was already fixed as "preserve". Do **not** proceed to Phase 5. Dispatch
+`genpage-customapi-builder` with **Mode: `edit`**, the returned `envUrl`, `pageTables`,
+and `intent`, then re-invoke the edit planner with the refreshed Custom API action,
+contract, and upload-file status (`<working-dir>/actions.json`). Skipping this ships
+`executeAction`/`executeFunction` code with no deployed binding, because upload would
+still omit `--actions`.
+
+The planner reads `page.tsx`, `config.json`, and `prompt.txt` for context and
+proposes the edit plan. It is a **headless** agent: it cannot ask the user anything
+and cannot present plan mode. Drive the loop from here until it completes:
+
+If `genpage-edit-planner` reports that its declared file tools are unavailable,
+do **not** retry the same worker and do not hand-write `genpage-edit-plan.md`.
+Halt the edit flow with the selected app/page and requested edit recorded. Plan
+provenance is a hard gate: unlike the pure discovery builders, the edit planner
+cannot be replaced by an inline fallback that invents its approved contract.
+
+- **`{ "action": "needs_input", "questions": [...] }`** — ask each question with
+ `AskUserQuestion` in this loop, record every exchange in `workflow-log.md` as
+ `AskUserQuestion: <question> → <answer>`, then re-invoke the planner with the
+ answers plus everything it already returned. Repeat as needed; each round must
+ carry the previous answers forward so the planner never re-asks the same thing.
+- **`{ "action": "connector_discovery_required", … }`** — handled above.
+- **`{ "action": "custom_api_discovery_required", … }`** — handled above.
+- **A proposed plan** — present it with `EnterPlanMode`, record `EnterPlanMode
+ called` and the response in `workflow-log.md`, and call `ExitPlanMode` to get
+ approval. A re-invocation is a fresh headless run with no memory of the last one,
+ so **carry the complete plan state forward every time** — the exact proposed-plan
+ body it returned, every prior discovery (connector and Custom API contracts,
+ entities), and every answer already gathered. On **approval**, re-invoke the
+ planner with that full state plus the approval outcome so it writes the approved
+ `<working-dir>/genpage-edit-plan.md` — not a plan it re-derives from scratch. On
+ **changes requested**, re-invoke it with the same full state plus the requested
+ revisions and present the revised plan again. Forwarding only the outcome lets it
+ reconstruct a different plan or re-ask answered questions (same rule as the create
+ flow's Phase 1 step 6).
+
+Only continue to Phase 5 once `<working-dir>/genpage-edit-plan.md` exists — that
+file is the approved contract Phase 5 reads, and reaching Phase 5 without it means
+applying an edit nobody approved.
## Edit Phase 5: Apply the Edit
@@ -194,6 +314,12 @@ or approved edit plan when the edit touches connector data access.
Do NOT rewrite the entire file. Use the minimum necessary `Edit` operations.
+Before Edit Phase 6, Grep the edited `page.tsx` with
+`['"]?borderWidth['"]?\s*:`. Griffel rejects that shorthand only at runtime;
+the regex also catches quoted keys and whitespace before the colon. Replace every match with
+`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and
+`borderLeftWidth`. Do not upload while any match remains.
+
## Edit Phase 6: Deploy Updated Page
This is an **update** (existing page-id), so `--prompt` must describe the
@@ -201,17 +327,31 @@ This is an **update** (existing page-id), so `--prompt` must describe the
See SKILL.md Phase 6 "`--prompt` semantics".
Connector binding rules for edit deploy:
-- **Add / replace / discover connectors:** the `genpage-connector-builder` agent
- (Mode: `edit`) has already gated on the flag and written the full desired binding
- set to `<working-dir>/connectors.json`. Pre-flight that `pac model genpage upload
- --help` contains `--connectors` and include `--connectors "<working-dir>/connectors.json"`
- in the upload.
+- **Add / replace / discover / remove one connector:** the `genpage-connector-builder`
+ agent (Mode: `edit`) has already gated on the flag and written the full desired
+ binding set to `<working-dir>/connectors.json` (a removal writes the remaining
+ bindings). Pre-flight that `pac model genpage upload --help` contains `--connectors`
+ and include `--connectors "<working-dir>/connectors.json"` in the upload — this is a
+ full replace, so it also deletes any binding left out of the file.
- **Code/visual-only edit (connectors unchanged):** omit `--connectors`; pac
preserves existing bindings.
- **Remove every connector:** write `[]` to `connectors.json` and pass
`--connectors` so pac clears `config.json.connectorBindings`.
- Never write connection IDs.
+Custom API binding rules for edit deploy (identical matrix, `--actions` for
+`<working-dir>/actions.json`):
+- **Add / replace / discover / remove one Custom API:** the `genpage-customapi-builder`
+ agent (Mode: `edit`) has already gated on the flag and written the full desired binding
+ set to `<working-dir>/actions.json` (a removal writes the remaining bindings). Pre-flight
+ that `pac model genpage upload --help` contains `--actions` and include
+ `--actions "<working-dir>/actions.json"` in the upload — a full replace that also deletes
+ any binding left out of the file.
+- **Code/visual-only edit (Custom APIs unchanged):** omit `--actions`; pac preserves
+ existing `actionBindings`.
+- **Remove every Custom API:** write `[]` to `actions.json` and pass `--actions` so pac
+ clears `config.json.actionBindings`.
+
```powershell
pac model genpage upload `
--app-id <app-id> `
@@ -219,6 +359,7 @@ pac model genpage upload `
--code-file <working-dir>/<page-id>/page.tsx `
--data-sources "entity1,entity2" `
--connectors "<working-dir>/connectors.json" `
+ --actions "<working-dir>/actions.json" `
--prompt "<User's edit request — only the changes, not the full page>" `
--model "<current-model-id>" `
--agent-message "Description of what was changed in this upload"
@@ -228,6 +369,7 @@ Use `--page-id` for updates. Omit `--add-to-sitemap` (the page is already in
the sitemap).
Omit `--data-sources` when `config.json.dataSources` was empty.
Omit `--connectors` when connector bindings are unchanged.
+Omit `--actions` when Custom API bindings are unchanged.
## Edit Phase 7: Verify (Optional)
diff --git a/plugins/model-apps/skills/report-issue/SKILL.md b/plugins/model-apps/skills/report-issue/SKILL.md
index f833ee21d..55f7e37a3 100644
--- a/plugins/model-apps/skills/report-issue/SKILL.md
+++ b/plugins/model-apps/skills/report-issue/SKILL.md
@@ -6,7 +6,7 @@ description: >
with the model-apps plugin to the GitHub repository.
user-invocable: true
argument-hint: "[optional: brief description of the bug]"
-allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, read, execute, search, todo
model: sonnet
---
diff --git a/plugins/model-apps/skills/telemetry/SKILL.md b/plugins/model-apps/skills/telemetry/SKILL.md
index f33e2cbab..f767b23bb 100644
--- a/plugins/model-apps/skills/telemetry/SKILL.md
+++ b/plugins/model-apps/skills/telemetry/SKILL.md
@@ -7,7 +7,7 @@ description: >
telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".
user-invocable: true
argument-hint: "on | off | status"
-allowed-tools: Bash
+allowed-tools: Bash, execute
model: haiku
---
diff --git a/scripts/tests/validate-agent-interactivity.test.js b/scripts/tests/validate-agent-interactivity.test.js
new file mode 100644
index 000000000..382698caf
--- /dev/null
+++ b/scripts/tests/validate-agent-interactivity.test.js
@@ -0,0 +1,291 @@
+// Guards the guard. validate-agent-interactivity.js exists because an agent declaring an
+// interactive tool specifies a flow that CANNOT complete — a Task subagent is headless, so the
+// question is never answered — and nothing else in the repo reads agent frontmatter. The
+// /genpage Phase 1 contradiction survived ~2.5 months for exactly that reason, so the cases that
+// matter most are the ones asserting this does not stay silent.
+
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const {
+ frontmatterOf,
+ interactiveToolsIn,
+ selfInteractionProseIn,
+ undeclaredSkillTools,
+ declaredToolsIn,
+ unportableToolsIn,
+ agentFiles,
+ skillFiles,
+ INTERACTIVE_TOOLS,
+ SCAN_PATHS,
+ SKILL_SCAN_PATHS,
+} = require('../validate-agent-interactivity.js');
+
+const ROOT = path.resolve(__dirname, '..', '..');
+
+test('a headless agent passes', () => {
+ const fm = 'name: worker\ntools:\n - Read\n - Write\n - Bash';
+ assert.deepEqual(interactiveToolsIn(fm), []);
+});
+
+test('each interactive tool is detected on its own', () => {
+ for (const tool of INTERACTIVE_TOOLS) {
+ assert.deepEqual(interactiveToolsIn(`tools:\n - Read\n - ${tool}`), [tool], tool);
+ }
+});
+
+test('all three are reported together, so one run names every problem in a file', () => {
+ const fm = 'tools:\n - Read\n - EnterPlanMode\n - ExitPlanMode\n - AskUserQuestion';
+ assert.deepEqual(interactiveToolsIn(fm).sort(), ['AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode']);
+});
+
+test('the inline / comma-separated tool form is caught too', () => {
+ assert.deepEqual(interactiveToolsIn('allowed-tools: Read, Write, AskUserQuestion'), ['AskUserQuestion']);
+});
+
+// A substring must not trip it: an agent legitimately named or describing something like
+// "AskUserQuestionnaireBuilder" is not declaring the tool.
+test('matching is word-bounded, not substring', () => {
+ assert.deepEqual(interactiveToolsIn('tools:\n - AskUserQuestionnaire'), []);
+ assert.deepEqual(interactiveToolsIn('tools:\n - MyEnterPlanModeHelper'), []);
+});
+
+// The frontmatter extractor must stop at the FIRST closing `---`, but it must not be fooled by a
+// markdown horizontal rule in the BODY into reading further — nor stop early and miss a
+// declaration. Several agents use `---` as a section break.
+test('frontmatterOf reads only the leading block, and a body rule does not extend it', () => {
+ const doc = ['---', 'name: a', 'tools:', ' - Read', '---', '', '# Body', '', '---', '', 'tools:', ' - AskUserQuestion'].join('\n');
+ const fm = frontmatterOf(doc);
+ assert.match(fm, /name: a/);
+ assert.doesNotMatch(fm, /AskUserQuestion/, 'a declaration below a body rule is not frontmatter');
+});
+
+test('a file with no frontmatter yields an empty block rather than throwing', () => {
+ assert.strictEqual(frontmatterOf('# Just a heading\n'), '');
+ assert.strictEqual(frontmatterOf(''), '');
+});
+
+test('an unterminated frontmatter block yields empty rather than swallowing the file', () => {
+ assert.strictEqual(frontmatterOf('---\nname: a\ntools:\n - AskUserQuestion\n'), '');
+});
+
+// The real repository must satisfy the rule — this is what actually fails a PR.
+test('every scanned agent in the repo is headless', () => {
+ let checked = 0;
+ for (const rel of SCAN_PATHS) {
+ const files = agentFiles(path.join(ROOT, rel));
+ assert.ok(files.length > 0, `expected agents under ${rel}`);
+ for (const f of files) {
+ checked += 1;
+ const found = interactiveToolsIn(frontmatterOf(fs.readFileSync(f, 'utf8')));
+ assert.deepEqual(found, [], `${path.relative(ROOT, f)} declares ${found.join(', ')}`);
+ }
+ }
+ assert.ok(checked >= 6, `expected to scan the genpage agents, scanned ${checked}`);
+});
+
+// The scope is deliberately narrow (other plugins still carry these declarations). Pinning it
+// means widening the scan is a conscious edit with a test change, not an accident.
+test('the scan scope is explicit', () => {
+ assert.deepEqual(SCAN_PATHS, [path.join('plugins', 'model-apps', 'agents')]);
+});
+
+// The mirror-image defect. Moving interaction OUT of an agent and INTO the skill's main loop only
+// works if the skill is ALLOWED to interact — /genpage was rewritten to call plan mode in the main
+// loop while its allowed-tools declared neither tool, moving the flow to a second context that
+// could not perform it either.
+test('a skill that uses an interactive tool but does not declare it is flagged', () => {
+ const doc = [
+ '---',
+ 'name: x',
+ 'allowed-tools: Read, Write, Task',
+ '---',
+ '',
+ 'Present the plan with `EnterPlanMode` and approve via `ExitPlanMode`.',
+ ].join('\n');
+ assert.deepEqual(undeclaredSkillTools(doc).sort(), ['EnterPlanMode', 'ExitPlanMode']);
+});
+
+test('a skill that declares what it uses passes', () => {
+ const doc = [
+ '---',
+ 'name: x',
+ 'allowed-tools: Read, Write, Task, AskUserQuestion, EnterPlanMode, ExitPlanMode',
+ '---',
+ '',
+ 'Ask with `AskUserQuestion`, present with `EnterPlanMode`, approve with `ExitPlanMode`.',
+ ].join('\n');
+ assert.deepEqual(undeclaredSkillTools(doc), []);
+});
+
+test('a skill that mentions no interactive tool needs no declaration', () => {
+ const doc = ['---', 'name: x', 'allowed-tools: Read, Bash', '---', '', 'Run the script.'].join('\n');
+ assert.deepEqual(undeclaredSkillTools(doc), []);
+});
+
+// The frontmatter's own declaration must not be mistaken for body usage, or every correctly
+// declared skill would report itself.
+test('the declaration in the frontmatter is not counted as body usage', () => {
+ const doc = ['---', 'allowed-tools: Read, AskUserQuestion', '---', '', 'No tool mentioned here.'].join('\n');
+ assert.deepEqual(undeclaredSkillTools(doc), []);
+});
+
+// Every real skill in the scanned plugin must satisfy it — this is what fails the PR.
+test('every scanned skill declares the interactive tools it uses', () => {
+ for (const rel of SKILL_SCAN_PATHS) {
+ const files = skillFiles(path.join(ROOT, rel));
+ assert.ok(files.length > 0, `expected skills under ${rel}`);
+ for (const f of files) {
+ const missing = undeclaredSkillTools(fs.readFileSync(f, 'utf8'));
+ assert.deepEqual(missing, [], `${path.relative(ROOT, f)} uses but does not declare ${missing.join(', ')}`);
+ }
+ }
+});
+
+// The tool-name check cannot see prose. Both planner agents described themselves as presenting
+// "a plan for user approval via plan mode" while their own bodies correctly said the orchestrator
+// does it — and `description` is the sentence the dispatching model reads, so it is the one most
+// likely to be acted on. Scoped to frontmatter, which carries only name/description/color/tools.
+test('frontmatter prose claiming the agent itself interacts is rejected', () => {
+ const doc = [
+ '---',
+ 'name: some-planner',
+ 'description: >-',
+ ' Gathers requirements and presents a plan for user approval via plan mode.',
+ 'tools: Read, Write',
+ '---',
+ '# Body',
+ ].join('\n');
+ assert.deepEqual(selfInteractionProseIn(frontmatterOf(doc)), ['/\\bplan mode\\b/i']);
+});
+
+test('a frontmatter that describes what the agent RETURNS is accepted', () => {
+ const doc = [
+ '---',
+ 'name: some-planner',
+ 'description: >-',
+ ' Gathers requirements and returns a proposed plan for the orchestrator to present.',
+ 'tools: Read, Write',
+ '---',
+ '# Body: the orchestrator presents it with EnterPlanMode and reports the outcome.',
+ ].join('\n');
+ assert.deepEqual(selfInteractionProseIn(frontmatterOf(doc)), []);
+});
+
+// A BODY may freely say the orchestrator uses plan mode — that is the correct statement, and
+// flagging it would push authors to stop documenting the contract.
+test('body prose about plan mode is not flagged', () => {
+ const doc = ['---', 'name: a', 'description: Returns a plan.', 'tools: Read', '---',
+ 'The orchestrator presents this in plan mode and asks the user to approve.'].join('\n');
+ assert.deepEqual(selfInteractionProseIn(frontmatterOf(doc)), []);
+});
+
+// Every real agent in the scanned plugin must satisfy it — this is what fails the PR.
+test('no scanned agent claims in its frontmatter that it interacts', () => {
+ for (const rel of SCAN_PATHS) {
+ const files = agentFiles(path.join(ROOT, rel));
+ assert.ok(files.length > 0, `expected agents under ${rel}`);
+ for (const f of files) {
+ const prose = selfInteractionProseIn(frontmatterOf(fs.readFileSync(f, 'utf8')));
+ assert.deepEqual(prose, [], `${path.relative(ROOT, f)} frontmatter matched ${prose.join(', ')}`);
+ }
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Cross-host tool portability — the second silent failure mode in the same frontmatter.
+//
+// Tool names are host-specific and every host IGNORES a name it does not recognize instead of
+// reporting it, so a capability named only in a scheme the running host does not know is simply
+// absent. The agent launches and then cannot run `node` or track progress, with nothing in any
+// log explaining why. That is the same fail-silent shape as the interactivity defect above,
+// which is why it is guarded in the same place.
+
+test('Claude names that Copilot publishes as compatible aliases are accepted as-is', () => {
+ // Read/Write/Bash ARE documented Copilot aliases, so they are already portable. A check that
+ // cried wolf here would be tuned out, and the real defect below would go with it.
+ assert.deepEqual(unportableToolsIn('tools:\n - Read\n - Write\n - Bash'), []);
+});
+
+test('TaskCreate/TaskUpdate/TaskList alone are flagged — no host but Claude Code knows them', () => {
+ const problems = unportableToolsIn('tools:\n - Read\n - TaskCreate\n - TaskUpdate\n - TaskList');
+ assert.equal(problems.length, 1, problems.join('; '));
+ assert.match(problems[0], /unknown to Copilot/);
+ assert.match(problems[0], /declare 'todo'/);
+});
+
+test('adding the portable todo alias clears it', () => {
+ assert.deepEqual(unportableToolsIn('tools:\n - Read\n - TaskCreate\n - todo'), []);
+});
+
+test('a Copilot-only declaration is flagged as invisible to Claude Code', () => {
+ const problems = unportableToolsIn('tools:\n - execute\n - todo');
+ assert.equal(problems.length, 2, problems.join('; '));
+ assert.ok(problems.every((p) => /unknown to Claude Code/.test(p)), problems.join('; '));
+});
+
+test('a host-specific namespaced tool name carries no assertion', () => {
+ // `execute/runInTerminal` is a real Copilot CLI tool id. It is in neither table, and because
+ // unrecognized names are ignored everywhere, declaring one is deliberately allowed.
+ assert.deepEqual(unportableToolsIn("tools: ['execute/runInTerminal', 'read/readFile']"), []);
+});
+
+test('tool names mentioned in YAML comments are not read as declarations', () => {
+ // The real agent frontmatter explains in a comment WHY both schemes are present, and names
+ // TaskCreate/TaskUpdate/TaskList while doing so. Reading those as declared would make a file
+ // pass or fail for reasons unrelated to what it actually grants.
+ const fm = [
+ '# TaskCreate/TaskUpdate/TaskList are NOT aliases anywhere - todo is the portable name.',
+ 'tools:',
+ ' - Read',
+ ' - todo # portable name',
+ ].join('\n');
+ assert.deepEqual(declaredToolsIn(fm), ['Read', 'todo']);
+});
+
+test('the inline comma form parses like the block form', () => {
+ assert.deepEqual(declaredToolsIn('allowed-tools: Read, Write, Bash'), ['Read', 'Write', 'Bash']);
+});
+
+test('the tool block ends at the next frontmatter key', () => {
+ const fm = 'tools:\n - Read\n - todo\ncolor: green\ndescription: not a tool';
+ assert.deepEqual(declaredToolsIn(fm), ['Read', 'todo']);
+});
+
+// Every real agent must satisfy it — this is what fails the PR.
+test('every scanned agent declares each capability in a form both hosts recognize', () => {
+ for (const rel of SCAN_PATHS) {
+ const files = agentFiles(path.join(ROOT, rel));
+ assert.ok(files.length > 0, `expected agents under ${rel}`);
+ for (const f of files) {
+ const problems = unportableToolsIn(frontmatterOf(fs.readFileSync(f, 'utf8')));
+ assert.deepEqual(problems, [], `${path.relative(ROOT, f)}: ${problems.join('; ')}`);
+ }
+ }
+});
+
+// A skill's allowed-tools is the same kind of host-specific allow-list and fails the same silent
+// way — /genpage and /app-builder both track progress through TaskCreate/TaskUpdate/TaskList,
+// which no Copilot host recognizes.
+test('every scanned skill declares each capability in a form both hosts recognize', () => {
+ for (const rel of SKILL_SCAN_PATHS) {
+ const files = skillFiles(path.join(ROOT, rel));
+ assert.ok(files.length > 0, `expected skills under ${rel}`);
+ for (const f of files) {
+ const problems = unportableToolsIn(frontmatterOf(fs.readFileSync(f, 'utf8')));
+ assert.deepEqual(problems, [], `${path.relative(ROOT, f)}: ${problems.join('; ')}`);
+ }
+ }
+});
+
+// The interactive tools have no portable equivalent — they are Claude-only names and there is
+// nothing to declare alongside them. They must therefore carry NO portability assertion, or every
+// skill that legitimately asks the user would fail this check.
+test('interactive tool names carry no portability assertion', () => {
+ assert.deepEqual(
+ unportableToolsIn('allowed-tools: Read, read, AskUserQuestion, EnterPlanMode, ExitPlanMode'),
+ []
+ );
+});
diff --git a/scripts/validate-agent-interactivity.js b/scripts/validate-agent-interactivity.js
new file mode 100644
index 000000000..9024f2790
--- /dev/null
+++ b/scripts/validate-agent-interactivity.js
@@ -0,0 +1,338 @@
+#!/usr/bin/env node
+
+/**
+ * Validates that no plugin agent declares a tool that only works in an
+ * INTERACTIVE session.
+ *
+ * WHY: agents under `plugins/<plugin>/agents/` are dispatched as `Task`
+ * subagents, and a subagent is HEADLESS — `AskUserQuestion`, `EnterPlanMode`
+ * and `ExitPlanMode` never reach the user from inside one. An agent that
+ * declares them is specifying a flow that cannot complete: the subagent stalls
+ * or silently skips the question, and the parent gets an answer nobody gave.
+ *
+ * This is not hypothetical. `/genpage` Phase 1 was specified to run its entire
+ * interactive flow — prereqs, auth, the "create new / edit existing" question
+ * and plan-mode approval — inside the `genpage-planner` subagent, while the same
+ * plugin's AGENTS.md documented that subagents are headless and `/app-builder`
+ * enforced the opposite rule. There was no compliant path through Phase 1, so
+ * create flows could not complete (issue #541). The contradiction survived ~2.5
+ * months because nothing checked for it: the frontmatter is prose to every test
+ * in the repo.
+ *
+ * The rule is therefore: interaction belongs to the MAIN conversation loop. An
+ * agent that needs input returns a structured REQUEST for it and the parent asks.
+ *
+ * SCOPE: model-apps only, and that is deliberate rather than an oversight.
+ * `mobile-apps` and `power-pages` currently ship agents with the same
+ * declarations; widening the scan today would fail PRs that have nothing to do
+ * with this. Scrub a plugin, then add it to SCAN_PATHS — the same staged
+ * approach `validate-no-real-environments.js` takes.
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const ROOT = path.resolve(__dirname, '..');
+
+// Add a plugin here only once its agents are scrubbed (see SCOPE above).
+const SCAN_PATHS = [path.join('plugins', 'model-apps', 'agents')];
+
+// Skills whose main loop owns the interaction, checked for the mirror-image defect below.
+const SKILL_SCAN_PATHS = [path.join('plugins', 'model-apps', 'skills')];
+
+// Tools that require a human on the other end of the conversation.
+const INTERACTIVE_TOOLS = ['AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode'];
+
+// Tool names are HOST-SPECIFIC, and every host silently IGNORES a name it does not
+// recognize rather than reporting it. That fail-silent behaviour is exactly why this needs
+// a machine check: a capability named only in a scheme the running host does not know is
+// simply absent, and the first symptom is a subagent that cannot run `node` or write a file
+// — with nothing in any log saying why.
+// Copilot: "All unrecognized tool names are ignored, which allows product-specific tools to
+// be specified in an agent profile without causing problems."
+// https://docs.github.com/en/copilot/reference/custom-agents-configuration#tool-aliases
+// Claude Code behaves the same way: https://github.com/anthropics/claude-code/issues/93171
+//
+// Capability -> the Claude Code tool names that provide it. These are the names a Claude host
+// recognizes; a capability declared ONLY as a Copilot primary alias (`execute`) is dropped there.
+const CLAUDE_NAMES_FOR = {
+ read: ['Read', 'NotebookRead'],
+ edit: ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'],
+ execute: ['Bash'],
+ search: ['Grep', 'Glob'],
+ agent: ['Task'],
+ web: ['WebSearch', 'WebFetch'],
+ // TaskCreate/TaskUpdate/TaskList are this repo's Claude-side todo tools.
+ todo: ['TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList'],
+};
+
+// Every tool name a Copilot host recognizes: the primary aliases plus the published
+// compatible aliases, matched case-insensitively ("All aliases are case insensitive").
+// NOTE the omissions that make this check worth having: TaskCreate, TaskUpdate and TaskList
+// appear in NO published alias table, so on a Copilot host they are silently dropped and the
+// agent loses progress tracking unless `todo` is also declared.
+const COPILOT_RECOGNIZED = new Set(
+ [
+ 'read', 'Read', 'NotebookRead',
+ 'edit', 'Edit', 'MultiEdit', 'Write', 'NotebookEdit',
+ 'execute', 'shell', 'Bash', 'powershell',
+ 'search', 'Grep', 'Glob',
+ 'agent', 'custom-agent', 'Task',
+ 'web', 'WebSearch', 'WebFetch',
+ 'todo', 'TodoWrite',
+ ].map((n) => n.toLowerCase())
+);
+
+// Claude-name -> capability, derived so the two tables cannot drift apart.
+const CAPABILITY_OF = Object.entries(CLAUDE_NAMES_FOR).reduce((acc, [capability, names]) => {
+ for (const n of names) acc[n] = capability;
+ return acc;
+}, {});
+
+// Pull the YAML frontmatter block out of an agent .md. Returns '' when the file
+// has no frontmatter, which is itself not an error here — this check is only
+// about what a declared tool list contains.
+function frontmatterOf(text) {
+ // Frontmatter is the region between the FIRST `---` line and the next one.
+ // Matched line-wise rather than with a lazy regex so a `---` inside the body
+ // (a markdown horizontal rule, which several agents use) cannot terminate it
+ // early and hide a declaration below.
+ const lines = text.split(/\r?\n/);
+ if (lines[0] !== '---') return '';
+ const end = lines.indexOf('---', 1);
+ if (end === -1) return '';
+ return lines.slice(1, end).join('\n');
+}
+
+// Returns the interactive tools declared by one agent's frontmatter.
+// Exported so the test can exercise the rule without touching the filesystem.
+function interactiveToolsIn(frontmatter) {
+ // The tool list is YAML, in either the block form
+ // tools:
+ // - Read
+ // - AskUserQuestion
+ // or an inline/comma form (`allowed-tools: Read, Write, AskUserQuestion`).
+ // A word-boundary match over the whole frontmatter covers both without
+ // parsing YAML, and the names are distinctive enough that a false positive
+ // would require an agent to mention the tool in its `description` — which is
+ // itself worth flagging, since the description is what the model reads.
+ return INTERACTIVE_TOOLS.filter((t) => new RegExp(`\\b${t}\\b`).test(frontmatter));
+}
+
+// Prose that claims the agent itself interacts, written WITHOUT naming a tool — so the
+// tool-name check above cannot see it. Both planner agents described themselves as presenting
+// "a plan for user approval via plan mode" while their own bodies correctly said the orchestrator
+// does it; the `description` is what the dispatching model reads, so it is the sentence most
+// likely to be acted on.
+//
+// Scoped to frontmatter, which carries only name/description/color/tools — there is no legitimate
+// reason for any of those to mention plan mode or asking the user. A body may freely say
+// "the orchestrator presents it with EnterPlanMode", and that is correct, so bodies are not scanned.
+const SELF_INTERACTION_PROSE = [/\bplan mode\b/i, /\basks? the user\b/i, /\bprompts? the user\b/i];
+
+function selfInteractionProseIn(frontmatter) {
+ return SELF_INTERACTION_PROSE.filter((re) => re.test(frontmatter)).map((re) => String(re));
+}
+
+// Strip YAML comments before reading the tool list. These frontmatter blocks deliberately
+// NAME tool aliases in their comments to explain why both naming schemes are present, so a
+// plain regex over the raw text would read those explanations as declarations.
+// Only whole-line and trailing comments are stripped; no value in this frontmatter is a
+// quoted string containing '#', so there is nothing subtler to handle.
+function stripYamlComments(frontmatter) {
+ return frontmatter
+ .split(/\r?\n/)
+ .map((line) => line.replace(/(^|\s)#.*$/, ''))
+ .join('\n');
+}
+
+// Returns every tool name a frontmatter declares, across the two forms in use here:
+// tools: allowed-tools: Read, Write, Bash
+// - Read tools: ['read/readFile', 'execute/runInTerminal']
+// - Write
+// Quotes and list brackets are stripped so the inline array form parses like the comma form.
+function declaredToolsIn(frontmatter) {
+ const lines = stripYamlComments(frontmatter).split(/\r?\n/);
+ const tools = [];
+ let inBlock = false;
+ for (const line of lines) {
+ const inline = line.match(/^(?:tools|allowed-tools)\s*:\s*(\S.*)$/);
+ if (inline) {
+ tools.push(
+ ...inline[1]
+ .replace(/[[\]'"]/g, '')
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean)
+ );
+ inBlock = false;
+ continue;
+ }
+ if (/^(?:tools|allowed-tools)\s*:\s*$/.test(line)) {
+ inBlock = true;
+ continue;
+ }
+ if (inBlock) {
+ const item = line.match(/^\s*-\s*(\S.*?)\s*$/);
+ if (item) {
+ tools.push(item[1].replace(/['"]/g, ''));
+ continue;
+ }
+ // Any non-list line at column 0 ends the block (the next frontmatter key).
+ if (/^\S/.test(line)) inBlock = false;
+ }
+ }
+ return tools;
+}
+
+// Returns capabilities that are declared in a way one host cannot see, as human-readable
+// problems. A one-sided declaration is not a style nit: the host that does not recognize the
+// declared name drops it silently, and the agent runs without that capability.
+function unportableToolsIn(frontmatter) {
+ const declared = declaredToolsIn(frontmatter);
+ const primaryAliases = new Set(Object.keys(CLAUDE_NAMES_FOR));
+
+ // Group every declared name under the capability it provides, so each capability is judged
+ // on the whole set of names declared for it rather than name by name.
+ const byCapability = new Map();
+ for (const tool of declared) {
+ const capability = primaryAliases.has(tool.toLowerCase())
+ ? tool.toLowerCase()
+ : CAPABILITY_OF[tool];
+ // A name in neither table (a host-specific tool, e.g. `execute/runInTerminal`) carries no
+ // assertion: it is deliberately allowed, since unrecognized names are ignored everywhere.
+ if (!capability) continue;
+ if (!byCapability.has(capability)) byCapability.set(capability, []);
+ byCapability.get(capability).push(tool);
+ }
+
+ const problems = [];
+ for (const [capability, names] of byCapability) {
+ if (!names.some((n) => CLAUDE_NAMES_FOR[capability].includes(n))) {
+ problems.push(
+ `${names.join('/')} (${capability}) is unknown to Claude Code — also declare one of ` +
+ CLAUDE_NAMES_FOR[capability].join('/')
+ );
+ }
+ if (!names.some((n) => COPILOT_RECOGNIZED.has(n.toLowerCase()))) {
+ problems.push(
+ `${names.join('/')} (${capability}) is unknown to Copilot — also declare '${capability}'`
+ );
+ }
+ }
+ return problems;
+}
+
+function agentFiles(dir) {
+ if (!fs.existsSync(dir)) return [];
+ return fs
+ .readdirSync(dir, { withFileTypes: true })
+ .filter((e) => e.isFile() && e.name.endsWith('.md'))
+ .map((e) => path.join(dir, e.name));
+}
+
+// The mirror-image defect, and the one that makes the fix for the first incomplete: moving
+// interaction OUT of an agent and INTO the skill's main loop only works if the skill is allowed to
+// interact. `/genpage` was rewritten to call `EnterPlanMode`/`ExitPlanMode` in the main loop while
+// its `allowed-tools` still listed neither — the flow was moved to a context that also could not
+// perform it. Nothing catches that either: a skill body is prose.
+//
+// The rule: a SKILL.md whose body tells the reader to use an interactive tool must DECLARE it.
+// A body that merely quotes the tool name (the `workflow-log.md` line format is
+// `AskUserQuestion: <q> → <a>`) also trips this, and that is fine — a skill documenting that format
+// is a skill that asks questions, so the declaration is correct anyway.
+function skillFiles(dir) {
+ if (!fs.existsSync(dir)) return [];
+ return fs
+ .readdirSync(dir, { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => path.join(dir, e.name, 'SKILL.md'))
+ .filter((f) => fs.existsSync(f));
+}
+
+// Returns the interactive tools a skill USES in its body but does not DECLARE in its frontmatter.
+function undeclaredSkillTools(text) {
+ const fm = frontmatterOf(text);
+ const body = fm ? text.slice(text.indexOf(fm) + fm.length) : text;
+ const declared = new Set(interactiveToolsIn(fm));
+ return INTERACTIVE_TOOLS.filter((t) => new RegExp(`\\b${t}\\b`).test(body) && !declared.has(t));
+}
+
+function main() {
+ const errors = [];
+ let checked = 0;
+
+ for (const rel of SCAN_PATHS) {
+ for (const filePath of agentFiles(path.join(ROOT, rel))) {
+ checked += 1;
+ const fm = frontmatterOf(fs.readFileSync(filePath, 'utf8'));
+ const found = interactiveToolsIn(fm);
+ if (found.length) {
+ errors.push(
+ `${path.relative(ROOT, filePath).replace(/\\/g, '/')}: declares ${found.join(', ')} — ` +
+ 'an agent runs as a headless Task subagent, so these never reach the user. ' +
+ 'Ask in the main conversation loop and have the agent return a structured request instead.'
+ );
+ }
+ const prose = selfInteractionProseIn(fm);
+ if (prose.length) {
+ errors.push(
+ `${path.relative(ROOT, filePath).replace(/\\/g, '/')}: frontmatter claims the agent itself ` +
+ `interacts (matched ${prose.join(', ')}) — the description is what the dispatching model reads, ` +
+ 'and a headless subagent cannot present plan mode or ask the user. Describe what it RETURNS ' +
+ 'and say the orchestrator presents it.'
+ );
+ }
+ const unportable = unportableToolsIn(fm);
+ if (unportable.length) {
+ errors.push(
+ `${path.relative(ROOT, filePath).replace(/\\/g, '/')}: declares ${unportable.join('; ')} — ` +
+ 'tool names are host-specific and every host silently IGNORES a name it does not ' +
+ 'recognize, so a capability named in only one scheme is simply absent on the other ' +
+ 'host and the agent runs without it. Declare both names for the capability.'
+ );
+ }
+ }
+ }
+
+ for (const rel of SKILL_SCAN_PATHS) {
+ for (const filePath of skillFiles(path.join(ROOT, rel))) {
+ checked += 1;
+ const text = fs.readFileSync(filePath, 'utf8');
+ const missing = undeclaredSkillTools(text);
+ if (missing.length) {
+ errors.push(
+ `${path.relative(ROOT, filePath).replace(/\\/g, '/')}: uses ${missing.join(', ')} in its body ` +
+ 'but does not declare it in allowed-tools — the flow would be moved to a loop that cannot ' +
+ 'perform it. Add the tool to the frontmatter.'
+ );
+ }
+ // A skill's allowed-tools is the same kind of host-specific allow-list as an agent's, and
+ // fails the same silent way: `/genpage` and `/app-builder` both track progress through
+ // TaskCreate/TaskUpdate/TaskList, which no Copilot host recognizes.
+ const unportable = unportableToolsIn(frontmatterOf(text));
+ if (unportable.length) {
+ errors.push(
+ `${path.relative(ROOT, filePath).replace(/\\/g, '/')}: declares ${unportable.join('; ')} — ` +
+ 'tool names are host-specific and every host silently IGNORES a name it does not ' +
+ 'recognize, so a capability named in only one scheme is simply absent on the other ' +
+ 'host. Declare both names for the capability.'
+ );
+ }
+ }
+ }
+
+ if (errors.length > 0) {
+ console.log('Agent interactivity validation failed:');
+ for (const error of errors) console.log(`- ${error}`);
+ process.exit(1);
+ }
+
+ console.log(`Checked ${checked} agent/skill file(s): agents are headless, every skill declares the interactive tools it uses, and every agent and skill capability is declared in a form both hosts recognize.`);
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = { frontmatterOf, interactiveToolsIn, selfInteractionProseIn, undeclaredSkillTools, stripYamlComments, declaredToolsIn, unportableToolsIn, agentFiles, skillFiles, INTERACTIVE_TOOLS, CLAUDE_NAMES_FOR, COPILOT_RECOGNIZED, CAPABILITY_OF, SCAN_PATHS, SKILL_SCAN_PATHS };