A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.19.0: changed-only binding fix (2.18.0 regression), one apply at a time, a retry after a new table's lag, key conflicts, generic-arrow pages, a wider token guard (#766)
Akshay Maloo9d2486d27d93
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdindex 4f8d18557..e3a0e669c 100644--- a/evals/model-apps/genpage/EVAL_GUIDE.md+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -80,6 +80,10 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual quadirectory. Environment/app checks use that producer, not unrelated same-ID downloads elsewhere;unmatched or ambiguous producers refuse preservation rather than guessing a historical source.- Prefix discipline holds across plan, entity-creation log, and resolved names+- An auth blocker the eval names (`az_not_logged_in`, `whoami_403`) is read from check-auth.js's own result: its advice — `az login`, or `az login --username <pacUser>` when az and pac are different identities — reaches the user verbatim, and nothing provisions, generates or uploads after it+- A gate that passes with az and pac signed in as different identities (`ok: true`, `identitiesMatch: false`) is a warning, not a blocker: the orchestrator shows its one-line `message` verbatim, with the `az login --username <pacUser>` fix, and goes on to the entity-builder, whose dispatch is read from the recorded calls; a builder re-probe that sees the same mismatch logs a one-line warning in its transaction log (`agents/genpage-entity-builder.md` Step 2)+- An edit keeps what its plan's Preservation Constraints promise: every identifier a constraint quotes in a code span and the downloaded page (`before/`) uses is still used by the edited page (comments do not count). Constraints written only in prose are left to a person+- Sample data handed to `provision-entities.js` is realistic: no lorem ipsum, no placeholder word (`test`, `sample`, `TBD`, `N/A`…) or numbered table name (`Project 1`), and no table whose rows repeat one name- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/the type generator/upload flags and their recorded results, the plan's entity blocks, the entity-creation transactions, and the choice enums in the captured `RuntimeTypes.ts` — on either upload transport. The plugin's own scripts are read as data: `scripts/list-tables.js` (a table exists when `tables` holds its exact logical name; `missing` names the terms with none; a failed read confirms nothing), `scripts/apps.js list` (`apps`), `scripts/genpage.js list` (`pages`, each with its `pageId` and `name`) and `scripts/list-languages.js` (`languages`; it is the only source, so a failed read detects nothing and a `pac model list-languages` after it is not credited). The type generator is `scripts/genpage.js types` and the edit flow's download `scripts/genpage.js download`; a capture made before the scripts records the `pac model list-tables`, `pac model list`, `pac model list-languages`, `pac model genpage list | download | generate-types` forms, and those are read too. The new-app expectations (eval 8) require the plugin's order: the first page uploaded with no app and no `--add-to-sitemap`, then `apps.js create --solution --page-id --publish` (which pins the first page's tables itself, so nothing has to follow it), and every upload after it naming the app it returned — `pac model create` does not satisfy them. These recognizers read a script's verb the way the mutation checks do, so a verb after its flags (`genpage.js --env <url> types …`) counts, and a "types … SKIPPED (mock data)" expectation fails for a run that generated types that way. A listing recorded as the JSON the scripts print — one line, as a parsed result, as text, or as a log's `Result: {…}` line — is read as data (`id`/`pageId`/`appId` and `name`); JSON that does not parse lists nothing, and only output that is not JSON (a PAC table, a log's bullets) goes to the older table reader**Runner:** `evals/model-apps/genpage/run-layer-1.js`@@ -107,7 +111,9 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua- The production `pageStructureProblems` gate rejects truncated modules, including unfinished statements after valid exports- The Custom API lifecycle grades actual saved TSX, method/parameter/bound-record parity, sanitized result handling and preservation versus explicit clear-Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The registered Phase-5b column checker now executes; its existing `column-name verification requires RuntimeTypes.ts fixture` SKIP is explicit, not silently excluded by routing. Column/schema verification itself remains unimplemented. Other unregistered/AST-dependent expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.+Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The column-name expectations (eval 1's Phase 5b, in both layers, and eval 7's) are graded by `lib/column-contract.js` against the RuntimeTypes.ts a fixture kept: every column a page names in its dataApi calls — a `select` list, an `orderBy` or `filter` expression, the keys of a `createRow`/`updateRow` payload, an options object or select list written as a name it declares, and each `<column>@OData.Community.Display.V1.FormattedValue` key it reads — must be one the schema declares on that table (or a system column every user-owned table has and the type generator does not write, such as `createdon`). A fixture that kept no RuntimeTypes.ts reports `column-name verification requires RuntimeTypes.ts fixture`. Other unregistered expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.++**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.**Bounded Custom API declaration tracking (Layers 1 and 2):** Potential-write checksdistinguish a definite plain arrow parameter declaration, including a default, from an@@ -147,7 +153,7 @@ All eval definitions live in `evals.json` alongside this file. The file contains- `common_code_assertions`: **21** registered code checks.- `evals`: **25** prompt definitions, each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.-The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **27 fixture directories / 34 top-level TSX files**, representing 25 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.+The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **33 fixture directories / 37 top-level TSX files**, representing 25 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.### Enumerating registered and unmatched checks@@ -187,7 +193,7 @@ report, and fails when:- an expectation is routed by neither runner (it would be dropped without even a SKIP), or acommon assertion has no check;- an expectation has no check and is not recorded as `deferred` (an offline check could grade- it) or `manual` (a person judges the generated page);+ it) or `manual` (a person judges the generated page), with the reason no check grades it yet;- a registered check returns SKIP on every fixture it runs on and is not recorded with its reason;- the counts and missing prompt IDs this guide and `fixtures/README.md` state disagree with theregistries, or the loader's entity-log name differs from the one the skill writes.@@ -247,25 +253,25 @@ The suite ships both kinds:| Eval | Synthetic fixture | Real capture ||-----:|-------------------|---------------|-| 1 | `1-account-card-gallery` | — |+| 1 | `1-account-card-gallery`, `1-account-cards-verified-columns` (current, keeps its RuntimeTypes.ts) | — || 2 | `2-mock-dashboard` | `2-mock-dashboard-real` (historical compatibility replay) || 4 | `4-case-wizard` | — || 5 | — | `5-kanban-task-board` (historical compatibility replay) |-| 7 | `7-job-candidates-new-entities` | — |+| 7 | `7-job-candidates-new-entities`, `7-job-candidates-verified-columns` (current, keeps its RuntimeTypes.ts) | — || 11 | `11-recruitment-multi-page` (historical) | `11-recruitment-pages-real` (historical, green) || 13 | `13-contact-localization` | — || 15 | — | `15-support-tickets-real` (historical, green) || 17 | `17-weather-mock-data` (historical) | — || 18 | `18-sharepoint-connectors` (historical) | — || 19 | `19-add-weather-connector` (historical edit) | — |-| 10 | `10-auth-timeout-halt` (current refusal) | — |+| 10 | `10-auth-timeout-halt`, `10-az-signed-out-halt`, `10-whoami-403-halt` (current refusals), `10-identity-mismatch-proceeds` (current, proceeds past an identity warning) | — || 20 | `20-upload-preservation` (current create/edit/refusal) | — || 21 | `21-discovery-failure` (current refusal) | — || 22 | `22-navigation-contract` (current before/after) | — || 23 | `23-worker-completeness` (current rejection/recovery) | — || 24 | `24-custom-api-lifecycle` (current create/preserve/clear) | — || 25 | `25-solution-package` (current packaging/refusal) | — |-| 3 | `3-contacts-edit-search-sort` (current edit) | — |+| 3 | `3-contacts-edit-search-sort` (current edit), `3-edit-no-pages-stop` (current refusal: the app has no pages) | — || 6 | `6-traffic-analytics-mock` (current mock data) | — || 8 | `8-account-metrics-new-app` (current new app) | — || 9 | `9-project-tracker-new-entities` (current new tables + sample data) | — |@@ -296,7 +302,7 @@ The first seven contract-2 fixtures exercise these current contracts:| `24-custom-api-lifecycle` | Discovery, re-probe, bare actions, runtime and config stages | Disabled/unreadable gate, invented kind/name/parameter, wrong method/bound record, unsafe response or lost bindings || `25-solution-package` | Explicit page IDs, dynamic types, app-first writes and read-back | Omitted page/wrong solution/type/order; invalid ID writes; partial failure reported as success |-Expected refusals are green **only when the recorded refusal contract is satisfied**. Fixtures 10 and 21 legitimately contain no generated TSX; Layer 2 grades their failed gate and absence of generation/mutations rather than manufacturing a page. Fixture 23's rejected snapshot is nested evidence; the top-level page is the accepted regeneration. Expected-failure mutations live in unit tests, never unexplained red corpus directories.+Expected refusals are green **only when the recorded refusal contract is satisfied**. The refusal fixtures of evals 10 and 21, and `3-edit-no-pages-stop`, legitimately contain no generated TSX; Layer 2 grades their failed gate and absence of generation/mutations rather than manufacturing a page. A refusal declares its stage in `fixture.json` (`refusal.stage`): `auth` and `discovery` stop at a failed check-auth.js or list-connections.js result, `custom-api` at a disabled or unreadable feature gate, and `edit-pages` at an app whose `genpage.js list` succeeded with no page to offer — the user is told so and nothing is downloaded, planned or uploaded after the first such listing (a later read does not reset it), and the edit phases that would follow the page choice skip for that run. Fixture 23's rejected snapshot is nested evidence; the top-level page is the accepted regeneration. Expected-failure mutations live in unit tests, never unexplained red corpus directories.---@@ -317,14 +323,15 @@ Exit codes:### Filter by tier```bash-node run-layer-1.js --tier smoke # 6 stored fixtures, 5 prompt definitions-node run-layer-1.js --tier full # 18 stored fixtures, 17 prompt definitions-node run-layer-1.js --tier stress # 3 stored fixtures, 3 prompt definitions+node run-layer-1.js --tier smoke # 8 stored fixtures, 5 prompt definitions+node run-layer-1.js --tier full # 19 stored fixtures, 17 prompt definitions+node run-layer-1.js --tier stress # 6 stored fixtures, 3 prompt definitions```A tier runs only existing fixtures, not every prompt definition. An empty selection reports-`no fixtures matched the filter` and exits 2. The stress tier now replays the synthetic auth-timeout-refusal, the plan-revision trace and the filename-collision trace.+`no fixtures matched the filter` and exits 2. The stress tier now replays the three synthetic auth+refusals (a timeout, a signed-out Azure CLI and a WhoAmI 403), a run that passes the auth gate with an+identity warning and goes on, the plan-revision trace and the filename-collision trace.### Filter by eval id (debugging)@@ -436,12 +443,12 @@ Read this output as:- **Final summary:** `# tests <N>` / `# pass <N>` / `# fail <N>` / `# skip <N>` / `# fixtures <N> (pass X, fail Y)`.**Skipped vs failed:**-- `# SKIP <reason>` — the assertion doesn't apply (e.g., "no Dataverse files in this fixture" for a mock-data assertion, or "Rule 14 batched-setState requires AST analysis" for an assertion the runner doesn't implement). **Does not fail the fixture.**+- `# SKIP <reason>` — the assertion doesn't apply (e.g., "no Dataverse files in this fixture" for a mock-data assertion), or a registered check cannot grade the stored evidence yet (e.g., "column-name verification requires RuntimeTypes.ts fixture"). **Does not fail the fixture.**- `not ok` — actual failure. Fixture fails. Exit code becomes 1.**Three common skip reasons in our suite:**1. `no Dataverse files / no <feature> detected` — the fixture doesn't exercise this code path-2. `requires AST analysis (not implemented)` — assertion needs more than regex; left as manual check until a parser-based implementation lands+2. `not graded yet` / `requires RuntimeTypes.ts fixture` — a check that cannot grade the stored evidence: a correct check would fail a historical fixture's real drift, or the capture did not keep what the check reads. `evals/model-apps/tests/eval-coverage-baseline.json` records the reason for each3. `no check registered for this expectation` — the assertion text in `evals.json` doesn't have a corresponding check in the runner library. Either add the check or accept the skip as documentation-only.---diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/RuntimeTypes.tsnew file mode 100644index 000000000..2769543a8--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/RuntimeTypes.ts@@ -0,0 +1,60 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "account": account,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "account-accountcategorycode": account_accountcategorycode,+ "account-statecode": account_statecode,+ "account-statuscode": account_statuscode,+}+export type account = TableRow<{+ // Primary Key Column+ readonly accountid: string,+ accountcategorycode: account_accountcategorycode,+ accountnumber: string,+ address1_city: string,+ address1_country: string,+ address1_line1: string,+ address1_postalcode: string,+ address1_stateorprovince: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ description: string,+ emailaddress1: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ name: string,+ numberofemployees: number,+ readonly owningbusinessunitname: string,+ _primarycontactid_value: `/contact(${string})`,+ readonly primarycontactidname: string,+ readonly primarycontactidyominame: string,+ revenue: number,+ statecode: account_statecode,+ statuscode: account_statuscode,+ telephone1: string,+ websiteurl: string,+}>++const enum account_accountcategorycode {+"Preferred Customer" = 1,+"Standard" = 2,+}+const enum account_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum account_statuscode {+"Active" = 1,+"Inactive" = 2,+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+}diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/account-gallery.tsx b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/account-gallery.tsxnew file mode 100644index 000000000..b91640a03--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/account-gallery.tsx@@ -0,0 +1,276 @@+import { useEffect, useState } from 'react';+import type {+ TableRow,+ ReadableTableRow,+ GeneratedComponentProps,+} from './RuntimeTypes';+import {+ makeStyles,+ tokens,+ Card,+ CardHeader,+ Text,+ Caption1,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import { BuildingRegular, GlobeRegular, MailRegular, CallRegular } from '@fluentui/react-icons';++// Accounts Gallery — Account records as a scrollable gallery of cards.+// Every column below is verified in RuntimeTypes.ts (account): accountid, name, websiteurl,+// emailaddress1 and telephone1. Selecting a card opens the Account record.++type AccountRow = TableRow<{+ readonly accountid: string;+ name?: string;+ websiteurl?: string;+ emailaddress1?: string;+ telephone1?: string;+}>;++type ReadableAccount = ReadableTableRow<AccountRow>;++type GalleryState = {+ records: ReadableAccount[];+ loading: boolean;+ error: string | null;+};++// Window-level cache + in-flight de-dupe (Rule 15, references/data-caching.md).+// Keys are scoped by page + query so another page reading account never shares them.+const CACHE_KEY = '__ppAccountsGallery_accountCache';+const INFLIGHT_KEY = '__ppAccountsGallery_accountInflight';+const winAny = window as unknown as Record<string, unknown>;++type XrmLike = {+ Navigation?: {+ navigateTo: (+ pageInput: { pageType: 'entityrecord'; entityName: string; entityId: string },+ ) => Promise<unknown>;+ };+};++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingHorizontalXL,+ height: '100%',+ width: '100%',+ boxSizing: 'border-box',+ '@media (max-width: 480px)': {+ padding: tokens.spacingHorizontalM,+ },+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ },+ titleGroup: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ titleIcon: {+ fontSize: tokens.fontSizeBase600,+ color: tokens.colorBrandForeground1,+ },+ count: {+ color: tokens.colorNeutralForeground3,+ },+ gallery: {+ flexGrow: 1,+ minHeight: 0,+ overflowY: 'auto',+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',+ gap: tokens.spacingHorizontalL,+ alignContent: 'start',+ paddingBlock: tokens.spacingVerticalXS,+ },+ card: {+ cursor: 'pointer',+ ':hover': {+ boxShadow: tokens.shadow8,+ },+ },+ detail: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ minWidth: 0,+ color: tokens.colorNeutralForeground2,+ },+ detailText: {+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ spinnerWrap: {+ display: 'flex',+ justifyContent: 'center',+ padding: tokens.spacingVerticalXXL,+ },+ empty: {+ padding: tokens.spacingVerticalXL,+ textAlign: 'center',+ color: tokens.colorNeutralForeground3,+ },+});++function openAccount(accountId: string): void {+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;+ void xrm?.Navigation?.navigateTo({+ pageType: 'entityrecord',+ entityName: 'account',+ entityId: accountId,+ });+}++function DetailLine(props: { icon: JSX.Element; value: string | undefined }) {+ const styles = useStyles();+ return (+ <div className={styles.detail}>+ {props.icon}+ <Caption1 className={styles.detailText} title={props.value || ''}>+ {props.value || '—'}+ </Caption1>+ </div>+ );+}++function AccountCard(props: { account: ReadableAccount }) {+ const styles = useStyles();+ const { account } = props;+ const name = account.name || 'Unnamed account';+ return (+ <Card+ className={styles.card}+ onClick={() => openAccount(account.accountid)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ openAccount(account.accountid);+ }+ }}+ tabIndex={0}+ role="button"+ aria-label={`Open account ${name}`}+ >+ <CardHeader+ image={<BuildingRegular aria-hidden="true" />}+ header={<Text weight="semibold">{name}</Text>}+ />+ <DetailLine icon={<GlobeRegular aria-hidden="true" />} value={account.websiteurl} />+ <DetailLine icon={<MailRegular aria-hidden="true" />} value={account.emailaddress1} />+ <DetailLine icon={<CallRegular aria-hidden="true" />} value={account.telephone1} />+ </Card>+ );+}++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // gallery page takes no record context; destructured per the component contract+ const styles = useStyles();++ // Seed from the window cache so a second mount paints cards without a spinner.+ const [data, setData] = useState<GalleryState>(() => {+ const cached = winAny[CACHE_KEY] as ReadableAccount[] | undefined;+ return { records: cached ?? [], loading: cached === undefined, error: null };+ });++ const dataReady = !!dataApi;++ useEffect(() => {+ if (!dataReady) return;++ const cached = winAny[CACHE_KEY] as ReadableAccount[] | undefined;+ if (cached !== undefined) {+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });+ return;+ }+ let cancelled = false;++ // The host double-mounts the page on open; a racing second mount awaits the+ // same in-flight promise instead of issuing a second query.+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableAccount[]> | undefined;+ if (!inflight) {+ inflight = dataApi.queryTable('account', {+ select: ['accountid', 'name', 'websiteurl', 'emailaddress1', 'telephone1'],+ orderBy: 'name asc',+ pageSize: 250,+ })+ .then((result) => {+ winAny[CACHE_KEY] = result.rows;+ return result.rows as ReadableAccount[];+ })+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });+ winAny[INFLIGHT_KEY] = inflight;+ }++ inflight+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })+ .catch((err) => {+ if (cancelled) return;+ const message = err instanceof Error ? err.message : 'Failed to load accounts.';+ setData({ records: [], loading: false, error: message });+ });++ return () => { cancelled = true; };+ // Readiness only — dataApi is a new reference on every render (Rule 15).+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dataReady]);++ if (data.loading) {+ return (+ <div className={styles.root}>+ <div className={styles.spinnerWrap}>+ <Spinner labelPosition="below" label="Loading accounts…" />+ </div>+ </div>+ );+ }++ return (+ <div className={styles.root}>+ <header className={styles.header}>+ <div className={styles.titleGroup}>+ <BuildingRegular className={styles.titleIcon} aria-hidden="true" />+ <Text as="h1" size={600} weight="semibold">+ Accounts+ </Text>+ </div>+ <Caption1 className={styles.count} aria-live="polite">+ {data.records.length === 1 ? '1 account' : `${data.records.length} accounts`}+ </Caption1>+ </header>++ {data.error && (+ <MessageBar intent="error">+ <MessageBarBody>{data.error}</MessageBarBody>+ </MessageBar>+ )}++ {data.records.length === 0 && !data.error ? (+ <Text className={styles.empty} block>+ No accounts found.+ </Text>+ ) : (+ <div className={styles.gallery} role="list" aria-label="Accounts">+ {data.records.map((account) => (+ <div role="listitem" key={account.accountid}>+ <AccountCard account={account} />+ </div>+ ))}+ </div>+ )}+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/agent-message.txt b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/agent-message.txtnew file mode 100644index 000000000..01921a9aa--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/agent-message.txt@@ -0,0 +1 @@+Created the Accounts Gallery page: a scrollable gallery of Account cards showing name, website, email and main phone. Selecting a card opens its Account form.diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/fixture.json b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/fixture.jsonnew file mode 100644index 000000000..98b551cfb--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/fixture.json@@ -0,0 +1,21 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed trace of a compliant attended create run for eval 1, not an agent capture. An existing Dataverse table (account) is shown as a scrollable gallery of cards added to an existing app; code-only, so no solution question, entity work or auth gate. It keeps the RuntimeTypes.ts the type generator wrote, so the page's column names are checked against the schema they were verified from. tool-results.json records every logged command in order; the create upload uses the file transport with the full User Requirements as its prompt.",+ "contracts": [+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0: Create Working Directory",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0.5: Initialize Local-Dev Manifest",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-7)",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 3: App Creation/Selection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4: Generate RuntimeTypes",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4.6 and 4.7 feature-gate re-probes",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Single-page fast path",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",+ "plugins/model-apps/references/plan-schema.md Required Structure",+ "plugins/model-apps/references/rules.md DataAPI Rules",+ "plugins/model-apps/references/data-caching.md"+ ],+ "expectedOutcome": "deployed",+ "toolResults": "tool-results.json",+ "artifacts": ["prompt.txt", "agent-message.txt", "page-name.txt", "RuntimeTypes.ts"]+}diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/genpage-plan.md b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/genpage-plan.mdnew file mode 100644index 000000000..ef25ea9c5--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/genpage-plan.md@@ -0,0 +1,61 @@+# Genpage Plan++## User Requirements+Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record.++- Data source: Dataverse entity account (already exists)+- Specific requirements: responsive card layout, each card clickable to open the Account record++## Working Directory+D:/work/account-gallery++## Plugin Root+D:/repo/plugins/model-apps++## Environment+- URL: https://contoso.crm.dynamics.com+- App: Sales Hub (11111111-2222-3333-4444-555555555555)+- Languages: English (1033) only+- Solution: Default+- Publisher Prefix: new++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Accounts Gallery | account-gallery.tsx | Scrollable gallery of Account cards; each card opens its Account record | account |++## Entity Creation Required+No entity creation required — all entities already exist.++## Existing Entities+account++## Connector Bindings+No connector bindings.++## Custom API Bindings+No custom API bindings.++## Design Preferences+- Styling: Default Fluent UI V9 look; makeStyles with tokens, no custom theme+- Features: Responsive card gallery — name, website, email and main phone on each card; the gallery scrolls; a card opens the Account form+- Accessibility: WCAG AA defaults; each card is keyboard reachable and announces the account it opens++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Accounts Gallery | 7-responsive-cards.tsx | Responsive card layout over Dataverse records |+| Accounts Gallery | 9-list-with-caching.tsx | Window cache and in-flight de-dupe for an on-mount read |++## Per-Page Specifications++### Accounts Gallery+- **File:** account-gallery.tsx+- **Purpose:** Scrollable gallery of Account cards; each card opens its Account record+- **Entities:** account+- **Needs caching:** true+- **Key Features:** Accounts title with record count; one card per account showing name, website, email and main phone; empty and error states.+- **Components:** Card, CardHeader, Text, Caption1, Spinner, MessageBar; BuildingRegular, GlobeRegular, MailRegular and CallRegular icons.+- **Layout:** Flex column filling the page; header row with title opposite the count; the gallery is a responsive grid (auto-fill, 260px minimum) and is the only part that scrolls; no viewport units.+- **Data Binding:** dataApi.queryTable('account') on mount selecting accountid, name, websiteurl, emailaddress1, telephone1, ordered by name asc, read via result.rows; window cache + in-flight de-dupe keyed for this page, single batched setData.+- **Interactions:** Selecting a card (click, Enter or Space) opens the Account record with Xrm.Navigation.navigateTo (pageType entityrecord).diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/page-name.txt b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/page-name.txtnew file mode 100644index 000000000..863bddbc2--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/page-name.txt@@ -0,0 +1 @@+Accounts Gallerydiff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/prompt.txt b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/prompt.txtnew file mode 100644index 000000000..3ed27f082--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/prompt.txt@@ -0,0 +1,4 @@+Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record.++- Data source: Dataverse entity account (already exists)+- Specific requirements: responsive card layout, each card clickable to open the Account recorddiff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/tool-results.json b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/tool-results.jsonnew file mode 100644index 000000000..30e7fb5dd--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/tool-results.json@@ -0,0 +1,92 @@+[+ {+ "id": "manifest",+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/account-gallery' 'account-gallery'",+ "exitCode": 0,+ "result": { "workingDir": "D:\\work\\account-gallery", "slug": "account-gallery", "features": [], "files": { "package.json": { "wrote": true }, "genpage.d.ts": { "wrote": true } } }+ },+ {+ "id": "interaction-mode",+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",+ "exitCode": 0,+ "result": { "ok": true, "interactive": true, "reason": "default (attended)" }+ },+ { "id": "node-version", "command": "node --version", "exitCode": 0, "result": "v20.20.2" },+ { "id": "pac-help", "command": "pac help", "exitCode": 0, "result": "Microsoft PowerPlatform CLI Version: 2.11.0" },+ {+ "id": "auth-list",+ "command": "pac auth list",+ "exitCode": 0,+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"+ },+ { "id": "list-languages", "by": "genpage-planner", "command": "node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'", "exitCode": 0, "result": { "ok": true, "baseLanguage": { "lcid": 1033, "code": "en-US", "name": "English (United States)", "rtl": false }, "languages": [{ "lcid": 1033, "code": "en-US", "name": "English (United States)", "rtl": false }], "unmapped": [], "summary": ["1033 en-US \u2014 RTL: No"] } },+ { "id": "list-tables", "by": "genpage-planner", "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'account' --exact", "exitCode": 0, "result": { "ok": true, "search": ["account"], "exact": true, "count": 1, "tables": [{ "logicalName": "account", "displayName": "Account", "schemaName": "Account", "isCustom": false }], "missing": [] } },+ { "id": "list-apps", "by": "genpage-planner", "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'", "exitCode": 0, "result": { "ok": true, "count": 2, "apps": [+ { "id": "11111111-2222-3333-4444-555555555555", "name": "Sales Hub", "uniqueName": "SalesHub", "description": "", "published": true, "unpublishedChanges": false },+ { "id": "44444444-5555-6666-7777-888888888888", "name": "Customer Service Hub", "uniqueName": "CustomerServiceHub", "description": "", "published": true, "unpublishedChanges": false }+ ] } },+ {+ "id": "planner-discovery",+ "command": "Task genpage-planner (discovery: create, No connector bindings., No custom API bindings.)",+ "result": { "action": "needs_input", "questions": [{ "id": "app", "question": "Which app should the page be added to?", "options": ["Sales Hub (11111111-2222-3333-4444-555555555555)", "Customer Service Hub (44444444-5555-6666-7777-888888888888)", "Create a new app"] }], "discovered": { "languages": ["English (1033)"], "existingEntities": ["account"], "entitiesToCreate": [] } }+ },+ {+ "id": "planner-proposal",+ "command": "Task genpage-planner (answers: create, account, card gallery, app Sales Hub)",+ "result": { "action": "plan", "pages": [{ "page": "Accounts Gallery", "file": "account-gallery.tsx", "entities": ["account"] }], "entityCreationRequired": false, "app": { "name": "Sales Hub", "appId": "11111111-2222-3333-4444-555555555555" } }+ },+ {+ "id": "plan-prepare",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/account-gallery/genpage-plan.md'",+ "exitCode": 0,+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\account-gallery\\genpage-plan.md", "quarantinedPath": null }+ },+ {+ "id": "planner-write",+ "command": "Task genpage-planner (approved: write genpage-plan.md)",+ "result": { "action": "written", "plan": "D:/work/account-gallery/genpage-plan.md" }+ },+ {+ "id": "plan-verify",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/account-gallery/genpage-plan.md' --approved '@D:/work/account-gallery/.approved-genpage-plan.md'",+ "exitCode": 0,+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\account-gallery\\genpage-plan.md", "kind": "create", "targets": ["account-gallery.tsx"], "writtenHash": "c5691e05dde677ed7f054162e2cd1fc5585b1b89e6bfa07e1e2369fb430dc224" }+ },+ {+ "id": "generate-types",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'account' --output-file 'D:/work/account-gallery/RuntimeTypes.ts'",+ "exitCode": 0,+ "result": { "ok": true, "outputFile": "D:/work/account-gallery/RuntimeTypes.ts", "dataSources": ["account"], "detail": "none", "bytes": 1911 }+ },+ { "id": "gate-custom-api", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api", "exitCode": 1, "result": "disabled" },+ { "id": "gate-telemetry", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry", "exitCode": 1, "result": "disabled" },+ {+ "id": "page-files",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/account-gallery/genpage-plan.md'",+ "exitCode": 0,+ "result": { "ok": true, "workingDir": "D:\\work\\account-gallery", "files": ["account-gallery.tsx"], "problems": [] }+ },+ {+ "id": "stamp",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/account-gallery/account-gallery.tsx'",+ "exitCode": 0,+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\account-gallery\\account-gallery.tsx", "existed": false }+ },+ { "id": "write-page", "command": "Write account-gallery.tsx", "artifact": "account-gallery.tsx" },+ { "id": "icon-grep", "command": "Grep from \"@fluentui/react-icons\" account-gallery.tsx; Grep ^(BuildingRegular|GlobeRegular|MailRegular|CallRegular)$ references/verified-icons.txt", "result": "BuildingRegular, GlobeRegular, MailRegular, CallRegular: verified" },+ { "id": "border-grep", "command": "Grep ['\"]?borderWidth['\"]?\\s*: account-gallery.tsx", "result": "no matches" },+ {+ "id": "gate",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-gallery/account-gallery.tsx'",+ "artifact": "account-gallery.tsx",+ "exitCode": 0,+ "result": { "ok": true, "filePath": "D:\\work\\account-gallery\\account-gallery.tsx", "problems": [] }+ },+ { "id": "write-upload-text", "command": "Write prompt.txt, agent-message.txt, page-name.txt", "artifacts": ["prompt.txt", "agent-message.txt", "page-name.txt"] },+ {+ "id": "create",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'account-gallery.tsx' --name-file 'page-name.txt' --data-sources 'account' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",+ "exitCode": 0,+ "result": { "ok": true, "pageId": "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", "appId": "11111111-2222-3333-4444-555555555555", "updated": false }+ }+]diff --git a/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/workflow-log.md b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/workflow-log.mdnew file mode 100644index 000000000..dfdfb9763--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-cards-verified-columns/workflow-log.md@@ -0,0 +1,131 @@+# Workflow Log — Eval 1: Account card gallery (create flow)++Synthetic trace constructed from the current `/genpage` SKILL.md, not a captured agent run.+Every command below has an ordered result in `tool-results.json`. Commands run from the+working directory, so file arguments are relative to it. The RuntimeTypes.ts the type+generator wrote is kept beside the page.++## Phase 0 — Working directory+- `$ARGUMENTS`: "Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record."+- Working directory created: `mkdir -p 'account-gallery'` (kebab-case from "Account gallery")+- Resolved working directory: D:/work/account-gallery+- Plugin root: D:/repo/plugins/model-apps++## Phase 0.5 — Local-dev manifest+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/account-gallery' 'account-gallery'`+- Result: exit 0; package.json and genpage.d.ts written; no `--features` (no charts or date/time pickers needed)++## Phase 1 — Plan++### Interaction mode+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, every gate asked in this loop++### Prereq checks (run separately, not chained)+- `node --version` → v20.20.2+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)++### Auth+- `pac auth list` → one profile, currently active: [email protected]+- Active environment reported to the user: https://contoso.crm.dynamics.com/++### Create or edit+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Create new page(s)++### Requirements+- Question 3 (data source) skipped: `$ARGUMENTS` already names it → Dataverse entity: account+- AskUserQuestion: Any specific requirements for the page? → Responsive card layout, each card clickable to open the Account record++### Discovery (genpage-planner dispatched via Task as a headless worker)+- Dispatched `Task genpage-planner` with the requirements, working directory, plugin root, create/edit decision = create, `No connector bindings.` (connectors.json: none — omit --connectors) and `No custom API bindings.` (actions.json: none — omit --actions)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'` → English (1033) only, no RTL language+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'account' --exact` → 1 table: `account` (exact logical-name match, nothing in `missing`); account already exists, so no entity creation+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 apps: Sales Hub (11111111-2222-3333-4444-555555555555), Customer Service Hub (44444444-5555-6666-7777-888888888888); both published, neither with unpublished changes+- Planner returned the discovery summary and `{ "action": "needs_input" }` for the app choice; no connector or Custom API need was found++### App selection+- AskUserQuestion: Which app should the page be added to? (options from the `apps.js list` output: Sales Hub — 11111111-2222-3333-4444-555555555555; Customer Service Hub — 44444444-5555-6666-7777-888888888888; Create a new app) → Sales Hub (existing app)++### Solution selection+- Code-only build (no new entities, existing app) → solution selection question SKIPPED+- Defaults written to the plan: `Solution: Default`, `Publisher Prefix: new`++### Plan approval+- Re-invoked `Task genpage-planner` with every answer gathered so far; it returned the proposed plan (1 page: Accounts Gallery on entity account)+- EnterPlanMode called — presented the proposed plan+- ExitPlanMode → user approved the plan without changes+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/account-gallery/genpage-plan.md'`+- Result: `"ok":true`, nothing to quarantine (first run in this folder)+- Saved the approved plan body verbatim to D:/work/account-gallery/.approved-genpage-plan.md+- Re-invoked `Task genpage-planner` with the approval outcome, the approved plan body and all prior discovery; it wrote genpage-plan.md (conforms to references/plan-schema.md)+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/account-gallery/genpage-plan.md' --approved '@D:/work/account-gallery/.approved-genpage-plan.md'`+- Result: `"ok":true`, kind create, targets [account-gallery.tsx], writtenHash c5691e05dde677ed7f054162e2cd1fc5585b1b89e6bfa07e1e2369fb430dc224++## Phase 2 — Entities+- SKIPPED: `## Entity Creation Required` is the no-entity sentinel (account exists)+- check-auth.js and genpage-entity-builder were not invoked (no metadata work)++## Phase 3 — App+- SKIPPED app creation: existing app Sales Hub (11111111-2222-3333-4444-555555555555) selected++## Phase 4 — RuntimeTypes+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'account' --output-file 'D:/work/account-gallery/RuntimeTypes.ts'`+- Read RuntimeTypes.ts: verified accountid, name, websiteurl, emailaddress1 and telephone1 on account (the columns the cards show)++## Phase 4.5 — Connector bindings+- SKIPPED: plan says `No connector bindings.` → Connectors: none; no connectors.json, no `--connectors`++## Phase 4.6 — Custom API bindings+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api`+- Result: `disabled`; plan body is exactly `No custom API bindings.` → continue with no Custom APIs, no actions.json, no `--actions`++## Phase 4.7 — Page telemetry+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry`+- Result: `disabled` → Telemetry: disabled; the page contains no telemetry calls++## Phase 5a — Plan validation+- One page row with a matching `### Accounts Gallery` subsection+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/account-gallery/genpage-plan.md'`+- Result: `"ok":true` — account-gallery.tsx is a safe, unique page file++## Phase 5b — Single-page fast path+- Plan has 1 page → inlined the page-builder workflow (no Task dispatch for the page)+- Data mode: dataverse; Connectors: none; Telemetry: disabled+- Read D:/repo/plugins/model-apps/references/rules.md+- Read sample D:/repo/plugins/model-apps/samples/7-responsive-cards.tsx (card layout) and samples/9-list-with-caching.tsx (from `## Relevant Samples`)+- Needs caching: true → read references/data-caching.md+- Languages: English only → localization.md not needed+- Read genpage-plan.md and RuntimeTypes.ts+- Read D:/repo/plugins/model-apps/references/verified-icons.txt to source icon names before writing+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/account-gallery/account-gallery.tsx'`+- Result: `"ok":true`, stamp recorded, no earlier file at the target+- Wrote account-gallery.tsx with the file tool: responsive card gallery (one Card per account with name, website, email and main phone), window cache + in-flight de-dupe gated on `dataReady`, single batched setData, result read via `.rows`, each card opens its record via Xrm.Navigation.navigateTo; every selected column is one RuntimeTypes.ts declares+- Icon verification: Grep for `from "@fluentui/react-icons"` → BuildingRegular, GlobeRegular, MailRegular, CallRegular; Grep of references/verified-icons.txt for each name → all present+- Grep `['"]?borderWidth['"]?\s*:` → no matches+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-gallery/account-gallery.tsx'`+- Result: `"ok":true`, problems [] — complete page accepted++## Phase 6 — Deploy+- No connectors.json / actions.json → the upload `--help` pre-flight for `--connectors` / `--actions` is not needed+- Checked prompt.txt, agent-message.txt and page-name.txt in the working directory: none existed, none is a link+- Wrote prompt.txt (the full `## User Requirements` body), agent-message.txt and page-name.txt ("Accounts Gallery") with the file tool+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'account-gallery.tsx' --name-file 'page-name.txt' --data-sources 'account' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`+- Prompt scope: full page description from the plan's `## User Requirements` (create)+- Result: page-id = bbbbbbbb-cccc-4ddd-8eee-ffffffffffff, status = success (`updated: false`, added to the Sales Hub sitemap)++## Phase 6.5 — Navigation fix-up+- SKIPPED: single page, no PAGEREF_ placeholders++## Phase 7 — Verify in browser+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Accounts Gallery | account-gallery.tsx | account | Deployed |++- App: Sales Hub (11111111-2222-3333-4444-555555555555)+- Page ID: bbbbbbbb-cccc-4ddd-8eee-ffffffffffff+- Entities created: none+- Browser verification: skippeddiff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.jsonindex 5f8b01f0e..e9f4ec5e5 100644--- a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/tool-results.json@@ -1,4 +1,11 @@[+ {+ "id": "list-tables-search",+ "by": "genpage-planner",+ "command": "node scripts\\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact",+ "exitCode": 0,+ "result": { "ok": true, "search": ["cnt_widget"], "exact": true, "count": 0, "tables": [], "missing": ["cnt_widget"] }+ },{"id": "auth-first","command": "node scripts\\check-auth.js --env https://contoso.crm.dynamics.com --require-pac",diff --git a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.mdindex d702ea60b..af18ccc9f 100644--- a/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md+++ b/evals/model-apps/genpage/fixtures/10-auth-timeout-halt/workflow-log.md@@ -13,6 +13,7 @@ Working directory created: D:\work\widget-page.- Unattended default: new or edit -> create new page- Unattended default: solution -> ContosoPages, Publisher Prefix cnt- Unattended default: plan approval -> approved+- Planner ran `node scripts\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact` -> 0 tables, missing: cnt_widget (exact logical-name match: the table does not exist, so it must be created)- genpage-plan.md records suffix widget under Entity Creation Required.## Phase 2a - Pre-flight and one retrydiff --git a/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/fixture.json b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/fixture.jsonnew file mode 100644index 000000000..e37d6b173--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/fixture.json@@ -0,0 +1,12 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed refusal trace, not an agent capture. The planner confirms cnt_widget is absent by an exact logical-name search; the auth pre-flight then finds the Azure CLI installed but signed out, and the orchestrator shows the az login advice verbatim and stops before any entity-builder dispatch, provisioning, page generation or upload.",+ "contracts": [+ "plugins/model-apps/agents/genpage-planner.md Step 4: Entity Detection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2a: Pre-flight: az + pac + Dataverse"+ ],+ "expectedOutcome": "refused",+ "refusal": { "stage": "auth" },+ "toolResults": "tool-results.json"+}diff --git a/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/genpage-plan.md b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/genpage-plan.mdnew file mode 100644index 000000000..799094657--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/genpage-plan.md@@ -0,0 +1,70 @@+# Genpage Plan++## User Requirements+Build a page for my new cnt_widget entity that does not exist yet.++## Working Directory+D:\work\widget-page++## Plugin Root+D:\repo\plugins\model-apps++## Environment+- URL: https://contoso.crm.dynamics.com+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)+- Languages: English (1033) only+- Solution: ContosoPages+- Publisher Prefix: cnt++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Widgets | widgets.tsx | Widget list | cnt_widget |++## Entity Creation Required+### widget+- Display Name: Widget+- Display Plural: Widgets+- Primary Name Suffix: name++- Columns:+| Suffix | Type | Required | Notes |+|--------|------|----------|-------|+| name | String | true | Widget name |++- Choice Columns:+| Column Suffix | Options |+|---------------|---------|++- Relationships:+| Type | Related Table | Lookup Suffix | Cascade |+|------|---------------|---------------|---------|++## Existing Entities+None.++## Connector Bindings+No connector bindings.++## Custom API Bindings+No custom API bindings.++## Design Preferences+Responsive widget list with accessible labels.++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Widgets | 9-list-with-caching.tsx | List layout |++## Per-Page Specifications+### Widgets+- **File:** widgets.tsx+- **Purpose:** Widget list+- **Entities:** cnt_widget+- **Needs caching:** true+- **Key Features:** Name list+- **Components:** Text, Card+- **Layout:** Responsive cards+- **Data Binding:** queryTable after provisioning+- **Interactions:** Local searchdiff --git a/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/tool-results.json b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/tool-results.jsonnew file mode 100644index 000000000..047b7acf8--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/tool-results.json@@ -0,0 +1,21 @@+[+ {+ "id": "list-tables-search",+ "by": "genpage-planner",+ "command": "node scripts\\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact",+ "exitCode": 0,+ "result": { "ok": true, "search": ["cnt_widget"], "exact": true, "count": 0, "tables": [], "missing": ["cnt_widget"] }+ },+ {+ "id": "auth",+ "command": "node scripts\\check-auth.js --env https://contoso.crm.dynamics.com --require-pac",+ "exitCode": 0,+ "result": {+ "ok": false, "blocker": "az_not_logged_in",+ "message": "Azure CLI is installed but not logged in. Run `az login` with the same identity as your active `pac auth` profile.",+ "warnings": [], "azUser": null, "pacUser": null,+ "envUrl": null, "identitiesMatch": false, "whoAmI": null+ },+ "userMessage": "Azure CLI is installed but not logged in. Run `az login` with the same identity as your active `pac auth` profile."+ }+]diff --git a/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/workflow-log.md b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/workflow-log.mdnew file mode 100644index 000000000..c77e666c6--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-az-signed-out-halt/workflow-log.md@@ -0,0 +1,24 @@+# Synthetic workflow evidence++Constructed from SKILL.md Phase 2a; this is not a captured agent run.++## Phase 0 - Working directory+Working directory created: D:\work\widget-page.++## Phase 1 - Planning+- node --version -> v20.20.2+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]+- Unattended default: interaction mode -> unattended (offline synthetic scenario)+- Unattended default: new or edit -> create new page+- Unattended default: solution -> ContosoPages, Publisher Prefix cnt+- Unattended default: plan approval -> approved+- Planner ran `node scripts\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact` -> 0 tables, missing: cnt_widget (exact logical-name match: the table does not exist, so it must be created)+- genpage-plan.md records suffix widget under Entity Creation Required.++## Phase 2a - Pre-flight+- Command: `node scripts\check-auth.js --env https://contoso.crm.dynamics.com --require-pac`+- Result: auth in tool-results.json, ok:false, blocker:az_not_logged_in.+- User message: Azure CLI is installed but not logged in. Run `az login` with the same identity as your active `pac auth` profile.+- Halted: the blocker is not a timeout, so there is no retry; the user signs in with `az login` and runs /genpage again.+- No entity-builder dispatch, provisioning, page generation, or upload was attempted.diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/RuntimeTypes.tsnew file mode 100644index 000000000..9eb685919--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/RuntimeTypes.ts@@ -0,0 +1,41 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "cr_widget": cr_widget,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "cr_widget-statecode": cr_widget_statecode,+ "cr_widget-statuscode": cr_widget_statuscode,+}+export type cr_widget = TableRow<{+ // Primary Key Column+ readonly cr_widgetid: string,+ cr_name: string,+ cr_quantity: number,+ cr_sku: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ readonly owningbusinessunitname: string,+ statecode: cr_widget_statecode,+ statuscode: cr_widget_statuscode,+}>++const enum cr_widget_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum cr_widget_statuscode {+"Active" = 1,+"Inactive" = 2,+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+}diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/agent-message.txt b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/agent-message.txtnew file mode 100644index 000000000..125f75aad--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/agent-message.txt@@ -0,0 +1 @@+Widget list over the new cr_widget table: a sortable grid of every widget with its name, SKU and quantity on hand; the widget name opens the Dataverse record; window cache with in-flight de-dupe.diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/fixture.json b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/fixture.jsonnew file mode 100644index 000000000..b25cefc57--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/fixture.json@@ -0,0 +1,28 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed trace of a compliant attended create run for eval 10, not an agent capture: the branch where the auth pre-flight passes with a warning. The planner confirms cr_widget is absent by an exact logical-name search; check-auth.js then returns ok:true with identitiesMatch:false (az and pac are signed in as different identities, and WhoAmI works). The orchestrator shows the one-line warning verbatim, with its az login --username fix for the pac identity, and goes on: the entity-builder provisions cr_widget (its re-probes return the same warning, which it logs in its transaction log), the user declines sample data, and the page is uploaded with cr_widget as its data source. tool-results.json records every logged command in order.",+ "contracts": [+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0: Create Working Directory",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0.5: Initialize Local-Dev Manifest",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-7)",+ "plugins/model-apps/agents/genpage-planner.md Step 4: Entity Detection, Dominant-prefix detection, Solution Selection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2a: Pre-flight: az + pac + Dataverse",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2b: Invoke entity-builder",+ "plugins/model-apps/agents/genpage-entity-builder.md Step 2: Verify Auth and Connectivity",+ "plugins/model-apps/agents/genpage-entity-builder.md Steps 3-8 (provision-entities.js, sample data declined)",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4: Generate RuntimeTypes",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Single-page fast path",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",+ "plugins/model-apps/references/plan-schema.md Required Structure"+ ],+ "expectedOutcome": "deployed",+ "toolResults": "tool-results.json",+ "artifacts": [+ "prompt.txt",+ "agent-message.txt",+ "page-name.txt",+ "provision-input.json",+ "RuntimeTypes.ts"+ ]+}diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-entity-creation-log.md b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-entity-creation-log.mdnew file mode 100644index 000000000..83c09c4a5--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-entity-creation-log.md@@ -0,0 +1,37 @@+# Entity Creation Log++## Environment+- URL: https://contoso.crm.dynamics.com+- Solution: ContosoOperations+- Publisher Prefix: cr+- Warning: az ([email protected]) and pac ([email protected]) use different identities; WhoAmI passed, so provisioning proceeds (run `az login --username [email protected]` if a later step returns 403).++## Created Tables++### Widget+- Schema Name: cr_Widget+- Resolved Full Name: cr_widget+- Metadata ID: n/a (SDK does not surface metadata ids)++## Created Columns++| Table | Display Name | Schema Name | Resolved Full Name | Metadata ID |+|-------|--------------|-------------|--------------------|-------------|+| cr_widget | SKU | cr_Sku | cr_sku | n/a |+| cr_widget | Quantity | cr_Quantity | cr_quantity | n/a |++## Created Relationships++| Type | From | To | Lookup Schema Name | Resolved Full Name |+|------|------|-----|--------------------|-------------------|++## Commands++```powershell+node "${PLUGIN_ROOT}/scripts/check-auth.js" --env "$ENV_URL" --require-pac # ok: true, identitiesMatch: false (warning above)+node "${PLUGIN_ROOT}/scripts/provision-entities.js" --env "$ENV_URL" --input @D:/work/widgets/provision-input.json --apply+```++## Sample Data++The user declined sample data ("No, skip"); cr_widget was left empty.diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-plan.md b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-plan.mdnew file mode 100644index 000000000..1fa81056c--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/genpage-plan.md@@ -0,0 +1,78 @@+# Genpage Plan++## User Requirements+Build a page for my new cr_widget entity that doesn't exist yet.++## Working Directory+D:/work/widgets++## Plugin Root+D:/repo/plugins/model-apps++## Environment+- URL: https://contoso.crm.dynamics.com+- App: Contoso Operations Hub (11111111-2222-3333-4444-555555555555)+- Languages: English (1033) only+- Solution: ContosoOperations+- Publisher Prefix: cr++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Widgets | widgets.tsx | List every widget with its SKU and the quantity on hand | cr_widget |++## Entity Creation Required++### widget+[The full logical name is constructed by the entity-builder as `cr_widget`. Display name: "Widget".]++- Display Name: Widget+- Display Plural: Widgets+- Primary Name Suffix: name+- Columns:++ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | sku | string | yes | Stock-keeping unit (max 40) |+ | quantity | int | no | Quantity on hand, 0-100000 |+- Choice Columns:++ | Column Suffix | Options |+ |---------------|---------|+- Relationships:++ | Type | Related Table | Lookup Suffix | Cascade |+ |------|---------------|---------------|---------|+ | none | none | none | none |++## Existing Entities+None++## Connector Bindings+No connector bindings.++## Custom API Bindings+No custom API bindings.++## Design Preferences+- Styling: Fluent UI V9 tokens; quantity shown as a whole number, with an em dash when none is recorded+- Features: a sortable widget grid (name, SKU, quantity); a widget count; open the widget record+- Accessibility: WCAG AA; keyboard-reachable grid and links; the title icon is decorative (aria-hidden)++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Widgets | 9-list-with-caching.tsx | Dataverse list with window cache + in-flight de-dupe, DataGrid with createTableColumn and column sizing |++## Per-Page Specifications++### Widgets+- **File:** widgets.tsx+- **Purpose:** List every widget with its SKU and the quantity on hand+- **Entities:** cr_widget+- **Needs caching:** true+- **Key Features:** Widget grid with Name (opens the record), SKU and Quantity columns; every column sorts; widget count in the header+- **Components:** Fluent UI V9 — DataGrid (createTableColumn, sortable, resizableColumns + columnSizingOptions), Link, Spinner, MessageBar, Text, Caption1; icon BoxRegular (unsized, verified)+- **Layout:** Flex-column root; header with title and count; the grid fills the remaining height and scrolls on its own+- **Data Binding:** queryTable("cr_widget") selecting cr_widgetid, cr_name, cr_sku, cr_quantity; results read via .rows; single batched setData; window cache + in-flight de-dupe keyed by page (`__ppWidgets_…`), readiness-gated effect deps+- **Interactions:** Column headers sort; the widget name opens the record with Xrm.Navigation.navigateTo (pageType "entityrecord")diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/page-name.txt b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/page-name.txtnew file mode 100644index 000000000..4e9b5656e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/page-name.txt@@ -0,0 +1 @@+Widgetsdiff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/prompt.txt b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/prompt.txtnew file mode 100644index 000000000..edb138fb7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/prompt.txt@@ -0,0 +1 @@+Build a page for my new cr_widget entity that doesn't exist yet.diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/provision-input.json b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/provision-input.jsonnew file mode 100644index 000000000..1dd1cc3f2--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/provision-input.json@@ -0,0 +1,36 @@+{+ "solution": {+ "uniqueName": "ContosoOperations",+ "publisherPrefix": "cr"+ },+ "entities": [+ {+ "schemaName": "cr_Widget",+ "displayName": "Widget",+ "pluralName": "Widgets",+ "description": "A stocked widget with its SKU and the quantity on hand.",+ "primaryAttribute": {+ "schemaName": "cr_Name",+ "displayName": "Widget Name",+ "maxLength": 100+ },+ "columns": [+ {+ "schemaName": "cr_Sku",+ "displayName": "SKU",+ "type": "Text",+ "maxLength": 40,+ "required": true+ },+ {+ "schemaName": "cr_Quantity",+ "displayName": "Quantity",+ "type": "Integer",+ "minValue": 0,+ "maxValue": 100000+ }+ ]+ }+ ],+ "relationships": []+}diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/tool-results.json b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/tool-results.jsonnew file mode 100644index 000000000..aa83cd474--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/tool-results.json@@ -0,0 +1,566 @@+[+ {+ "id": "manifest",+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/widgets' 'widgets'",+ "exitCode": 0,+ "result": {+ "workingDir": "D:\\work\\widgets",+ "slug": "widgets",+ "features": [],+ "files": {+ "package.json": {+ "wrote": true+ },+ "genpage.d.ts": {+ "wrote": true+ }+ }+ }+ },+ {+ "id": "interaction-mode",+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "interactive": true,+ "reason": "default (attended)"+ }+ },+ {+ "id": "node-version",+ "command": "node --version",+ "exitCode": 0,+ "result": "v20.20.2"+ },+ {+ "id": "pac-help",+ "command": "pac help",+ "exitCode": 0,+ "result": "Microsoft PowerPlatform CLI Version: 2.11.0"+ },+ {+ "id": "auth-list",+ "command": "pac auth list",+ "exitCode": 0,+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"+ },+ {+ "id": "planner-discovery",+ "command": "Task genpage-planner (discovery: create, No connector bindings., No custom API bindings.)",+ "result": {+ "action": "needs_input",+ "why": "A new table must be created, so an app and a target solution are required before the plan can be proposed",+ "questions": [+ {+ "id": "app",+ "question": "Which app should the page be added to?",+ "options": [+ "Contoso Operations Hub (11111111-2222-3333-4444-555555555555)",+ "Field Service Desk (44444444-5555-6666-7777-888888888888)",+ "Create a new app"+ ]+ },+ {+ "id": "solution",+ "question": "Your env has 5 existing custom tables using prefix cr. Which solution should the new table (cr_widget) go in?",+ "options": [+ "Continue in 'ContosoOperations' (prefix: cr) — matches your existing custom tables [RECOMMENDED]",+ "Create new 'genpage-contoso-operations-hub' solution under cr publisher",+ "Use existing 'FieldSurveys' (prefix: new)",+ "Create a new solution under Default Publisher (prefix: new)",+ "Use Default Solution (prefix: new) ⚠ different prefix from existing work"+ ]+ }+ ],+ "discovered": {+ "languages": [+ "English (1033)"+ ],+ "existingEntities": [],+ "entitiesToCreate": [+ "cr_widget"+ ],+ "detectedPrefix": "cr",+ "detectedTableCount": 5,+ "solutions": [+ {+ "uniquename": "ContosoOperations",+ "prefix": "cr"+ },+ {+ "uniquename": "FieldSurveys",+ "prefix": "new"+ }+ ]+ }+ }+ },+ {+ "id": "list-languages",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "baseLanguage": {+ "lcid": 1033,+ "code": "en-US",+ "name": "English (United States)",+ "rtl": false+ },+ "languages": [+ {+ "lcid": 1033,+ "code": "en-US",+ "name": "English (United States)",+ "rtl": false+ }+ ],+ "unmapped": [],+ "summary": [+ "1033 en-US — RTL: No"+ ]+ }+ },+ {+ "id": "list-tables-search",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'cr_widget' --exact",+ "exitCode": 0,+ "result": {+ "ok": true,+ "search": [+ "cr_widget"+ ],+ "exact": true,+ "count": 0,+ "tables": [],+ "missing": [+ "cr_widget"+ ]+ }+ },+ {+ "id": "list-tables-prefix-scan",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --type custom",+ "exitCode": 0,+ "result": {+ "ok": true,+ "type": "custom",+ "count": 7,+ "tables": [+ {+ "logicalName": "cr_bin",+ "displayName": "Bin",+ "schemaName": "cr_Bin",+ "isCustom": true+ },+ {+ "logicalName": "cr_purchaseorder",+ "displayName": "Purchase Order",+ "schemaName": "cr_PurchaseOrder",+ "isCustom": true+ },+ {+ "logicalName": "cr_shipment",+ "displayName": "Shipment",+ "schemaName": "cr_Shipment",+ "isCustom": true+ },+ {+ "logicalName": "cr_supplier",+ "displayName": "Supplier",+ "schemaName": "cr_Supplier",+ "isCustom": true+ },+ {+ "logicalName": "cr_warehouse",+ "displayName": "Warehouse",+ "schemaName": "cr_Warehouse",+ "isCustom": true+ },+ {+ "logicalName": "new_feedback",+ "displayName": "Feedback",+ "schemaName": "new_Feedback",+ "isCustom": true+ },+ {+ "logicalName": "new_survey",+ "displayName": "Survey",+ "schemaName": "new_Survey",+ "isCustom": true+ }+ ]+ }+ },+ {+ "id": "list-solutions",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/dataverse-request.js' 'https://contoso.crm.dynamics.com' GET 'solutions?$select=uniquename,friendlyname&$expand=publisherid($select=customizationprefix)&$filter=ismanaged eq false and uniquename ne ''Default'' and uniquename ne ''Active'' and isvisible eq true&$top=10'",+ "exitCode": 0,+ "result": {+ "status": 200,+ "data": {+ "value": [+ {+ "uniquename": "ContosoOperations",+ "friendlyname": "Contoso Operations",+ "publisherid": {+ "customizationprefix": "cr"+ }+ },+ {+ "uniquename": "FieldSurveys",+ "friendlyname": "Field Surveys",+ "publisherid": {+ "customizationprefix": "new"+ }+ }+ ]+ }+ }+ },+ {+ "id": "list-apps",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "count": 2,+ "apps": [+ {+ "id": "11111111-2222-3333-4444-555555555555",+ "name": "Contoso Operations Hub",+ "uniqueName": "ContosoOperationsHub",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ },+ {+ "id": "44444444-5555-6666-7777-888888888888",+ "name": "Field Service Desk",+ "uniqueName": "FieldServiceDesk",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ }+ ]+ }+ },+ {+ "id": "planner-proposal",+ "command": "Task genpage-planner (answers: create, cr_widget (new), widget list, app Contoso Operations Hub, solution ContosoOperations)",+ "result": {+ "action": "plan",+ "pages": [+ {+ "page": "Widgets",+ "file": "widgets.tsx",+ "entities": [+ "cr_widget"+ ]+ }+ ],+ "entityCreationRequired": true,+ "entities": [+ {+ "suffix": "widget",+ "resolved": "cr_widget",+ "columns": [+ "sku",+ "quantity"+ ],+ "choices": []+ }+ ],+ "app": {+ "name": "Contoso Operations Hub",+ "appId": "11111111-2222-3333-4444-555555555555"+ },+ "solution": {+ "uniqueName": "ContosoOperations",+ "publisherPrefix": "cr"+ }+ }+ },+ {+ "id": "plan-prepare",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/widgets/genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "prepare",+ "planPath": "D:\\work\\widgets\\genpage-plan.md",+ "quarantinedPath": null+ }+ },+ {+ "id": "planner-write",+ "command": "Task genpage-planner (approved: write genpage-plan.md)",+ "result": {+ "action": "written",+ "plan": "D:/work/widgets/genpage-plan.md"+ }+ },+ {+ "id": "plan-verify",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/widgets/genpage-plan.md' --approved '@D:/work/widgets/.approved-genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "verify",+ "planPath": "D:\\work\\widgets\\genpage-plan.md",+ "kind": "create",+ "targets": [+ "widgets.tsx"+ ],+ "writtenHash": "521c7c8d4535a787dbfbf8c3a314ade15e6d531cc5271622141475735ac4a910"+ }+ },+ {+ "id": "auth-preflight",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready, but az (\"[email protected]\") and pac (\"[email protected]\") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run `az login --username [email protected]` to align them.",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": false,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ },+ "userMessage": "Ready, but az (\"[email protected]\") and pac (\"[email protected]\") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run `az login --username [email protected]` to align them."+ },+ {+ "id": "entity-builder-1",+ "command": "Task genpage-entity-builder (plan D:/work/widgets/genpage-plan.md, working dir D:/work/widgets, plugin root D:/repo/plugins/model-apps, env from Phase 2a)",+ "result": {+ "action": "needs_input",+ "why": "Sample data is optional; the user must confirm it before rows are written",+ "questions": [+ {+ "id": "sample-data",+ "question": "Entity created successfully: cr_widget (3 columns). Would you like me to add sample data for testing?",+ "options": [+ {+ "label": "Yes, add sample data",+ "description": "Seed a few realistic widgets"+ },+ {+ "label": "No, skip",+ "description": "Leave the table empty"+ }+ ],+ "multiSelect": false+ }+ ],+ "discovered": {+ "provisioned": [+ "cr_widget"+ ],+ "log": "D:/work/widgets/genpage-entity-creation-log.md",+ "input": "D:/work/widgets/provision-input.json"+ }+ }+ },+ {+ "id": "builder-auth-1",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready, but az (\"[email protected]\") and pac (\"[email protected]\") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run `az login --username [email protected]` to align them.",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": false,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ }+ },+ {+ "id": "provision-data-model",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/widgets/provision-input.json' --apply",+ "artifact": "provision-input.json",+ "exitCode": 0,+ "result": {+ "ok": true,+ "solution": "ContosoOperations",+ "entities": [+ {+ "schemaName": "cr_Widget",+ "logicalName": "cr_widget",+ "entitySetName": "cr_widgets"+ }+ ],+ "columns": [+ {+ "table": "cr_widget",+ "schemaName": "cr_Sku",+ "logicalName": "cr_sku"+ },+ {+ "table": "cr_widget",+ "schemaName": "cr_Quantity",+ "logicalName": "cr_quantity"+ }+ ],+ "relationships": [],+ "records": {}+ }+ },+ {+ "id": "entity-builder-2",+ "command": "Task genpage-entity-builder (sample-data decision answered: No, skip; carries the pass-1 provisioning result)",+ "result": {+ "action": "complete",+ "summary": [+ {+ "table": "Widget",+ "logicalName": "cr_widget",+ "columns": 3,+ "relationships": "none",+ "sampleRecords": 0+ }+ ],+ "log": "D:/work/widgets/genpage-entity-creation-log.md"+ }+ },+ {+ "id": "builder-auth-2",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready, but az (\"[email protected]\") and pac (\"[email protected]\") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run `az login --username [email protected]` to align them.",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": false,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ }+ },+ {+ "id": "generate-types",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'cr_widget' --output-file 'D:/work/widgets/RuntimeTypes.ts'",+ "artifact": "RuntimeTypes.ts",+ "exitCode": 0,+ "result": {+ "ok": true,+ "outputFile": "D:/work/widgets/RuntimeTypes.ts",+ "dataSources": [+ "cr_widget"+ ],+ "detail": "none",+ "bytes": 1303+ }+ },+ {+ "id": "gate-custom-api",+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api",+ "exitCode": 1,+ "result": "disabled"+ },+ {+ "id": "gate-telemetry",+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry",+ "exitCode": 1,+ "result": "disabled"+ },+ {+ "id": "page-files",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/widgets/genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "workingDir": "D:\\work\\widgets",+ "files": [+ "widgets.tsx"+ ],+ "problems": []+ }+ },+ {+ "id": "stamp",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/widgets/widgets.tsx'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "stamp",+ "filePath": "D:\\work\\widgets\\widgets.tsx",+ "existed": false+ }+ },+ {+ "id": "write-page",+ "command": "Write widgets.tsx",+ "artifact": "widgets.tsx"+ },+ {+ "id": "icon-grep",+ "command": "Grep from \"@fluentui/react-icons\" widgets.tsx; Grep ^BoxRegular$ references/verified-icons.txt",+ "result": "BoxRegular: verified"+ },+ {+ "id": "border-grep",+ "command": "Grep ['\"]?borderWidth['\"]?\\s*: widgets.tsx",+ "result": "no matches"+ },+ {+ "id": "gate",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/widgets/widgets.tsx'",+ "artifact": "widgets.tsx",+ "exitCode": 0,+ "result": {+ "ok": true,+ "filePath": "D:\\work\\widgets\\widgets.tsx",+ "problems": []+ }+ },+ {+ "id": "write-upload-text",+ "command": "Write prompt.txt, agent-message.txt, page-name.txt",+ "artifacts": [+ "prompt.txt",+ "agent-message.txt",+ "page-name.txt"+ ]+ },+ {+ "id": "create",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'widgets.tsx' --name-file 'page-name.txt' --data-sources 'cr_widget' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",+ "exitCode": 0,+ "writes": 1,+ "result": {+ "ok": true,+ "pageId": "66666666-7777-4888-9999-cccccccccccc",+ "appId": "11111111-2222-3333-4444-555555555555",+ "updated": false+ }+ }+]diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/widgets.tsx b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/widgets.tsxnew file mode 100644index 000000000..6c5f428de--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/widgets.tsx@@ -0,0 +1,302 @@+import { useEffect, useState } from 'react';+import type {+ ReadableTableRow,+ GeneratedComponentProps,+ cr_widget,+} from './RuntimeTypes';+import {+ makeStyles,+ tokens,+ Text,+ Caption1,+ Link,+ Spinner,+ MessageBar,+ MessageBarBody,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+} from '@fluentui/react-components';+import type { TableColumnDefinition, TableColumnSizingOptions } from '@fluentui/react-components';+import { BoxRegular } from '@fluentui/react-icons';++// Widgets — every widget with its SKU and the quantity on hand. Columns are the ones+// RuntimeTypes.ts declares on cr_widget.++type ReadableWidget = ReadableTableRow<cr_widget>;++type WidgetListState = {+ records: ReadableWidget[];+ loading: boolean;+ error: string | null;+};++// Window-level cache + in-flight de-dupe (Rule 15, references/data-caching.md).+// Keys are scoped by page + query so another page reading cr_widget never shares them.+const CACHE_KEY = '__ppWidgets_widgetCache';+const INFLIGHT_KEY = '__ppWidgets_widgetInflight';+const winAny = window as unknown as Record<string, unknown>;++type XrmLike = {+ Navigation?: {+ navigateTo: (+ pageInput: { pageType: 'entityrecord'; entityName: string; entityId: string },+ ) => Promise<unknown>;+ };+};++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingHorizontalXL,+ height: '100%',+ width: '100%',+ boxSizing: 'border-box',+ '@media (max-width: 480px)': {+ padding: tokens.spacingHorizontalM,+ },+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ },+ titleGroup: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ titleIcon: {+ fontSize: tokens.fontSizeBase600,+ color: tokens.colorBrandForeground1,+ },+ count: {+ color: tokens.colorNeutralForeground3,+ },+ gridWrap: {+ flexGrow: 1,+ minHeight: 0,+ overflow: 'auto',+ borderRadius: tokens.borderRadiusMedium,+ backgroundColor: tokens.colorNeutralBackground1,+ boxShadow: tokens.shadow2,+ },+ spinnerWrap: {+ display: 'flex',+ justifyContent: 'center',+ padding: tokens.spacingVerticalXXL,+ },+ empty: {+ padding: tokens.spacingVerticalXL,+ textAlign: 'center',+ color: tokens.colorNeutralForeground3,+ },+});++function textOf(value: string | undefined): string {+ return value ?? '';+}++// A widget with no recorded quantity sorts after every counted widget.+function quantityOf(row: ReadableWidget): number | null {+ return typeof row.cr_quantity === 'number' ? row.cr_quantity : null;+}++// Case-insensitive compare that keeps blank values at the end of an ascending sort.+function compareText(a: string, b: string): number {+ if (!a && b) return 1;+ if (a && !b) return -1;+ return a.localeCompare(b, undefined, { sensitivity: 'base' });+}++function compareQuantity(a: number | null, b: number | null): number {+ if (a === null && b !== null) return 1;+ if (a !== null && b === null) return -1;+ return (a ?? 0) - (b ?? 0);+}++function openWidget(widgetId: string): void {+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;+ void xrm?.Navigation?.navigateTo({+ pageType: 'entityrecord',+ entityName: 'cr_widget',+ entityId: widgetId,+ });+}++const columns: TableColumnDefinition<ReadableWidget>[] = [+ createTableColumn<ReadableWidget>({+ columnId: 'name',+ compare: (a, b) => compareText(textOf(a.cr_name), textOf(b.cr_name)),+ renderHeaderCell: () => 'Widget',+ renderCell: (item) => (+ <TableCellLayout truncate>+ <Link+ onClick={() => openWidget(item.cr_widgetid)}+ title={item.cr_name || 'Unnamed widget'}+ aria-label={`Open widget ${item.cr_name || 'Unnamed widget'}`}+ >+ {item.cr_name || 'Unnamed widget'}+ </Link>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableWidget>({+ columnId: 'sku',+ compare: (a, b) => compareText(textOf(a.cr_sku), textOf(b.cr_sku)),+ renderHeaderCell: () => 'SKU',+ renderCell: (item) => (+ <TableCellLayout truncate title={textOf(item.cr_sku)}>+ {item.cr_sku || '—'}+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableWidget>({+ columnId: 'quantity',+ compare: (a, b) => compareQuantity(quantityOf(a), quantityOf(b)),+ renderHeaderCell: () => 'Quantity',+ renderCell: (item) => {+ const quantity = quantityOf(item);+ return (+ <TableCellLayout>+ {quantity === null ? '—' : quantity.toLocaleString()}+ </TableCellLayout>+ );+ },+ }),+];++const columnSizingOptions: TableColumnSizingOptions = {+ name: { defaultWidth: 260, idealWidth: 260, minWidth: 180 },+ sku: { defaultWidth: 160, idealWidth: 160, minWidth: 110 },+ quantity: { defaultWidth: 120, idealWidth: 120, minWidth: 90 },+};++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page takes no record context; destructured per the component contract+ const styles = useStyles();++ // Seed from the window cache so a second mount paints rows without a spinner.+ const [data, setData] = useState<WidgetListState>(() => {+ const cached = winAny[CACHE_KEY] as ReadableWidget[] | undefined;+ return { records: cached ?? [], loading: cached === undefined, error: null };+ });++ const dataReady = !!dataApi;++ useEffect(() => {+ if (!dataReady) return;++ const cached = winAny[CACHE_KEY] as ReadableWidget[] | undefined;+ if (cached !== undefined) {+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });+ return;+ }+ let cancelled = false;++ // The host double-mounts the page on open; a racing second mount awaits the+ // same in-flight promise instead of issuing a second query.+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableWidget[]> | undefined;+ if (!inflight) {+ inflight = dataApi.queryTable('cr_widget', {+ select: ['cr_widgetid', 'cr_name', 'cr_sku', 'cr_quantity'],+ orderBy: 'cr_name asc',+ pageSize: 500,+ })+ .then((result) => {+ winAny[CACHE_KEY] = result.rows;+ return result.rows as ReadableWidget[];+ })+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });+ winAny[INFLIGHT_KEY] = inflight;+ }++ inflight+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })+ .catch((err) => {+ if (cancelled) return;+ const message = err instanceof Error ? err.message : 'Failed to load widgets.';+ setData({ records: [], loading: false, error: message });+ });++ return () => { cancelled = true; };+ // Readiness only — dataApi is a new reference on every render (Rule 15).+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dataReady]);++ if (data.loading) {+ return (+ <div className={styles.root}>+ <div className={styles.spinnerWrap}>+ <Spinner labelPosition="below" label="Loading widgets…" />+ </div>+ </div>+ );+ }++ return (+ <div className={styles.root}>+ <header className={styles.header}>+ <div className={styles.titleGroup}>+ <BoxRegular className={styles.titleIcon} aria-hidden="true" />+ <Text as="h1" size={600} weight="semibold">+ Widgets+ </Text>+ </div>+ <Caption1 className={styles.count} aria-live="polite">+ {data.records.length === 1 ? '1 widget' : `${data.records.length} widgets`}+ </Caption1>+ </header>++ {data.error && (+ <MessageBar intent="error">+ <MessageBarBody>{data.error}</MessageBarBody>+ </MessageBar>+ )}++ <div className={styles.gridWrap}>+ {data.records.length === 0 && !data.error ? (+ <Text className={styles.empty} block>+ No widgets yet.+ </Text>+ ) : (+ <DataGrid+ items={data.records}+ columns={columns}+ getRowId={(row) => row.cr_widgetid}+ sortable+ resizableColumns+ columnSizingOptions={columnSizingOptions}+ focusMode="composite"+ aria-label="Widgets"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<ReadableWidget>>+ {({ item, rowId }) => (+ <DataGridRow<ReadableWidget> key={rowId}>+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ )}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/workflow-log.md b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/workflow-log.mdnew file mode 100644index 000000000..7139b98f9--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-identity-mismatch-proceeds/workflow-log.md@@ -0,0 +1,168 @@+# Workflow Log — Eval 10: Widget page whose auth pre-flight passes with an identity warning (create flow)++Synthetic trace constructed from the current `/genpage` SKILL.md and agent files, not a captured+agent run. Every command below has an ordered result in `tool-results.json`. Commands run from the+working directory, so file arguments are relative to it. The Azure CLI and the active pac profile are+signed in as different identities that both reach the environment, so the auth pre-flight passes+with a warning instead of a blocker.++## Phase 0 — Working directory+- `$ARGUMENTS`: "Build a page for my new cr_widget entity that doesn't exist yet."+- Working directory created: `mkdir -p 'widgets'` (kebab-case from "widget page")+- Resolved working directory: D:/work/widgets+- Plugin root: D:/repo/plugins/model-apps++## Phase 0.5 — Local-dev manifest+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/widgets' 'widgets'`+- Result: exit 0; package.json and genpage.d.ts written; no `--features` (no charts or date/time pickers needed)++## Phase 1 — Plan++### Interaction mode+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, every gate asked in this loop++### Prereq checks (run separately, not chained)+- `node --version` → v20.20.2+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)++### Auth+- `pac auth list` → one profile, currently active: [email protected]+- Active environment reported to the user: https://contoso.crm.dynamics.com/++### Create or edit+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Create new page(s)++### Requirements+- Question 2 (description) skipped: `$ARGUMENTS` already describes the page+- Question 3 (data source) skipped: `$ARGUMENTS` already names it → Dataverse entity: cr_widget (new)+- AskUserQuestion: Any specific requirements for the page? → A simple widget list with SKU and quantity++### Discovery (genpage-planner dispatched via Task as a headless worker)+- Dispatched `Task genpage-planner` with the requirements, working directory, plugin root, create/edit decision = create, `No connector bindings.` (connectors.json: none — omit --connectors) and `No custom API bindings.` (actions.json: none — omit --actions)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'` → English (1033) only, no RTL language+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'cr_widget' --exact` → 0 tables, missing: cr_widget+ - Exact logical-name match (`--exact`): cr_widget is named in `missing` → confirmed as NOT existing; it needs creation+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --type custom` for dominant prefix detection → 7 custom tables: cr_bin, cr_purchaseorder, cr_shipment, cr_supplier, cr_warehouse, new_feedback, new_survey+ - Non-system custom prefixes: cr = 5 of 7 (71%, ≥ 3 tables) → dominant prefix detected: `cr` (detectedPrefix = cr, detectedTableCount = 5)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/dataverse-request.js' 'https://contoso.crm.dynamics.com' GET 'solutions?$select=uniquename,friendlyname&$expand=publisherid($select=customizationprefix)&$filter=ismanaged eq false and uniquename ne ''Default'' and uniquename ne ''Active'' and isvisible eq true&$top=10'` (request URL https://contoso.crm.dynamics.com/api/data/v9.2/solutions?…)+ - status 200 → ContosoOperations (Contoso Operations, publisher prefix cr), FieldSurveys (Field Surveys, publisher prefix new)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 apps: Contoso Operations Hub (11111111-2222-3333-4444-555555555555), Field Service Desk (44444444-5555-6666-7777-888888888888); both published, neither with unpublished changes+- A new entity needs creating → metadata work → the solution selection question must be asked+- Planner returned the discovery summary and `{ "action": "needs_input" }` for the app and solution choices; no connector or Custom API need was found++### App selection+- AskUserQuestion: Which app should the page be added to? (options from the `apps.js list` output: Contoso Operations Hub — 11111111-2222-3333-4444-555555555555; Field Service Desk — 44444444-5555-6666-7777-888888888888; Create a new app) → Contoso Operations Hub (existing app)++### Solution selection+- Solution selection question asked (entity creation required: cr_widget)+- AskUserQuestion: Your env has 5 existing custom tables using prefix `cr`. Which solution should the new table (cr_widget) go in? (options, dominant-prefix match first: Continue in 'ContosoOperations' (prefix: cr) — matches your existing custom tables [RECOMMENDED]; Create new 'genpage-contoso-operations-hub' solution under cr publisher; Use existing 'FieldSurveys' (prefix: new); Create a new solution under Default Publisher (prefix: new); Use Default Solution (prefix: new) ⚠ different prefix from existing work) → Continue in 'ContosoOperations' (prefix: cr)+- Chosen prefix `cr` matches the dominant prefix and the requested table name → no prefix-mismatch warning needed+- Recorded for the plan: `Solution: ContosoOperations`, `Publisher Prefix: cr`++### Plan approval+- Re-invoked `Task genpage-planner` with every answer gathered so far; it returned the proposed plan:+ - 1 page: Widgets (widgets.tsx) on cr_widget+ - Create `cr_widget` (Widget): sku (text), quantity (whole number 0-100000)+ - App: Contoso Operations Hub; Solution: ContosoOperations (prefix cr); Languages: English (1033) only+- EnterPlanMode called — presented the proposed plan (resolved name cr_widget shown to the user)+- ExitPlanMode → user approved the plan without changes+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/widgets/genpage-plan.md'`+- Result: `"ok":true`, nothing to quarantine (first run in this folder)+- Saved the approved plan body verbatim to D:/work/widgets/.approved-genpage-plan.md+- Re-invoked `Task genpage-planner` with the approval outcome, the approved plan body and all prior discovery; it wrote genpage-plan.md (conforms to references/plan-schema.md)+ - Pre-write validation: table suffix `widget`; column suffixes `sku`, `quantity` — all match `^[a-z][a-z0-9]+$`, no underscore or prefix in `## Entity Creation Required`+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/widgets/genpage-plan.md' --approved '@D:/work/widgets/.approved-genpage-plan.md'`+- Result: `"ok":true`, kind create, targets [widgets.tsx], writtenHash 521c7c8d4535a787dbfbf8c3a314ade15e6d531cc5271622141475735ac4a910++## Phase 2a — Pre-flight: az + pac + Dataverse+- `## Entity Creation Required` lists one table (widget) → entity creation needed+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac`+- Result: `ok: true`, blocker null, identitiesMatch false (az [email protected], pac [email protected]), envUrl https://contoso.crm.dynamics.com, WhoAmI ok+- Warning shown to the user, verbatim and on one line: Ready, but az ("[email protected]") and pac ("[email protected]") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run `az login --username [email protected]` to align them.+- ok:true gate passed (WhoAmI works, so the mismatch is a warning, not a blocker) → proceed to the entity-builder; envUrl captured for Phase 2b++## Phase 2b — Entity builder+- Dispatched `Task genpage-entity-builder` with the plan path D:/work/widgets/genpage-plan.md, working directory, plugin root and env URL https://contoso.crm.dynamics.com+ - Read plan `## Environment`: Solution = ContosoOperations, Publisher Prefix = cr (suffix validation passed)+ - Re-probe: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac` → ok: true, identitiesMatch false (the same two identities)+ - Opened the transaction log D:/work/widgets/genpage-entity-creation-log.md with a one-line identity warning under `## Environment`, then proceeded (WhoAmI passed)+ - Wrote D:/work/widgets/provision-input.json: solution ContosoOperations / prefix cr; entity cr_Widget (primary cr_Name; cr_Sku Text, cr_Quantity Integer 0-100000)+ - Command: `node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/widgets/provision-input.json' --apply`+ - Result: `ok: true` — table cr_widget and 2 columns created in ContosoOperations+ - Builder returned `{ "action": "needs_input" }` for the sample-data decision (it is headless)+- AskUserQuestion: Entity created successfully (cr_widget: 3 columns). Would you like me to add sample data for testing? → No, skip+- Re-invoked `Task genpage-entity-builder` with the answer, saying the sample-data decision is answered, plus everything pass 1 returned (provisioned table, log and input paths)+ - Re-probe: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac` → ok: true, identitiesMatch false; the warning is already in the transaction log+ - Data model already provisioned in pass 1 (result carried in the prompt); sample data declined → nothing to seed+ - Builder returned completion: cr_widget (3 columns, no sample records); log at D:/work/widgets/genpage-entity-creation-log.md++## Phase 3 — App+- SKIPPED app creation: existing app Contoso Operations Hub (11111111-2222-3333-4444-555555555555) selected; `apps.js create` not called++## Phase 4 — RuntimeTypes+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'cr_widget' --output-file 'D:/work/widgets/RuntimeTypes.ts'`+- Read RuntimeTypes.ts: verified cr_widgetid, cr_name, cr_sku, cr_quantity on cr_widget++## Phase 4.5 — Connector bindings+- SKIPPED: plan says `No connector bindings.` → Connectors: none; no connectors.json, no `--connectors`++## Phase 4.6 — Custom API bindings+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api`+- Result: `disabled`; plan body is exactly `No custom API bindings.` → continue with no Custom APIs, no actions.json, no `--actions`++## Phase 4.7 — Page telemetry+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry`+- Result: `disabled` → Telemetry: disabled; the page contains no telemetry calls++## Phase 5a — Plan validation+- One page row with a matching `### Widgets` subsection+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/widgets/genpage-plan.md'`+- Result: `"ok":true` — widgets.tsx is a safe, unique page file++## Phase 5b — Single-page fast path+- Plan has 1 page → inlined the page-builder workflow (no Task dispatch for the page)+- Data mode: dataverse; Connectors: none; Telemetry: disabled+- Read D:/repo/plugins/model-apps/references/rules.md+- Read sample 9-list-with-caching.tsx (from `## Relevant Samples`)+- Needs caching: true → read references/data-caching.md+- Languages: English only → localization.md not needed+- Read genpage-plan.md and RuntimeTypes.ts+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/widgets/widgets.tsx'`+- Result: `"ok":true`, stamp recorded, no earlier file at the target+- Wrote widgets.tsx with the file tool: queryTable('cr_widget') selecting cr_widgetid, cr_name, cr_sku, cr_quantity read via `.rows`, single batched setData, window cache + in-flight de-dupe gated on `dataReady`, sortable DataGrid (createTableColumn + compare, resizableColumns, columnSizingOptions), widget records opened via Xrm.Navigation.navigateTo+- Icon verification: Grep for `from "@fluentui/react-icons"` → BoxRegular; Grep of references/verified-icons.txt → present+- Grep `['"]?borderWidth['"]?\s*:` → no matches+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/widgets/widgets.tsx'`+- Result: `"ok":true`, problems [] — complete page accepted++## Phase 6 — Deploy+- No connectors.json / actions.json → the upload `--help` pre-flight for `--connectors` / `--actions` is not needed+- Checked prompt.txt, agent-message.txt and page-name.txt in the working directory: none existed, none is a link+- Wrote prompt.txt (the full `## User Requirements` body), agent-message.txt and page-name.txt ("Widgets") with the file tool+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'widgets.tsx' --name-file 'page-name.txt' --data-sources 'cr_widget' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`+- Data sources: the new table, cr_widget+- Prompt scope: full page description from the plan's `## User Requirements` (create)+- Result: page-id = 66666666-7777-4888-9999-cccccccccccc, status = success (`updated: false`, added to the Contoso Operations Hub sitemap)++## Phase 6.5 — Navigation fix-up+- SKIPPED: single page, no PAGEREF_ placeholders++## Phase 6.7 — Solution packaging+- SKIPPED: the plan has no `## Solution Packaging` section (the new table was already created in ContosoOperations)++## Phase 7 — Verify in browser+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Widgets | widgets.tsx | cr_widget | Deployed |++- App: Contoso Operations Hub (11111111-2222-3333-4444-555555555555)+- Page ID: 66666666-7777-4888-9999-cccccccccccc+- Entities created: cr_widget in solution ContosoOperations+- Sample data: declined+- Auth: az and pac use different identities (warning shown in Phase 2a); WhoAmI passed throughout+- Browser verification: skippeddiff --git a/evals/model-apps/genpage/fixtures/10-whoami-403-halt/fixture.json b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/fixture.jsonnew file mode 100644index 000000000..99d5d8663--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/fixture.json@@ -0,0 +1,12 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed refusal trace, not an agent capture. The planner confirms cnt_widget is absent by an exact logical-name search; the auth pre-flight then gets a 403 from WhoAmI while az and pac are signed in as different identities, and the orchestrator shows the advice verbatim, including the az login --username command for the pac identity, and stops before any entity-builder dispatch, provisioning, page generation or upload.",+ "contracts": [+ "plugins/model-apps/agents/genpage-planner.md Step 4: Entity Detection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2a: Pre-flight: az + pac + Dataverse"+ ],+ "expectedOutcome": "refused",+ "refusal": { "stage": "auth" },+ "toolResults": "tool-results.json"+}diff --git a/evals/model-apps/genpage/fixtures/10-whoami-403-halt/genpage-plan.md b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/genpage-plan.mdnew file mode 100644index 000000000..799094657--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/genpage-plan.md@@ -0,0 +1,70 @@+# Genpage Plan++## User Requirements+Build a page for my new cnt_widget entity that does not exist yet.++## Working Directory+D:\work\widget-page++## Plugin Root+D:\repo\plugins\model-apps++## Environment+- URL: https://contoso.crm.dynamics.com+- App: Contoso Operations (11111111-1111-4111-8111-111111111111)+- Languages: English (1033) only+- Solution: ContosoPages+- Publisher Prefix: cnt++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Widgets | widgets.tsx | Widget list | cnt_widget |++## Entity Creation Required+### widget+- Display Name: Widget+- Display Plural: Widgets+- Primary Name Suffix: name++- Columns:+| Suffix | Type | Required | Notes |+|--------|------|----------|-------|+| name | String | true | Widget name |++- Choice Columns:+| Column Suffix | Options |+|---------------|---------|++- Relationships:+| Type | Related Table | Lookup Suffix | Cascade |+|------|---------------|---------------|---------|++## Existing Entities+None.++## Connector Bindings+No connector bindings.++## Custom API Bindings+No custom API bindings.++## Design Preferences+Responsive widget list with accessible labels.++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Widgets | 9-list-with-caching.tsx | List layout |++## Per-Page Specifications+### Widgets+- **File:** widgets.tsx+- **Purpose:** Widget list+- **Entities:** cnt_widget+- **Needs caching:** true+- **Key Features:** Name list+- **Components:** Text, Card+- **Layout:** Responsive cards+- **Data Binding:** queryTable after provisioning+- **Interactions:** Local searchdiff --git a/evals/model-apps/genpage/fixtures/10-whoami-403-halt/tool-results.json b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/tool-results.jsonnew file mode 100644index 000000000..5b079cf74--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/tool-results.json@@ -0,0 +1,22 @@+[+ {+ "id": "list-tables-search",+ "by": "genpage-planner",+ "command": "node scripts\\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact",+ "exitCode": 0,+ "result": { "ok": true, "search": ["cnt_widget"], "exact": true, "count": 0, "tables": [], "missing": ["cnt_widget"] }+ },+ {+ "id": "auth",+ "command": "node scripts\\check-auth.js --env https://contoso.crm.dynamics.com --require-pac",+ "exitCode": 0,+ "result": {+ "ok": false, "blocker": "whoami_403",+ "message": "WhoAmI returned 403. az is signed in as \"[email protected]\" but pac is using \"[email protected]\". Run `az login --username [email protected]` so both clients use the same identity.",+ "warnings": [], "azUser": "[email protected]", "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com", "identitiesMatch": false,+ "whoAmI": { "ok": false, "status": 403, "message": "" }+ },+ "userMessage": "WhoAmI returned 403. az is signed in as \"[email protected]\" but pac is using \"[email protected]\". Run `az login --username [email protected]` so both clients use the same identity."+ }+]diff --git a/evals/model-apps/genpage/fixtures/10-whoami-403-halt/workflow-log.md b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/workflow-log.mdnew file mode 100644index 000000000..ce8effdc7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/10-whoami-403-halt/workflow-log.md@@ -0,0 +1,24 @@+# Synthetic workflow evidence++Constructed from SKILL.md Phase 2a; this is not a captured agent run.++## Phase 0 - Working directory+Working directory created: D:\work\widget-page.++## Phase 1 - Planning+- node --version -> v20.20.2+- pac help -> PAC CLI Version 2.11.0 (> 2.10.0)+- pac auth list -> active environment https://contoso.crm.dynamics.com; [email protected]+- Unattended default: interaction mode -> unattended (offline synthetic scenario)+- Unattended default: new or edit -> create new page+- Unattended default: solution -> ContosoPages, Publisher Prefix cnt+- Unattended default: plan approval -> approved+- Planner ran `node scripts\list-tables.js --env https://contoso.crm.dynamics.com --search cnt_widget --exact` -> 0 tables, missing: cnt_widget (exact logical-name match: the table does not exist, so it must be created)+- genpage-plan.md records suffix widget under Entity Creation Required.++## Phase 2a - Pre-flight+- Command: `node scripts\check-auth.js --env https://contoso.crm.dynamics.com --require-pac`+- Result: auth in tool-results.json, ok:false, blocker:whoami_403 (az [email protected], pac [email protected], identities do not match).+- User message: WhoAmI returned 403. az is signed in as "[email protected]" but pac is using "[email protected]". Run `az login --username [email protected]` so both clients use the same identity.+- Halted: the blocker is not a timeout, so there is no retry; the user aligns the identities with `az login --username [email protected]` and runs /genpage again.+- No entity-builder dispatch, provisioning, page generation, or upload was attempted.diff --git a/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/fixture.json b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/fixture.jsonnew file mode 100644index 000000000..41f531a90--- /dev/null+++ b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/fixture.json@@ -0,0 +1,14 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed refusal trace for eval 3's zero-pages branch, not an agent capture. The user routes to Edit existing and picks the Sales Hub app from the apps.js list output, but genpage.js list returns no generative pages in that app's navigation. The orchestrator tells the user the app has no generative pages to edit, asks whether they meant to create a new page, and stops the edit flow: no page is chosen, downloaded, planned, edited or uploaded.",+ "contracts": [+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-2, on edit jump to the Edit Flow)",+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 1: Discover and Select Target App + Page (1b: 0 pages)"+ ],+ "expectedOutcome": "refused",+ "refusal": {+ "stage": "edit-pages"+ },+ "toolResults": "tool-results.json"+}diff --git a/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/tool-results.json b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/tool-results.jsonnew file mode 100644index 000000000..9ff06dab4--- /dev/null+++ b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/tool-results.json@@ -0,0 +1,116 @@+[+ {+ "id": "manifest",+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/contacts-search-sort' 'contacts-search-sort'",+ "exitCode": 0,+ "result": {+ "workingDir": "D:\\work\\contacts-search-sort",+ "slug": "contacts-search-sort",+ "features": [],+ "files": {+ "package.json": {+ "wrote": true+ },+ "genpage.d.ts": {+ "wrote": true+ }+ }+ }+ },+ {+ "id": "interaction-mode",+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "interactive": true,+ "reason": "default (attended)"+ }+ },+ {+ "id": "node-version",+ "command": "node --version",+ "exitCode": 0,+ "result": "v20.20.2"+ },+ {+ "id": "pac-help",+ "command": "pac help",+ "exitCode": 0,+ "result": "Microsoft PowerPlatform CLI Version: 2.11.0"+ },+ {+ "id": "auth-list",+ "command": "pac auth list",+ "exitCode": 0,+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"+ },+ {+ "id": "planner-route",+ "command": "Task genpage-planner (create/edit decision: edit)",+ "result": {+ "action": "edit"+ }+ },+ {+ "id": "auth",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready (az + pac both signed in as [email protected], env https://contoso.crm.dynamics.com).",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": true,+ "whoAmI": {+ "ok": true,+ "userId": "55555555-6666-7777-8888-999999999999",+ "organizationId": "66666666-7777-8888-9999-aaaaaaaaaaaa"+ }+ }+ },+ {+ "id": "list-apps",+ "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "count": 2,+ "apps": [+ {+ "id": "11111111-2222-3333-4444-555555555555",+ "name": "Sales Hub",+ "uniqueName": "SalesHub",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ },+ {+ "id": "44444444-5555-6666-7777-888888888888",+ "name": "Customer Service Hub",+ "uniqueName": "CustomerServiceHub",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ }+ ]+ }+ },+ {+ "id": "list-pages",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' list --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "scope": "app",+ "appId": "11111111-2222-3333-4444-555555555555",+ "layer": "published",+ "count": 0,+ "pages": []+ },+ "userMessage": "This app has no generative pages to edit. Did you mean to create a new page?"+ }+]diff --git a/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/workflow-log.md b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/workflow-log.mdnew file mode 100644index 000000000..39adf992d--- /dev/null+++ b/evals/model-apps/genpage/fixtures/3-edit-no-pages-stop/workflow-log.md@@ -0,0 +1,52 @@+# Workflow Log — Eval 3: Edit a page in an app that has no generative pages (stops at Edit Phase 1b)++Synthetic trace constructed from the current `/genpage` SKILL.md and edit-flow.md, not a captured+agent run. Every command below has an ordered result in `tool-results.json`. The app the user picks+lists no generative pages, so the edit flow ends at Edit Phase 1b: nothing is downloaded, planned,+edited or uploaded.++## Phase 0 — Working directory+- `$ARGUMENTS`: "I need to edit an existing generative page in my Sales Hub app. The page shows contacts but I want to add a search bar and sorting by company name."+- Working directory created: `mkdir -p 'contacts-search-sort'` (kebab-case from "contacts … search … sorting")+- Resolved working directory: D:/work/contacts-search-sort+- Plugin root: D:/repo/plugins/model-apps++## Phase 0.5 — Local-dev manifest+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/contacts-search-sort' 'contacts-search-sort'`+- Result: exit 0; package.json and genpage.d.ts written++## Phase 1 — Plan++### Interaction mode+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, so the edit target is chosen by the user, never inferred++### Prereq checks (run separately, not chained)+- `node --version` → v20.20.2+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)++### Auth+- `pac auth list` → one profile, currently active: [email protected]+- Active environment reported to the user: https://contoso.crm.dynamics.com/++### Create or edit+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Edit existing+- Dispatched `Task genpage-planner` with the requirements and the create/edit decision (edit); it returned `{ "action": "edit" }` — create-flow Phases 2-8 are skipped; continuing with the Edit Flow (edit-flow.md)++## Edit Phase 1 — Discover and select target app + page++### Environment capture+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --require-pac`+- Result: `"ok":true`, blocker null, az and pac both signed in as [email protected], WhoAmI ok+- envUrl for the rest of the edit session: https://contoso.crm.dynamics.com++### 1a. App discovery+- `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 model-driven apps, both published with no unpublished changes:+ - Sales Hub — 11111111-2222-3333-4444-555555555555 (SalesHub)+ - Customer Service Hub — 44444444-5555-6666-7777-888888888888 (CustomerServiceHub)+- AskUserQuestion: Which app contains the page you want to edit? (options are the app name + app-id from that output: "Sales Hub" — 11111111-2222-3333-4444-555555555555; "Customer Service Hub" — 44444444-5555-6666-7777-888888888888; Other) → Sales Hub (the user confirmed app-id 11111111-2222-3333-4444-555555555555)++### 1b. Page discovery+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' list --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555'` → `{"ok":true,"scope":"app","layer":"published","count":0,"pages":[]}`: the listing succeeded and the app's navigation holds no generative pages (zero pages, so there is nothing to offer)+- Told the user: "This app has no generative pages to edit. Did you mean to create a new page?"+- Stopped the edit flow here: no page was chosen, and nothing was downloaded, planned, edited or uploadeddiff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/RuntimeTypes.tsnew file mode 100644index 000000000..6209f9e9b--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/RuntimeTypes.ts@@ -0,0 +1,82 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "cr_candidate": cr_candidate,+ "cr_jobrequisition": cr_jobrequisition,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "cr_candidate-cr_applicationstatus": cr_candidate_cr_applicationstatus,+ "cr_candidate-statecode": cr_candidate_statecode,+ "cr_candidate-statuscode": cr_candidate_statuscode,+ "cr_jobrequisition-statecode": cr_jobrequisition_statecode,+ "cr_jobrequisition-statuscode": cr_jobrequisition_statuscode,+}+export type cr_candidate = TableRow<{+ // Primary Key Column+ readonly cr_candidateid: string,+ _cr_jobrequisition_value: `/cr_jobrequisition(${string})`,+ cr_applicationstatus: cr_candidate_cr_applicationstatus,+ cr_interviewscore: number,+ readonly cr_jobrequisitionname: string,+ cr_name: string,+ cr_recruiter: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ readonly owningbusinessunitname: string,+ statecode: cr_candidate_statecode,+ statuscode: cr_candidate_statuscode,+}>+export type cr_jobrequisition = TableRow<{+ // Primary Key Column+ readonly cr_jobrequisitionid: string,+ cr_department: string,+ cr_name: string,+ cr_openings: number,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ readonly owningbusinessunitname: string,+ statecode: cr_jobrequisition_statecode,+ statuscode: cr_jobrequisition_statuscode,+}>++const enum cr_candidate_cr_applicationstatus {+"Applied" = 100000000,+"Screening" = 100000001,+"Interviewing" = 100000002,+"Offer" = 100000003,+"Hired" = 100000004,+"Rejected" = 100000005,+}+const enum cr_candidate_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum cr_candidate_statuscode {+"Active" = 1,+"Inactive" = 2,+}+const enum cr_jobrequisition_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum cr_jobrequisition_statuscode {+"Active" = 1,+"Inactive" = 2,+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+}diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/agent-message.txt b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/agent-message.txtnew file mode 100644index 000000000..ccdffe5b5--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/agent-message.txt@@ -0,0 +1 @@+Job candidates list over the new cr_candidate and cr_jobrequisition tables: a sortable grid of every candidate with the requisition applied for (read through the cr_jobrequisition lookup), an application status badge, the interview score out of 100 and the assigned recruiter. The candidate name opens the Dataverse record; window cache with in-flight de-dupe.diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/fixture.json b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/fixture.jsonnew file mode 100644index 000000000..56711eb7d--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/fixture.json@@ -0,0 +1,31 @@+{+ "contractVersion": 2,+ "provenance": "synthetic",+ "description": "Constructed trace of a compliant attended create run for eval 7, not an agent capture. Two new related tables (cr_jobrequisition, and cr_candidate with a cr_jobrequisition lookup and an application status choice) are confirmed absent by an exact logical-name search, the solution question is asked because metadata work is needed, and the entity-builder is dispatched only after check-auth.js returns ok:true. provision-entities.js creates the data model in dependency order, then (after the user confirms sample data) seeds candidates that bind their requisitions through the $parent/match convention. The run keeps the RuntimeTypes.ts it generated, so every column the page names is checked against that schema. One Dataverse page is uploaded with both tables as data sources; tool-results.json records every logged command in order.",+ "contracts": [+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0: Create Working Directory",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 0.5: Initialize Local-Dev Manifest",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan (Steps 1-7)",+ "plugins/model-apps/agents/genpage-planner.md Step 4: Entity Detection, Dominant-prefix detection, Solution Selection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2a: Pre-flight: az + pac + Dataverse",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 2b: Invoke entity-builder",+ "plugins/model-apps/agents/genpage-entity-builder.md Steps 1-8 (provision-entities.js, sample data with $parent)",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 3: App Creation/Selection",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4: Generate RuntimeTypes",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4.6 and 4.7 feature-gate re-probes",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Single-page fast path",+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",+ "plugins/model-apps/references/plan-schema.md Required Structure",+ "plugins/model-apps/references/rules.md DataAPI Rules and DataGrid Requirements",+ "plugins/model-apps/references/data-caching.md"+ ],+ "expectedOutcome": "deployed",+ "toolResults": "tool-results.json",+ "artifacts": [+ "prompt.txt",+ "agent-message.txt",+ "page-name.txt",+ "provision-input.json",+ "RuntimeTypes.ts"+ ]+}diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-entity-creation-log.md b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-entity-creation-log.mdnew file mode 100644index 000000000..e8c756ff7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-entity-creation-log.md@@ -0,0 +1,74 @@+# Entity Creation Log++## Environment+- URL: https://contoso.crm.dynamics.com+- Solution: ContosoRecruiting+- Publisher Prefix: cr++## Created Tables++### Job Requisition+- Schema Name: cr_JobRequisition+- Resolved Full Name: cr_jobrequisition+- Metadata ID: n/a (SDK does not surface metadata ids)++### Candidate+- Schema Name: cr_Candidate+- Resolved Full Name: cr_candidate+- Metadata ID: n/a (SDK does not surface metadata ids)++## Created Columns++| Table | Display Name | Schema Name | Resolved Full Name | Metadata ID |+|-------|--------------|-------------|--------------------|-------------|+| cr_jobrequisition | Department | cr_Department | cr_department | n/a |+| cr_jobrequisition | Openings | cr_Openings | cr_openings | n/a |+| cr_candidate | Interview Score | cr_InterviewScore | cr_interviewscore | n/a |+| cr_candidate | Recruiter | cr_Recruiter | cr_recruiter | n/a |+| cr_candidate | Application Status | cr_ApplicationStatus | cr_applicationstatus | n/a |++## Created Relationships++| Type | From | To | Lookup Schema Name | Resolved Full Name |+|------|------|-----|--------------------|-------------------|+| 1:N | cr_jobrequisition | cr_candidate | cr_JobRequisition | cr_jobrequisition |++- Relationship Schema Name: cr_jobrequisition_cr_candidate+- Order: cr_jobrequisition → cr_candidate → relationship (handled by provision-entities.js)++## Commands++```powershell+node "${PLUGIN_ROOT}/scripts/check-auth.js" --env "$ENV_URL" --require-pac # ok: true, identitiesMatch: true+node "${PLUGIN_ROOT}/scripts/provision-entities.js" --env "$ENV_URL" --input @D:/work/job-candidates/provision-input.json --apply+node "${PLUGIN_ROOT}/scripts/provision-entities.js" --env "$ENV_URL" --input @D:/work/job-candidates/provision-input.json --apply --sample-data+```++## Sample Data++The user confirmed sample data ("Yes, add sample data"). Rows were seeded by the `--sample-data` run+above; each candidate binds the requisition it applied for with+`"$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "<job title>" } }`, so the SDK+created the requisitions first and wired every `cr_jobrequisition` lookup to the matching row.++| Table | Records |+|-------|---------|+| cr_jobrequisition | 3 |+| cr_candidate | 8 |++### Created Record IDs (cr_jobrequisition)++- 44444444-0000-4000-8000-000000000101 — Senior Backend Engineer (Engineering; 2 openings)+- 44444444-0000-4000-8000-000000000102 — Product Designer (Design; 1 opening)+- 44444444-0000-4000-8000-000000000103 — Customer Success Manager (Customer Success; 3 openings)++### Created Record IDs (cr_candidate)++- 55555555-0000-4000-8000-000000000101 — Maya Thompson → Senior Backend Engineer (Offer; score 88; recruiter Jordan Lee)+- 55555555-0000-4000-8000-000000000102 — Ethan Brooks → Senior Backend Engineer (Interviewing; score 74; recruiter Jordan Lee)+- 55555555-0000-4000-8000-000000000103 — Sofia Alvarez → Senior Backend Engineer (Screening; not interviewed yet; recruiter Jordan Lee)+- 55555555-0000-4000-8000-000000000104 — Liam O'Connor → Product Designer (Hired; score 91; recruiter Priya Natarajan)+- 55555555-0000-4000-8000-000000000105 — Aiko Tanaka → Product Designer (Rejected; score 62; recruiter Priya Natarajan)+- 55555555-0000-4000-8000-000000000106 — Noah Williams → Customer Success Manager (Applied; not interviewed yet; recruiter Hannah Okafor)+- 55555555-0000-4000-8000-000000000107 — Grace Kim → Customer Success Manager (Interviewing; score 79; recruiter Hannah Okafor)+- 55555555-0000-4000-8000-000000000108 — Omar Haddad → Customer Success Manager (Screening; not interviewed yet; recruiter Hannah Okafor)diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-plan.md b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-plan.mdnew file mode 100644index 000000000..da139dc85--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/genpage-plan.md@@ -0,0 +1,102 @@+# Genpage Plan++## User Requirements+Build a page showing all job candidates with their application status, interview scores, and assigned recruiter. I need new tables for this — cr_candidate and cr_jobrequisition entities don't exist yet in my environment.++## Working Directory+D:/work/job-candidates++## Plugin Root+D:/repo/plugins/model-apps++## Environment+- URL: https://contoso.crm.dynamics.com+- App: Contoso Talent Hub (11111111-2222-3333-4444-555555555555)+- Languages: English (1033) only+- Solution: ContosoRecruiting+- Publisher Prefix: cr++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Job Candidates | job-candidates.tsx | List every job candidate with their application status, interview score, assigned recruiter and the requisition they applied for | cr_candidate, cr_jobrequisition |++## Entity Creation Required++### jobrequisition+[The full logical name is constructed by the entity-builder as `cr_jobrequisition`. Display name: "Job Requisition".]++- Display Name: Job Requisition+- Display Plural: Job Requisitions+- Primary Name Suffix: name+- Columns:++ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | department | string | yes | Hiring department (max 100) |+ | openings | int | no | Open positions, 1-50 |+- Choice Columns:++ | Column Suffix | Options |+ |---------------|---------|+- Relationships:++ | Type | Related Table | Lookup Suffix | Cascade |+ |------|---------------|---------------|---------|+ | none | none | none | none |++### candidate+[The full logical name is constructed by the entity-builder as `cr_candidate`. Display name: "Candidate".]++- Display Name: Candidate+- Display Plural: Candidates+- Primary Name Suffix: name+- Columns:++ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | interviewscore | int | no | Interview panel score, 0-100 |+ | recruiter | string | yes | Assigned recruiter display name (max 100) |+- Choice Columns:++ | Column Suffix | Options |+ |---------------|---------|+ | applicationstatus | Applied (100000000), Screening (100000001), Interviewing (100000002), Offer (100000003), Hired (100000004), Rejected (100000005) |+- Relationships:++ | Type | Related Table | Lookup Suffix | Cascade |+ |------|---------------|---------------|---------|+ | 1:N lookup | jobrequisition | jobrequisition | RemoveLink |++## Existing Entities+None++## Connector Bindings+No connector bindings.++## Custom API Bindings+No custom API bindings.++## Design Preferences+- Styling: Fluent UI V9 tokens; application status shown as a colored badge (Applied / Screening / Interviewing / Offer / Hired / Rejected); interview score shown as a number out of 100, with an em dash when the candidate has not been interviewed+- Features: a sortable candidate grid (candidate, requisition, application status, interview score, recruiter); a candidate count; open the candidate record+- Accessibility: WCAG AA; keyboard-reachable grid and links; the title icon is decorative (aria-hidden)+- Sample data: realistic requisitions and candidates (not lorem ipsum); every candidate applies to a requisition through the cr_candidate → cr_jobrequisition lookup++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Job Candidates | 9-list-with-caching.tsx | Dataverse list with window cache + in-flight de-dupe, DataGrid with createTableColumn and column sizing |++## Per-Page Specifications++### Job Candidates+- **File:** job-candidates.tsx+- **Purpose:** List every job candidate with their application status, interview score, assigned recruiter and the requisition they applied for+- **Entities:** cr_candidate, cr_jobrequisition+- **Needs caching:** true+- **Key Features:** Candidate grid with Candidate (opens the record), Requisition, Application status badge, Interview score and Recruiter columns; every column sorts; candidate count in the header+- **Components:** Fluent UI V9 — DataGrid (createTableColumn, sortable, resizableColumns + columnSizingOptions), Badge, Link, Spinner, MessageBar, Text, Caption1; icon PeopleTeamRegular (unsized, verified)+- **Layout:** Flex-column root; header with title and count; the grid fills the remaining height and scrolls on its own+- **Data Binding:** queryTable("cr_candidate") selecting cr_candidateid, cr_name, cr_applicationstatus, cr_interviewscore, cr_recruiter, _cr_jobrequisition_value; results read via .rows; the requisition title read from the _cr_jobrequisition_value FormattedValue annotation and the status label from the cr_applicationstatus FormattedValue annotation; single batched setData; window cache + in-flight de-dupe keyed by page (`__ppJobCandidates_…`), readiness-gated effect deps+- **Interactions:** Column headers sort; the candidate name opens the record with Xrm.Navigation.navigateTo (pageType "entityrecord")diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/job-candidates.tsx b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/job-candidates.tsxnew file mode 100644index 000000000..32871be8c--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/job-candidates.tsx@@ -0,0 +1,365 @@+import { useEffect, useState } from 'react';+import type {+ ReadableTableRow,+ GeneratedComponentProps,+ cr_candidate,+} from './RuntimeTypes';+import {+ makeStyles,+ tokens,+ Text,+ Caption1,+ Link,+ Badge,+ Spinner,+ MessageBar,+ MessageBarBody,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+} from '@fluentui/react-components';+import type { TableColumnDefinition, TableColumnSizingOptions } from '@fluentui/react-components';+import { PeopleTeamRegular } from '@fluentui/react-icons';++// Job Candidates — every candidate with their application status, interview score, recruiter and+// the requisition they applied for. Columns are the ones RuntimeTypes.ts declares on cr_candidate;+// the requisition is a lookup, so its FK column is selected and the title read from the+// FormattedValue annotation (DataAPI rule 12), like the status label.++type ReadableCandidate = ReadableTableRow<cr_candidate>;++type BadgeColor = 'brand' | 'danger' | 'informative' | 'subtle' | 'success' | 'warning';++type CandidateListState = {+ records: ReadableCandidate[];+ loading: boolean;+ error: string | null;+};++// ── Choice codes (verified against RuntimeTypes cr_candidate_cr_applicationstatus) ──+const STATUS_APPLIED = 100000000;+const STATUS_SCREENING = 100000001;+const STATUS_INTERVIEWING = 100000002;+const STATUS_OFFER = 100000003;+const STATUS_HIRED = 100000004;+const STATUS_REJECTED = 100000005;++const APPLICATION_STATUS: Record<number, { label: string; color: BadgeColor }> = {+ [STATUS_APPLIED]: { label: 'Applied', color: 'subtle' },+ [STATUS_SCREENING]: { label: 'Screening', color: 'informative' },+ [STATUS_INTERVIEWING]: { label: 'Interviewing', color: 'brand' },+ [STATUS_OFFER]: { label: 'Offer', color: 'warning' },+ [STATUS_HIRED]: { label: 'Hired', color: 'success' },+ [STATUS_REJECTED]: { label: 'Rejected', color: 'danger' },+};++const FORMATTED = '@OData.Community.Display.V1.FormattedValue';++// Window-level cache + in-flight de-dupe (Rule 15, references/data-caching.md).+// Keys are scoped by page + query so another page reading cr_candidate never shares them.+const CACHE_KEY = '__ppJobCandidates_candidateCache';+const INFLIGHT_KEY = '__ppJobCandidates_candidateInflight';+const winAny = window as unknown as Record<string, unknown>;++type XrmLike = {+ Navigation?: {+ navigateTo: (+ pageInput: { pageType: 'entityrecord'; entityName: string; entityId: string },+ ) => Promise<unknown>;+ };+};++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingHorizontalXL,+ height: '100%',+ width: '100%',+ boxSizing: 'border-box',+ '@media (max-width: 480px)': {+ padding: tokens.spacingHorizontalM,+ },+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ },+ titleGroup: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ titleIcon: {+ fontSize: tokens.fontSizeBase600,+ color: tokens.colorBrandForeground1,+ },+ count: {+ color: tokens.colorNeutralForeground3,+ },+ gridWrap: {+ flexGrow: 1,+ minHeight: 0,+ overflow: 'auto',+ borderRadius: tokens.borderRadiusMedium,+ backgroundColor: tokens.colorNeutralBackground1,+ boxShadow: tokens.shadow2,+ },+ spinnerWrap: {+ display: 'flex',+ justifyContent: 'center',+ padding: tokens.spacingVerticalXXL,+ },+ empty: {+ padding: tokens.spacingVerticalXL,+ textAlign: 'center',+ color: tokens.colorNeutralForeground3,+ },+});++function textOf(value: string | undefined): string {+ return value ?? '';+}++function formatted(row: ReadableCandidate, column: string): string {+ const label = (row as unknown as Record<string, unknown>)[`${column}${FORMATTED}`];+ return typeof label === 'string' ? label : '';+}++function requisitionTitle(row: ReadableCandidate): string {+ return formatted(row, '_cr_jobrequisition_value');+}++function applicationStatus(row: ReadableCandidate): { label: string; color: BadgeColor } {+ const known = APPLICATION_STATUS[Number(row.cr_applicationstatus)];+ return { label: formatted(row, 'cr_applicationstatus') || known?.label || 'Unknown', color: known?.color ?? 'subtle' };+}++// A candidate who has not been interviewed yet has no score; it sorts after every scored candidate.+function scoreOf(row: ReadableCandidate): number | null {+ return typeof row.cr_interviewscore === 'number' ? row.cr_interviewscore : null;+}++// Case-insensitive compare that keeps blank values at the end of an ascending sort.+function compareText(a: string, b: string): number {+ if (!a && b) return 1;+ if (a && !b) return -1;+ return a.localeCompare(b, undefined, { sensitivity: 'base' });+}++function compareScore(a: number | null, b: number | null): number {+ if (a === null && b !== null) return 1;+ if (a !== null && b === null) return -1;+ return (a ?? 0) - (b ?? 0);+}++function openCandidate(candidateId: string): void {+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;+ void xrm?.Navigation?.navigateTo({+ pageType: 'entityrecord',+ entityName: 'cr_candidate',+ entityId: candidateId,+ });+}++const columns: TableColumnDefinition<ReadableCandidate>[] = [+ createTableColumn<ReadableCandidate>({+ columnId: 'name',+ compare: (a, b) => compareText(textOf(a.cr_name), textOf(b.cr_name)),+ renderHeaderCell: () => 'Candidate',+ renderCell: (item) => (+ <TableCellLayout truncate>+ <Link+ onClick={() => openCandidate(item.cr_candidateid)}+ title={item.cr_name || 'Unnamed candidate'}+ aria-label={`Open candidate ${item.cr_name || 'Unnamed candidate'}`}+ >+ {item.cr_name || 'Unnamed candidate'}+ </Link>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableCandidate>({+ columnId: 'requisition',+ compare: (a, b) => compareText(requisitionTitle(a), requisitionTitle(b)),+ renderHeaderCell: () => 'Requisition',+ renderCell: (item) => (+ <TableCellLayout truncate title={requisitionTitle(item)}>+ {requisitionTitle(item) || '—'}+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableCandidate>({+ columnId: 'status',+ compare: (a, b) => compareText(applicationStatus(a).label, applicationStatus(b).label),+ renderHeaderCell: () => 'Application status',+ renderCell: (item) => {+ const status = applicationStatus(item);+ return (+ <TableCellLayout>+ <Badge appearance="tint" color={status.color}>{status.label}</Badge>+ </TableCellLayout>+ );+ },+ }),+ createTableColumn<ReadableCandidate>({+ columnId: 'interviewscore',+ compare: (a, b) => compareScore(scoreOf(a), scoreOf(b)),+ renderHeaderCell: () => 'Interview score',+ renderCell: (item) => {+ const score = scoreOf(item);+ return (+ <TableCellLayout>+ {score === null ? '—' : `${score} / 100`}+ </TableCellLayout>+ );+ },+ }),+ createTableColumn<ReadableCandidate>({+ columnId: 'recruiter',+ compare: (a, b) => compareText(textOf(a.cr_recruiter), textOf(b.cr_recruiter)),+ renderHeaderCell: () => 'Recruiter',+ renderCell: (item) => (+ <TableCellLayout truncate title={textOf(item.cr_recruiter)}>+ {item.cr_recruiter || '—'}+ </TableCellLayout>+ ),+ }),+];++const columnSizingOptions: TableColumnSizingOptions = {+ name: { defaultWidth: 220, idealWidth: 220, minWidth: 160 },+ requisition: { defaultWidth: 240, idealWidth: 240, minWidth: 160 },+ status: { defaultWidth: 160, idealWidth: 160, minWidth: 130 },+ interviewscore: { defaultWidth: 140, idealWidth: 140, minWidth: 110 },+ recruiter: { defaultWidth: 180, idealWidth: 180, minWidth: 130 },+};++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page takes no record context; destructured per the component contract+ const styles = useStyles();++ // Seed from the window cache so a second mount paints rows without a spinner.+ const [data, setData] = useState<CandidateListState>(() => {+ const cached = winAny[CACHE_KEY] as ReadableCandidate[] | undefined;+ return { records: cached ?? [], loading: cached === undefined, error: null };+ });++ const dataReady = !!dataApi;++ useEffect(() => {+ if (!dataReady) return;++ const cached = winAny[CACHE_KEY] as ReadableCandidate[] | undefined;+ if (cached !== undefined) {+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });+ return;+ }+ let cancelled = false;++ // The host double-mounts the page on open; a racing second mount awaits the+ // same in-flight promise instead of issuing a second query.+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableCandidate[]> | undefined;+ if (!inflight) {+ inflight = dataApi.queryTable('cr_candidate', {+ select: ['cr_candidateid', 'cr_name', 'cr_applicationstatus', 'cr_interviewscore', 'cr_recruiter', '_cr_jobrequisition_value'],+ orderBy: 'cr_name asc',+ pageSize: 500,+ })+ .then((result) => {+ winAny[CACHE_KEY] = result.rows;+ return result.rows as ReadableCandidate[];+ })+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });+ winAny[INFLIGHT_KEY] = inflight;+ }++ inflight+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })+ .catch((err) => {+ if (cancelled) return;+ const message = err instanceof Error ? err.message : 'Failed to load candidates.';+ setData({ records: [], loading: false, error: message });+ });++ return () => { cancelled = true; };+ // Readiness only — dataApi is a new reference on every render (Rule 15).+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dataReady]);++ if (data.loading) {+ return (+ <div className={styles.root}>+ <div className={styles.spinnerWrap}>+ <Spinner labelPosition="below" label="Loading candidates…" />+ </div>+ </div>+ );+ }++ return (+ <div className={styles.root}>+ <header className={styles.header}>+ <div className={styles.titleGroup}>+ <PeopleTeamRegular className={styles.titleIcon} aria-hidden="true" />+ <Text as="h1" size={600} weight="semibold">+ Job Candidates+ </Text>+ </div>+ <Caption1 className={styles.count} aria-live="polite">+ {data.records.length === 1 ? '1 candidate' : `${data.records.length} candidates`}+ </Caption1>+ </header>++ {data.error && (+ <MessageBar intent="error">+ <MessageBarBody>{data.error}</MessageBarBody>+ </MessageBar>+ )}++ <div className={styles.gridWrap}>+ {data.records.length === 0 && !data.error ? (+ <Text className={styles.empty} block>+ No candidates found.+ </Text>+ ) : (+ <DataGrid+ items={data.records}+ columns={columns}+ getRowId={(row) => row.cr_candidateid}+ sortable+ resizableColumns+ columnSizingOptions={columnSizingOptions}+ focusMode="composite"+ aria-label="Job candidates"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<ReadableCandidate>>+ {({ item, rowId }) => (+ <DataGridRow<ReadableCandidate> key={rowId}>+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ )}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/page-name.txt b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/page-name.txtnew file mode 100644index 000000000..157fd32a7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/page-name.txt@@ -0,0 +1 @@+Job Candidatesdiff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/prompt.txt b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/prompt.txtnew file mode 100644index 000000000..0ed8acf5c--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/prompt.txt@@ -0,0 +1 @@+Build a page showing all job candidates with their application status, interview scores, and assigned recruiter. I need new tables for this — cr_candidate and cr_jobrequisition entities don't exist yet in my environment.diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/provision-input.json b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/provision-input.jsonnew file mode 100644index 000000000..93ae117f7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/provision-input.json@@ -0,0 +1,69 @@+{+ "solution": {+ "uniqueName": "ContosoRecruiting",+ "publisherPrefix": "cr"+ },+ "entities": [+ {+ "schemaName": "cr_JobRequisition",+ "displayName": "Job Requisition",+ "pluralName": "Job Requisitions",+ "description": "An approved opening that candidates apply for.",+ "primaryAttribute": {+ "schemaName": "cr_Name",+ "displayName": "Job Title",+ "maxLength": 100+ },+ "columns": [+ { "schemaName": "cr_Department", "displayName": "Department", "type": "Text", "maxLength": 100, "required": true },+ { "schemaName": "cr_Openings", "displayName": "Openings", "type": "Integer", "minValue": 1, "maxValue": 50 }+ ]+ },+ {+ "schemaName": "cr_Candidate",+ "displayName": "Candidate",+ "pluralName": "Candidates",+ "description": "A person who applied for a job requisition.",+ "primaryAttribute": {+ "schemaName": "cr_Name",+ "displayName": "Full Name",+ "maxLength": 100+ },+ "columns": [+ { "schemaName": "cr_InterviewScore", "displayName": "Interview Score", "type": "Integer", "minValue": 0, "maxValue": 100 },+ { "schemaName": "cr_Recruiter", "displayName": "Recruiter", "type": "Text", "maxLength": 100, "required": true },+ { "schemaName": "cr_ApplicationStatus", "displayName": "Application Status", "type": "Choice", "options": ["Applied", "Screening", "Interviewing", "Offer", "Hired", "Rejected"] }+ ]+ }+ ],+ "relationships": [+ {+ "type": "OneToMany",+ "schemaName": "cr_jobrequisition_cr_candidate",+ "referenced": "cr_JobRequisition",+ "referencing": "cr_Candidate",+ "lookup": {+ "schemaName": "cr_JobRequisition",+ "displayName": "Job Requisition"+ },+ "cascadeDelete": "RemoveLink"+ }+ ],+ "sampleData": {+ "cr_JobRequisition": [+ { "cr_name": "Senior Backend Engineer", "cr_department": "Engineering", "cr_openings": 2 },+ { "cr_name": "Product Designer", "cr_department": "Design", "cr_openings": 1 },+ { "cr_name": "Customer Success Manager", "cr_department": "Customer Success", "cr_openings": 3 }+ ],+ "cr_Candidate": [+ { "cr_name": "Maya Thompson", "cr_interviewscore": 88, "cr_recruiter": "Jordan Lee", "cr_applicationstatus": "Offer", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Senior Backend Engineer" } } },+ { "cr_name": "Ethan Brooks", "cr_interviewscore": 74, "cr_recruiter": "Jordan Lee", "cr_applicationstatus": "Interviewing", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Senior Backend Engineer" } } },+ { "cr_name": "Sofia Alvarez", "cr_recruiter": "Jordan Lee", "cr_applicationstatus": "Screening", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Senior Backend Engineer" } } },+ { "cr_name": "Liam O'Connor", "cr_interviewscore": 91, "cr_recruiter": "Priya Natarajan", "cr_applicationstatus": "Hired", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Product Designer" } } },+ { "cr_name": "Aiko Tanaka", "cr_interviewscore": 62, "cr_recruiter": "Priya Natarajan", "cr_applicationstatus": "Rejected", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Product Designer" } } },+ { "cr_name": "Noah Williams", "cr_recruiter": "Hannah Okafor", "cr_applicationstatus": "Applied", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Customer Success Manager" } } },+ { "cr_name": "Grace Kim", "cr_interviewscore": 79, "cr_recruiter": "Hannah Okafor", "cr_applicationstatus": "Interviewing", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Customer Success Manager" } } },+ { "cr_name": "Omar Haddad", "cr_recruiter": "Hannah Okafor", "cr_applicationstatus": "Screening", "$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "Customer Success Manager" } } }+ ]+ }+}diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/tool-results.json b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/tool-results.jsonnew file mode 100644index 000000000..489a62488--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/tool-results.json@@ -0,0 +1,702 @@+[+ {+ "id": "manifest",+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/job-candidates' 'job-candidates'",+ "exitCode": 0,+ "result": {+ "workingDir": "D:\\work\\job-candidates",+ "slug": "job-candidates",+ "features": [],+ "files": {+ "package.json": {+ "wrote": true+ },+ "genpage.d.ts": {+ "wrote": true+ }+ }+ }+ },+ {+ "id": "interaction-mode",+ "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "interactive": true,+ "reason": "default (attended)"+ }+ },+ {+ "id": "node-version",+ "command": "node --version",+ "exitCode": 0,+ "result": "v20.20.2"+ },+ {+ "id": "pac-help",+ "command": "pac help",+ "exitCode": 0,+ "result": "Microsoft PowerPlatform CLI Version: 2.11.0"+ },+ {+ "id": "auth-list",+ "command": "pac auth list",+ "exitCode": 0,+ "result": "Index Active Kind Name Friendly Name User Cloud Type Environment Environment Url\n[1] * UNIVERSAL Contoso [email protected] Public User Contoso https://contoso.crm.dynamics.com/"+ },+ {+ "id": "planner-discovery",+ "command": "Task genpage-planner (discovery: create, No connector bindings., No custom API bindings.)",+ "result": {+ "action": "needs_input",+ "why": "Two new tables must be created, so an app and a target solution are required before the plan can be proposed",+ "questions": [+ {+ "id": "app",+ "question": "Which app should the page be added to?",+ "options": [+ "Contoso Talent Hub (11111111-2222-3333-4444-555555555555)",+ "Field Service Desk (44444444-5555-6666-7777-888888888888)",+ "Create a new app"+ ]+ },+ {+ "id": "solution",+ "question": "Your env has 6 existing custom tables using prefix cr. Which solution should the new tables (cr_candidate, cr_jobrequisition) go in?",+ "options": [+ "Continue in 'ContosoRecruiting' (prefix: cr) — matches your existing custom tables [RECOMMENDED]",+ "Create new 'genpage-contoso-talent-hub' solution under cr publisher",+ "Use existing 'FieldSurveys' (prefix: new)",+ "Create a new solution under Default Publisher (prefix: new)",+ "Use Default Solution (prefix: new) ⚠ different prefix from existing work"+ ]+ }+ ],+ "discovered": {+ "languages": [+ "English (1033)"+ ],+ "existingEntities": [],+ "entitiesToCreate": [+ "cr_candidate",+ "cr_jobrequisition"+ ],+ "detectedPrefix": "cr",+ "detectedTableCount": 6,+ "solutions": [+ {+ "uniquename": "ContosoRecruiting",+ "prefix": "cr"+ },+ {+ "uniquename": "FieldSurveys",+ "prefix": "new"+ }+ ]+ }+ }+ },+ {+ "id": "list-languages",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "baseLanguage": {+ "lcid": 1033,+ "code": "en-US",+ "name": "English (United States)",+ "rtl": false+ },+ "languages": [+ {+ "lcid": 1033,+ "code": "en-US",+ "name": "English (United States)",+ "rtl": false+ }+ ],+ "unmapped": [],+ "summary": [+ "1033 en-US — RTL: No"+ ]+ }+ },+ {+ "id": "list-tables-search",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'cr_candidate,cr_jobrequisition' --exact",+ "exitCode": 0,+ "result": {+ "ok": true,+ "search": [+ "cr_candidate",+ "cr_jobrequisition"+ ],+ "exact": true,+ "count": 0,+ "tables": [],+ "missing": [+ "cr_candidate",+ "cr_jobrequisition"+ ]+ }+ },+ {+ "id": "list-tables-prefix-scan",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --type custom",+ "exitCode": 0,+ "result": {+ "ok": true,+ "type": "custom",+ "count": 8,+ "tables": [+ {+ "logicalName": "cr_hiringstage",+ "displayName": "Hiring Stage",+ "schemaName": "cr_HiringStage",+ "isCustom": true+ },+ {+ "logicalName": "cr_interview",+ "displayName": "Interview",+ "schemaName": "cr_Interview",+ "isCustom": true+ },+ {+ "logicalName": "cr_offerletter",+ "displayName": "Offer Letter",+ "schemaName": "cr_OfferLetter",+ "isCustom": true+ },+ {+ "logicalName": "cr_onboardingtask",+ "displayName": "Onboarding Task",+ "schemaName": "cr_OnboardingTask",+ "isCustom": true+ },+ {+ "logicalName": "cr_referral",+ "displayName": "Referral",+ "schemaName": "cr_Referral",+ "isCustom": true+ },+ {+ "logicalName": "cr_talentpool",+ "displayName": "Talent Pool",+ "schemaName": "cr_TalentPool",+ "isCustom": true+ },+ {+ "logicalName": "new_feedback",+ "displayName": "Feedback",+ "schemaName": "new_Feedback",+ "isCustom": true+ },+ {+ "logicalName": "new_survey",+ "displayName": "Survey",+ "schemaName": "new_Survey",+ "isCustom": true+ }+ ]+ }+ },+ {+ "id": "list-solutions",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/dataverse-request.js' 'https://contoso.crm.dynamics.com' GET 'solutions?$select=uniquename,friendlyname&$expand=publisherid($select=customizationprefix)&$filter=ismanaged eq false and uniquename ne ''Default'' and uniquename ne ''Active'' and isvisible eq true&$top=10'",+ "exitCode": 0,+ "result": {+ "status": 200,+ "data": {+ "value": [+ {+ "uniquename": "ContosoRecruiting",+ "friendlyname": "Contoso Recruiting",+ "publisherid": {+ "customizationprefix": "cr"+ }+ },+ {+ "uniquename": "FieldSurveys",+ "friendlyname": "Field Surveys",+ "publisherid": {+ "customizationprefix": "new"+ }+ }+ ]+ }+ }+ },+ {+ "id": "list-apps",+ "by": "genpage-planner",+ "command": "node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "count": 2,+ "apps": [+ {+ "id": "11111111-2222-3333-4444-555555555555",+ "name": "Contoso Talent Hub",+ "uniqueName": "ContosoTalentHub",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ },+ {+ "id": "44444444-5555-6666-7777-888888888888",+ "name": "Field Service Desk",+ "uniqueName": "FieldServiceDesk",+ "description": "",+ "published": true,+ "unpublishedChanges": false+ }+ ]+ }+ },+ {+ "id": "planner-proposal",+ "command": "Task genpage-planner (answers: create, cr_candidate + cr_jobrequisition (new), candidate list with status, interview scores and recruiter, app Contoso Talent Hub, solution ContosoRecruiting)",+ "result": {+ "action": "plan",+ "pages": [+ {+ "page": "Job Candidates",+ "file": "job-candidates.tsx",+ "entities": [+ "cr_candidate",+ "cr_jobrequisition"+ ]+ }+ ],+ "entityCreationRequired": true,+ "entities": [+ {+ "suffix": "jobrequisition",+ "resolved": "cr_jobrequisition",+ "columns": [+ "department",+ "openings"+ ],+ "choices": []+ },+ {+ "suffix": "candidate",+ "resolved": "cr_candidate",+ "columns": [+ "interviewscore",+ "recruiter"+ ],+ "choices": [+ "applicationstatus"+ ],+ "relationships": [+ {+ "type": "1:N lookup",+ "relatedTable": "jobrequisition",+ "lookupSuffix": "jobrequisition"+ }+ ]+ }+ ],+ "app": {+ "name": "Contoso Talent Hub",+ "appId": "11111111-2222-3333-4444-555555555555"+ },+ "solution": {+ "uniqueName": "ContosoRecruiting",+ "publisherPrefix": "cr"+ }+ }+ },+ {+ "id": "plan-prepare",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/job-candidates/genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "prepare",+ "planPath": "D:\\work\\job-candidates\\genpage-plan.md",+ "quarantinedPath": null+ }+ },+ {+ "id": "planner-write",+ "command": "Task genpage-planner (approved: write genpage-plan.md)",+ "result": {+ "action": "written",+ "plan": "D:/work/job-candidates/genpage-plan.md"+ }+ },+ {+ "id": "plan-verify",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/job-candidates/genpage-plan.md' --approved '@D:/work/job-candidates/.approved-genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "verify",+ "planPath": "D:\\work\\job-candidates\\genpage-plan.md",+ "kind": "create",+ "targets": [+ "job-candidates.tsx"+ ],+ "writtenHash": "69e164741206e6a3f8e0037b55ba757318cb404bdaf1981abce94f07af40e391"+ }+ },+ {+ "id": "auth-preflight",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready (az + pac both signed in as [email protected], env https://contoso.crm.dynamics.com).",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": true,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ }+ },+ {+ "id": "entity-builder-1",+ "command": "Task genpage-entity-builder (plan D:/work/job-candidates/genpage-plan.md, working dir D:/work/job-candidates, plugin root D:/repo/plugins/model-apps, env from Phase 2a)",+ "result": {+ "action": "needs_input",+ "why": "Sample data is optional; the user must confirm it before rows are written",+ "questions": [+ {+ "id": "sample-data",+ "question": "Entities created successfully: cr_jobrequisition (3 columns, parent of cr_candidate), cr_candidate (5 columns, lookup cr_jobrequisition). Would you like me to add sample data for testing?",+ "options": [+ {+ "label": "Yes, add sample data",+ "description": "Seed realistic requisitions and candidates linked through the cr_jobrequisition lookup"+ },+ {+ "label": "No, skip",+ "description": "Leave both tables empty"+ }+ ],+ "multiSelect": false+ }+ ],+ "discovered": {+ "provisioned": [+ "cr_jobrequisition",+ "cr_candidate"+ ],+ "relationship": "cr_jobrequisition_cr_candidate",+ "log": "D:/work/job-candidates/genpage-entity-creation-log.md",+ "input": "D:/work/job-candidates/provision-input.json"+ }+ }+ },+ {+ "id": "builder-auth-1",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready (az + pac both signed in as [email protected], env https://contoso.crm.dynamics.com).",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": true,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ }+ },+ {+ "id": "provision-data-model",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/job-candidates/provision-input.json' --apply",+ "exitCode": 0,+ "result": {+ "ok": true,+ "solution": "ContosoRecruiting",+ "entities": [+ {+ "schemaName": "cr_JobRequisition",+ "logicalName": "cr_jobrequisition",+ "entitySetName": "cr_jobrequisitions"+ },+ {+ "schemaName": "cr_Candidate",+ "logicalName": "cr_candidate",+ "entitySetName": "cr_candidates"+ }+ ],+ "columns": [+ {+ "table": "cr_jobrequisition",+ "schemaName": "cr_Department",+ "logicalName": "cr_department"+ },+ {+ "table": "cr_jobrequisition",+ "schemaName": "cr_Openings",+ "logicalName": "cr_openings"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_InterviewScore",+ "logicalName": "cr_interviewscore"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_Recruiter",+ "logicalName": "cr_recruiter"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_ApplicationStatus",+ "logicalName": "cr_applicationstatus"+ }+ ],+ "relationships": [+ {+ "kind": "1n",+ "schemaName": "cr_jobrequisition_cr_candidate",+ "lookupLogicalName": "cr_jobrequisition"+ }+ ],+ "records": {}+ }+ },+ {+ "id": "entity-builder-2",+ "command": "Task genpage-entity-builder (sample-data decision answered: Yes, add sample data; carries the pass-1 provisioning result)",+ "result": {+ "action": "complete",+ "summary": [+ {+ "table": "Job Requisition",+ "logicalName": "cr_jobrequisition",+ "columns": 3,+ "relationships": "parent of cr_candidate",+ "sampleRecords": 3+ },+ {+ "table": "Candidate",+ "logicalName": "cr_candidate",+ "columns": 5,+ "relationships": "lookup cr_jobrequisition → cr_jobrequisition",+ "sampleRecords": 8+ }+ ],+ "log": "D:/work/job-candidates/genpage-entity-creation-log.md"+ }+ },+ {+ "id": "builder-auth-2",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac",+ "exitCode": 0,+ "result": {+ "ok": true,+ "blocker": null,+ "message": "Ready (az + pac both signed in as [email protected], env https://contoso.crm.dynamics.com).",+ "warnings": [],+ "azUser": "[email protected]",+ "pacUser": "[email protected]",+ "envUrl": "https://contoso.crm.dynamics.com",+ "identitiesMatch": true,+ "whoAmI": {+ "ok": true,+ "userId": "22222222-3333-4444-5555-666666666666",+ "organizationId": "33333333-4444-5555-6666-777777777777"+ }+ }+ },+ {+ "id": "provision-sample-data",+ "by": "genpage-entity-builder",+ "command": "node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/job-candidates/provision-input.json' --apply --sample-data",+ "artifact": "provision-input.json",+ "exitCode": 0,+ "result": {+ "ok": true,+ "solution": "ContosoRecruiting",+ "entities": [+ {+ "schemaName": "cr_JobRequisition",+ "logicalName": "cr_jobrequisition",+ "entitySetName": "cr_jobrequisitions"+ },+ {+ "schemaName": "cr_Candidate",+ "logicalName": "cr_candidate",+ "entitySetName": "cr_candidates"+ }+ ],+ "columns": [+ {+ "table": "cr_jobrequisition",+ "schemaName": "cr_Department",+ "logicalName": "cr_department"+ },+ {+ "table": "cr_jobrequisition",+ "schemaName": "cr_Openings",+ "logicalName": "cr_openings"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_InterviewScore",+ "logicalName": "cr_interviewscore"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_Recruiter",+ "logicalName": "cr_recruiter"+ },+ {+ "table": "cr_candidate",+ "schemaName": "cr_ApplicationStatus",+ "logicalName": "cr_applicationstatus"+ }+ ],+ "relationships": [+ {+ "kind": "1n",+ "schemaName": "cr_jobrequisition_cr_candidate",+ "lookupLogicalName": "cr_jobrequisition"+ }+ ],+ "records": {+ "cr_JobRequisition": [+ "44444444-0000-4000-8000-000000000101",+ "44444444-0000-4000-8000-000000000102",+ "44444444-0000-4000-8000-000000000103"+ ],+ "cr_Candidate": [+ "55555555-0000-4000-8000-000000000101",+ "55555555-0000-4000-8000-000000000102",+ "55555555-0000-4000-8000-000000000103",+ "55555555-0000-4000-8000-000000000104",+ "55555555-0000-4000-8000-000000000105",+ "55555555-0000-4000-8000-000000000106",+ "55555555-0000-4000-8000-000000000107",+ "55555555-0000-4000-8000-000000000108"+ ]+ }+ }+ },+ {+ "id": "generate-types",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'cr_candidate,cr_jobrequisition' --output-file 'D:/work/job-candidates/RuntimeTypes.ts'",+ "artifact": "RuntimeTypes.ts",+ "exitCode": 0,+ "result": {+ "ok": true,+ "outputFile": "D:/work/job-candidates/RuntimeTypes.ts",+ "dataSources": [+ "cr_candidate",+ "cr_jobrequisition"+ ],+ "detail": "none",+ "bytes": 2769+ }+ },+ {+ "id": "gate-custom-api",+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api",+ "exitCode": 1,+ "result": "disabled"+ },+ {+ "id": "gate-telemetry",+ "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry",+ "exitCode": 1,+ "result": "disabled"+ },+ {+ "id": "page-files",+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/job-candidates/genpage-plan.md'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "workingDir": "D:\\work\\job-candidates",+ "files": [+ "job-candidates.tsx"+ ],+ "problems": []+ }+ },+ {+ "id": "stamp",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/job-candidates/job-candidates.tsx'",+ "exitCode": 0,+ "result": {+ "ok": true,+ "action": "stamp",+ "filePath": "D:\\work\\job-candidates\\job-candidates.tsx",+ "existed": false+ }+ },+ {+ "id": "write-page",+ "command": "Write job-candidates.tsx",+ "artifact": "job-candidates.tsx"+ },+ {+ "id": "icon-grep",+ "command": "Grep from \"@fluentui/react-icons\" job-candidates.tsx; Grep ^PeopleTeamRegular$ references/verified-icons.txt",+ "result": "PeopleTeamRegular: verified"+ },+ {+ "id": "border-grep",+ "command": "Grep ['\"]?borderWidth['\"]?\\s*: job-candidates.tsx",+ "result": "no matches"+ },+ {+ "id": "gate",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/job-candidates/job-candidates.tsx'",+ "artifact": "job-candidates.tsx",+ "exitCode": 0,+ "result": {+ "ok": true,+ "filePath": "D:\\work\\job-candidates\\job-candidates.tsx",+ "problems": []+ }+ },+ {+ "id": "write-upload-text",+ "command": "Write prompt.txt, agent-message.txt, page-name.txt",+ "artifacts": [+ "prompt.txt",+ "agent-message.txt",+ "page-name.txt"+ ]+ },+ {+ "id": "create",+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'job-candidates.tsx' --name-file 'page-name.txt' --data-sources 'cr_candidate,cr_jobrequisition' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",+ "exitCode": 0,+ "writes": 1,+ "result": {+ "ok": true,+ "pageId": "66666666-7777-4888-9999-bbbbbbbbbbbb",+ "appId": "11111111-2222-3333-4444-555555555555",+ "updated": false+ }+ }+]diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/workflow-log.md b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/workflow-log.mdnew file mode 100644index 000000000..a4d900149--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-verified-columns/workflow-log.md@@ -0,0 +1,173 @@+# Workflow Log — Eval 7: Job candidates with new entities (create flow)++Synthetic trace constructed from the current `/genpage` SKILL.md and agent files, not a captured+agent run. Every command below has an ordered result in `tool-results.json`. Commands run from the+working directory, so file arguments are relative to it. The run keeps the RuntimeTypes.ts that+Phase 4 generated, so the page's column names can be checked against it.++## Phase 0 — Working directory+- `$ARGUMENTS`: "Build a page showing all job candidates with their application status, interview scores, and assigned recruiter. I need new tables for this — cr_candidate and cr_jobrequisition entities don't exist yet in my environment."+- Working directory created: `mkdir -p 'job-candidates'` (kebab-case from "job candidates")+- Resolved working directory: D:/work/job-candidates+- Plugin root: D:/repo/plugins/model-apps++## Phase 0.5 — Local-dev manifest+- Command: `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/job-candidates' 'job-candidates'`+- Result: exit 0; package.json and genpage.d.ts written; no `--features` (no charts or date/time pickers needed)++## Phase 1 — Plan++### Interaction mode+- Command: `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'`+- Result: `{"ok":true,"interactive":true,"reason":"default (attended)"}` — attended run, every gate asked in this loop++### Prereq checks (run separately, not chained)+- `node --version` → v20.20.2+- `pac help` → Microsoft PowerPlatform CLI Version: 2.11.0 (> 2.10.0 verified)++### Auth+- `pac auth list` → one profile, currently active: [email protected]+- Active environment reported to the user: https://contoso.crm.dynamics.com/++### Create or edit+- AskUserQuestion: Do you want to create new page(s) or edit an existing page? → Create new page(s)++### Requirements+- Question 2 (description) skipped: `$ARGUMENTS` already describes the page+- Question 3 (data source) skipped: `$ARGUMENTS` already names it → Dataverse entities: cr_candidate, cr_jobrequisition (new)+- AskUserQuestion: Any specific requirements for the page? → Candidate list with status, interview scores, assigned recruiter++### Discovery (genpage-planner dispatched via Task as a headless worker)+- Dispatched `Task genpage-planner` with the requirements, working directory, plugin root, create/edit decision = create, `No connector bindings.` (connectors.json: none — omit --connectors) and `No custom API bindings.` (actions.json: none — omit --actions)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-languages.js' --env 'https://contoso.crm.dynamics.com'` → English (1033) only, no RTL language+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --search 'cr_candidate,cr_jobrequisition' --exact` → 0 tables, missing: cr_candidate, cr_jobrequisition+ - Exact logical-name match (`--exact`): cr_candidate and cr_jobrequisition are both named in `missing` → both confirmed as NOT existing; both need creation+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/list-tables.js' --env 'https://contoso.crm.dynamics.com' --type custom` for dominant prefix detection → 8 custom tables: cr_hiringstage, cr_interview, cr_offerletter, cr_onboardingtask, cr_referral, cr_talentpool, new_feedback, new_survey+ - Non-system custom prefixes: cr = 6 of 8 (75%, ≥ 3 tables) → dominant prefix detected: `cr` (detectedPrefix = cr, detectedTableCount = 6)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/dataverse-request.js' 'https://contoso.crm.dynamics.com' GET 'solutions?$select=uniquename,friendlyname&$expand=publisherid($select=customizationprefix)&$filter=ismanaged eq false and uniquename ne ''Default'' and uniquename ne ''Active'' and isvisible eq true&$top=10'` (request URL https://contoso.crm.dynamics.com/api/data/v9.2/solutions?…)+ - status 200 → ContosoRecruiting (Contoso Recruiting, publisher prefix cr), FieldSurveys (Field Surveys, publisher prefix new)+- Planner ran `node 'D:/repo/plugins/model-apps/scripts/apps.js' list --env 'https://contoso.crm.dynamics.com'` → 2 apps: Contoso Talent Hub (11111111-2222-3333-4444-555555555555), Field Service Desk (44444444-5555-6666-7777-888888888888); both published, neither with unpublished changes+- New entities need creating → metadata work → the solution selection question must be asked+- Planner returned the discovery summary and `{ "action": "needs_input" }` for the app and solution choices; no connector or Custom API need was found++### App selection+- AskUserQuestion: Which app should the page be added to? (options from the `apps.js list` output: Contoso Talent Hub — 11111111-2222-3333-4444-555555555555; Field Service Desk — 44444444-5555-6666-7777-888888888888; Create a new app) → Contoso Talent Hub (existing app)++### Solution selection+- Solution selection question asked (entity creation required: cr_candidate, cr_jobrequisition)+- AskUserQuestion: Your env has 6 existing custom tables using prefix `cr`. Which solution should the new tables (cr_candidate, cr_jobrequisition) go in? (options, dominant-prefix match first: Continue in 'ContosoRecruiting' (prefix: cr) — matches your existing custom tables [RECOMMENDED]; Create new 'genpage-contoso-talent-hub' solution under cr publisher; Use existing 'FieldSurveys' (prefix: new); Create a new solution under Default Publisher (prefix: new); Use Default Solution (prefix: new) ⚠ different prefix from existing work) → Continue in 'ContosoRecruiting' (prefix: cr)+- Chosen prefix `cr` matches the dominant prefix and the requested table names → no prefix-mismatch warning needed+- Recorded for the plan: `Solution: ContosoRecruiting`, `Publisher Prefix: cr`++### Plan approval+- Re-invoked `Task genpage-planner` with every answer gathered so far; it returned the proposed plan:+ - 1 page: Job Candidates (job-candidates.tsx) on cr_candidate, cr_jobrequisition+ - Create `cr_jobrequisition` (Job Requisition): department (text), openings (whole number 1-50)+ - Create `cr_candidate` (Candidate): interviewscore (whole number 0-100), recruiter (text), applicationstatus choice Applied / Screening / Interviewing / Offer / Hired / Rejected+ - Lookup relationship: 1:N cr_jobrequisition → cr_candidate, lookup column `cr_jobrequisition` on cr_candidate (cr_candidate → cr_jobrequisition)+ - Sample data requested: realistic requisitions with candidates linked to the requisition they applied for+ - App: Contoso Talent Hub; Solution: ContosoRecruiting (prefix cr); Languages: English (1033) only+- EnterPlanMode called — presented the proposed plan (resolved names cr_candidate / cr_jobrequisition shown to the user)+- ExitPlanMode → user approved the plan without changes+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/job-candidates/genpage-plan.md'`+- Result: `"ok":true`, nothing to quarantine (first run in this folder)+- Saved the approved plan body verbatim to D:/work/job-candidates/.approved-genpage-plan.md+- Re-invoked `Task genpage-planner` with the approval outcome, the approved plan body and all prior discovery; it wrote genpage-plan.md (conforms to references/plan-schema.md)+ - Pre-write validation: table suffixes `jobrequisition`, `candidate`; column suffixes `department`, `openings`, `interviewscore`, `recruiter`; choice suffix `applicationstatus`; lookup suffix `jobrequisition` — all match `^[a-z][a-z0-9]+$`, no underscore or prefix in `## Entity Creation Required`+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/job-candidates/genpage-plan.md' --approved '@D:/work/job-candidates/.approved-genpage-plan.md'`+- Result: `"ok":true`, kind create, targets [job-candidates.tsx], writtenHash 69e164741206e6a3f8e0037b55ba757318cb404bdaf1981abce94f07af40e391++## Phase 2a — Pre-flight: az + pac + Dataverse+- `## Entity Creation Required` lists two tables (jobrequisition, candidate) → entity creation needed+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac`+- Result: `ok: true`, blocker null, identitiesMatch true (az and pac both [email protected]), envUrl https://contoso.crm.dynamics.com, WhoAmI ok+- ok:true gate passed → proceed to the entity-builder; envUrl captured for Phase 2b++## Phase 2b — Entity builder+- Dispatched `Task genpage-entity-builder` with the plan path D:/work/job-candidates/genpage-plan.md, working directory, plugin root and env URL https://contoso.crm.dynamics.com+ - Read plan `## Environment`: Solution = ContosoRecruiting, Publisher Prefix = cr (suffix validation passed)+ - Dependency order: cr_jobrequisition (independent) → cr_candidate (references cr_jobrequisition) → 1:N relationship after both tables exist+ - Re-probe: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac` → ok: true, identitiesMatch true+ - Opened the transaction log D:/work/job-candidates/genpage-entity-creation-log.md+ - Wrote D:/work/job-candidates/provision-input.json: solution ContosoRecruiting / prefix cr; entities cr_JobRequisition (primary cr_Name; cr_Department Text, cr_Openings Integer 1-50) and cr_Candidate (primary cr_Name; cr_InterviewScore Integer 0-100, cr_Recruiter Text, cr_ApplicationStatus Choice); relationship OneToMany cr_jobrequisition_cr_candidate (referenced cr_JobRequisition, referencing cr_Candidate, lookup cr_JobRequisition)+ - Command: `node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/job-candidates/provision-input.json' --apply`+ - Result: `ok: true` — tables cr_jobrequisition and cr_candidate, 5 columns, relationship cr_jobrequisition_cr_candidate (lookup cr_jobrequisition) created in ContosoRecruiting; the CLI handled table-before-relationship ordering and metadata propagation+ - Builder returned `{ "action": "needs_input" }` for the sample-data decision (it is headless)+- AskUserQuestion: Entities created successfully (cr_jobrequisition: 3 columns, parent of cr_candidate; cr_candidate: 5 columns, lookup cr_jobrequisition). Would you like me to add sample data for testing? → Yes, add sample data+- Re-invoked `Task genpage-entity-builder` with the answer, saying the sample-data decision is answered, plus everything pass 1 returned (provisioned tables, relationship, log and input paths)+ - Re-probe: `node 'D:/repo/plugins/model-apps/scripts/check-auth.js' --env 'https://contoso.crm.dynamics.com' --require-pac` → ok: true, identitiesMatch true+ - Data model already provisioned in pass 1 (result carried in the prompt) → went straight to Step 7+ - Extended provision-input.json with `sampleData`: 3 cr_JobRequisition rows and 8 cr_Candidate rows; choice values written as labels; every candidate binds its requisition with `"$parent": { "entity": "cr_JobRequisition", "match": { "cr_name": "<job title>" } }`+ - Command: `node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/job-candidates/provision-input.json' --apply --sample-data`+ - Result: `ok: true` — existing tables and relationship re-reported (idempotent); parents seeded before children; records cr_JobRequisition 3, cr_Candidate 8, each candidate linked through its cr_jobrequisition lookup+ - Updated `## Commands` in genpage-entity-creation-log.md with the `--sample-data` run and recorded the created record ids+ - Builder returned completion: cr_jobrequisition (3 columns, 3 sample records), cr_candidate (5 columns incl. lookup, 8 sample records); log at D:/work/job-candidates/genpage-entity-creation-log.md++## Phase 3 — App+- SKIPPED app creation: existing app Contoso Talent Hub (11111111-2222-3333-4444-555555555555) selected; `apps.js create` not called++## Phase 4 — RuntimeTypes+- `node 'D:/repo/plugins/model-apps/scripts/genpage.js' types --env 'https://contoso.crm.dynamics.com' --data-sources 'cr_candidate,cr_jobrequisition' --output-file 'D:/work/job-candidates/RuntimeTypes.ts'`+- Read RuntimeTypes.ts: verified cr_candidateid, cr_name, cr_applicationstatus (enum Applied/Screening/Interviewing/Offer/Hired/Rejected = 100000000-100000005), cr_interviewscore, cr_recruiter and the `_cr_jobrequisition_value` foreign key on cr_candidate (the requisition title comes from its FormattedValue annotation; `cr_jobrequisitionname` is not selectable); cr_jobrequisitionid, cr_name, cr_department, cr_openings on cr_jobrequisition++## Phase 4.5 — Connector bindings+- SKIPPED: plan says `No connector bindings.` → Connectors: none; no connectors.json, no `--connectors`++## Phase 4.6 — Custom API bindings+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api`+- Result: `disabled`; plan body is exactly `No custom API bindings.` → continue with no Custom APIs, no actions.json, no `--actions`++## Phase 4.7 — Page telemetry+- Command: `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry`+- Result: `disabled` → Telemetry: disabled; the page contains no telemetry calls++## Phase 5a — Plan validation+- One page row with a matching `### Job Candidates` subsection+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/job-candidates/genpage-plan.md'`+- Result: `"ok":true` — job-candidates.tsx is a safe, unique page file++## Phase 5b — Single-page fast path+- Plan has 1 page → inlined the page-builder workflow (no Task dispatch for the page)+- Data mode: dataverse; Connectors: none; Telemetry: disabled+- Read D:/repo/plugins/model-apps/references/rules.md+- Read sample 9-list-with-caching.tsx (from `## Relevant Samples`)+- Needs caching: true → read references/data-caching.md+- Languages: English only → localization.md not needed+- Read genpage-plan.md and RuntimeTypes.ts+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/job-candidates/job-candidates.tsx'`+- Result: `"ok":true`, stamp recorded, no earlier file at the target+- Wrote job-candidates.tsx with the file tool: queryTable('cr_candidate') selecting only RuntimeTypes.ts columns (cr_candidateid, cr_name, cr_applicationstatus, cr_interviewscore, cr_recruiter, _cr_jobrequisition_value) read via `.rows`, single batched setData, window cache + in-flight de-dupe gated on `dataReady`, requisition title and status label from their FormattedValue annotations, sortable DataGrid (createTableColumn + compare, resizableColumns, columnSizingOptions), candidate records opened via Xrm.Navigation.navigateTo+- Icon verification: Grep for `from "@fluentui/react-icons"` → PeopleTeamRegular; Grep of references/verified-icons.txt → present+- Grep `['"]?borderWidth['"]?\s*:` → no matches+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/job-candidates/job-candidates.tsx'`+- Result: `"ok":true`, problems [] — complete page accepted++## Phase 6 — Deploy+- No connectors.json / actions.json → the upload `--help` pre-flight for `--connectors` / `--actions` is not needed+- Checked prompt.txt, agent-message.txt and page-name.txt in the working directory: none existed, none is a link+- Wrote prompt.txt (the full `## User Requirements` body), agent-message.txt and page-name.txt ("Job Candidates") with the file tool+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --code-file 'job-candidates.tsx' --name-file 'page-name.txt' --data-sources 'cr_candidate,cr_jobrequisition' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`+- Data sources: both new tables, cr_candidate and cr_jobrequisition+- Prompt scope: full page description from the plan's `## User Requirements` (create)+- Result: page-id = 66666666-7777-4888-9999-bbbbbbbbbbbb, status = success (`updated: false`, added to the Contoso Talent Hub sitemap)++## Phase 6.5 — Navigation fix-up+- SKIPPED: single page, no PAGEREF_ placeholders++## Phase 6.7 — Solution packaging+- SKIPPED: the plan has no `## Solution Packaging` section (the new tables were already created in ContosoRecruiting)++## Phase 7 — Verify in browser+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Job Candidates | job-candidates.tsx | cr_candidate, cr_jobrequisition | Deployed |++- App: Contoso Talent Hub (11111111-2222-3333-4444-555555555555)+- Page ID: 66666666-7777-4888-9999-bbbbbbbbbbbb+- Entities created: cr_jobrequisition, cr_candidate (lookup cr_candidate → cr_jobrequisition) in solution ContosoRecruiting+- Sample data: 3 requisitions, 8 candidates (each linked to its requisition)+- Browser verification: skippeddiff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.mdindex 762374cc3..fb98c69c7 100644--- a/evals/model-apps/genpage/fixtures/README.md+++ b/evals/model-apps/genpage/fixtures/README.md@@ -90,7 +90,7 @@ Two rules for evidence files:## Current state-This directory has **27 fixtures, 34 top-level TSX files and 25 represented+This directory has **33 fixtures, 37 top-level TSX files and 25 representedprompt IDs**. All are green under both runners. Directories listed in`contracts.json` are historical contract-1 evidence; every other directory is acurrent contract-2 synthetic. Registered prompts with no fixture:@@ -113,7 +113,10 @@ of step with the fixtures.| `17-weather-mock-data/` | 17 | Historical synthetic | green | Mock weather, no discovery || `18-sharepoint-connectors/` | 18 | Historical synthetic | green | Connector-backed source and discovery || `19-add-weather-connector/` | 19 | Historical synthetic | green | Add-from-none edit compatibility |-| `10-auth-timeout-halt/` | 10 | Current synthetic | green | Associated timeout results, one retry/advice, halt with no TSX/mutation |+| `10-auth-timeout-halt/` | 10 | Current synthetic | green | Exact-match discovery of the missing table; associated timeout results, one retry/advice, halt with no TSX/mutation |+| `10-az-signed-out-halt/` | 10 | Current synthetic | green | Exact-match discovery; Azure CLI signed out: the `az login` advice is shown verbatim and the run halts with no TSX/mutation |+| `10-whoami-403-halt/` | 10 | Current synthetic | green | Exact-match discovery; WhoAmI 403 with different az and pac identities: the `az login --username <pacUser>` advice is shown verbatim and the run halts |+| `10-identity-mismatch-proceeds/` | 10 | Current synthetic | green | Exact-match discovery; `ok: true` with different az and pac identities: the one-line warning is shown verbatim and the run goes on — the entity-builder (which logs the same warning in its transaction log) provisions the table and the page is uploaded || `20-upload-preservation/` | 20 | Current synthetic | green | App-less create (first page of a new app); exact create file transport; independent edit read-backs; a straight quote stored exactly || `21-discovery-failure/` | 21 | Current synthetic | green | Unreadable discovery is needs_input, never setup/upload; no generated TSX || `22-navigation-contract/` | 22 | Current synthetic | green | Actual before/after source, optional calls/overrides/escaped keys/Unicode terminators, affected-only upload |@@ -121,12 +124,15 @@ of step with the fixtures.| `24-custom-api-lifecycle/` | 24 | Current synthetic | green | Bound Action/global Function discovery, re-probe, runtime, preserve and clear || `25-solution-package/` | 25 | Current synthetic | green | Every deployed page, dynamic component types, app-first writes, read-back and invalid-id refusal || `3-contacts-edit-search-sort/` | 3 | Current synthetic | green | Edit flow: discovered app/page, download snapshot in `before/`, inline edit adding SearchBox + header sorting, `--page-id` delta upload without `--add-to-sitemap` |+| `3-edit-no-pages-stop/` | 3 | Current synthetic | green | Edit flow refused at Edit Phase 1b: the chosen app's `genpage.js list` succeeds with no pages, the user is told there is nothing to edit, and the run stops with no download, plan, TSX or upload || `6-traffic-analytics-mock/` | 6 | Current synthetic | green | Clean, minimal mock-data analytics with D3 only; no entity work; upload omits `--data-sources` || `8-account-metrics-new-app/` | 8 | Current synthetic | green | Zero apps → create-new-app choice, solution question, first page uploaded with no app, then `apps.js create --solution --page-id --publish`, which pins the page's tables itself, so no upload follows || `9-project-tracker-new-entities/` | 9 | Current synthetic | green | Two new related tables, auth gate, dependency-ordered provisioning, `$parent`/match sample data, both tables as data sources || `12-account-plan-revision/` | 12 | Current synthetic | green | First plan rejected, revised plan re-presented and approved; page has both search box and filter toolbar || `14-account-list-edit-collision/` | 14 | Current synthetic | green | Colliding file names refused by the Phase 5a gate, re-plan, two parallel builders, Phase 6.5 navigation fix-up || `16-account-list/` | 16 | Current synthetic | green | Minimal single list page over an existing table; code-only, no solution question or auth gate |+| `1-account-cards-verified-columns/` | 1 | Current synthetic | green | Account card gallery over an existing table; keeps the RuntimeTypes.ts it was written against, so every column its dataApi call names is checked against the schema |+| `7-job-candidates-verified-columns/` | 7 | Current synthetic | green | Two new related tables (cr_jobrequisition, cr_candidate with a lookup and a status choice), auth gate, dependency-ordered provisioning, `$parent`/match sample data; keeps the RuntimeTypes.ts it generated, so the page's columns are checked against the schema |Historical captures remain compatibility/parser evidence, not proof of today'sfile transport, binding preservation or full skill compliance. Their currentdiff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.jsindex 731ae5cb1..582996b7d 100644--- a/evals/model-apps/genpage/lib/assertions-layer-1.js+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js@@ -16,7 +16,7 @@const fs = require('node:fs');const path = require('node:path');const { pageFileProblems } = require('../../../../plugins/model-apps/scripts/lib/page-file-targets.js');-const { currentContract, workflowCalls, isAuth, isDiscovery, authGateProblems, discoveryProblems, refusalProblems, resultObject, isGeneration, isUpload } = require('./workflow-evidence.js');+const { currentContract, workflowCalls, isAuth, isDiscovery, authGateProblems, discoveryProblems, refusalProblems, emptyPageListingProblems, isEmptyPageListing, resultObject, isGeneration, isUpload, isMutation } = require('./workflow-evidence.js');const { gradeEvidence, isGuid, fileName, artifactText, commandInfo } = require('./evidence-utils.js');const { navigationProblems, navTargets } = require('./navigation-contract.js');const { workerProblems } = require('./worker-contract.js');@@ -24,6 +24,9 @@ const { uploadProblems, uploadPreservationProblems } = require('./upload-contracconst { planSection, findMarkdownTable, parseMarkdownRows } = require('./plan-evidence.js');const { customApiProblems, customApiGateProblems } = require('./custom-api-contract.js');const { packagingProblems, isPackaging } = require('./packaging-contract.js');+const { preservationProblems } = require('./preservation-contract.js');+const { columnProblems } = require('./column-contract.js');+const { escapeRe } = require('./source-evidence.js');const evidence = require('./expectation-evidence.js');const { blankLiterals } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');const { planTargets } = require('../../../../plugins/model-apps/scripts/genpage-plan-provenance.js');@@ -68,7 +71,21 @@ function skip(reason) { return { status: 'skip', reason }; }// 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);+ return Boolean(fixture && ((fixture.genpageEditPlan && !fixture.genpagePlan) || noPagesRefusal(fixture)));+}++// An edit run refused at Edit Phase 1b because the chosen app has no generative pages (fixture.json+// `"expectedOutcome": "refused", "refusal": { "stage": "edit-pages" }`). It ends before a page is chosen, so it+// writes no plan of either kind, and refusalProblems grades the stop itself.+function noPagesRefusal(fixture) {+ return fixture?.manifest?.expectedOutcome === 'refused' && fixture.manifest.refusal?.stage === 'edit-pages';+}++// The page listing a run refused at Edit Phase 1b stopped at: its first listing that came back empty (the+// same stop emptyPageListingProblems grades), else its last listing.+function stopListing(fixture) {+ const listings = evidence.commandCalls(fixture, evidence.GENPAGE_LIST);+ return listings.find((entry) => isEmptyPageListing(resultObject(entry.call))) || listings.at(-1);}function beforePlanningRefusal(fixture) {@@ -764,9 +781,18 @@ PHASE_EXPECTATIONS.set(({ fixture }) => gradeEvidence(workerProblems, fixture));+// A refusal is graded whole: its failed gate, the halt, and nothing provisioned or uploaded. A run that went+// on is graded only when an auth call timed out on the way — it must then have retried once and been+// authorized by a later ok:true gate (authGateProblems counts the attempts). A run with no timeout at all+// has nothing for this expectation to grade.PHASE_EXPECTATIONS.set('Phase 2a: Auth timeout retries once then halts before provisioning or upload',- ({ fixture }) => checkProblems(refusalProblems(fixture))+ ({ fixture }) => {+ if (fixture.manifest?.expectedOutcome === 'refused') return checkProblems(refusalProblems(fixture));+ const timedOut = workflowCalls(fixture).some((call) => isAuth(call.command) && /^(az|pac)_timeout$/.test(resultObject(call)?.blocker || ''));+ if (!timedOut) return skip('no auth timeout in this scenario');+ return checkProblems(authGateProblems(fixture, { required: true }));+ });PHASE_EXPECTATIONS.set(@@ -976,9 +1002,17 @@ PHASE_EXPECTATIONS.set(});+// The same check Layer 2 runs on the code (lib/column-contract.js): the column names the pages give their+// dataApi calls, against the RuntimeTypes.ts the run kept. A trace that kept no RuntimeTypes.ts has no+// schema to verify them against.PHASE_EXPECTATIONS.set('Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names',- () => skip('column-name verification needs schema cross-check')+ ({ fixture }) => {+ if (!fixture.runtimeTypes) return skip('column-name verification requires RuntimeTypes.ts fixture');+ const problems = columnProblems(fixture.files || [], fixture.runtimeTypes);+ if (problems === null) return skip('the pages name no Dataverse column for RuntimeTypes.ts to verify');+ return resultOf(problems);+ });PHASE_EXPECTATIONS.set(@@ -1111,27 +1145,55 @@ PHASE_EXPECTATIONS.set(});+// The blocker is read from check-auth.js's own result — `{ "ok": false, "blocker": "az_not_logged_in",+// "message": "Azure CLI is installed but not logged in. Run `az login` with the same identity as your active+// `pac auth` profile." }` — and from a historical log's `Result: ok=false, blocker=az_not_logged_in` line+// (workflow-evidence.js historicalResult). A current trace must show the message reaching the user verbatim+// (the event's `userMessage`); a historical one, the `az login` advice in its log. Halting is nothing that+// writes or generates after the blocker, and the log saying the run stopped.PHASE_EXPECTATIONS.set('Phase 2a: If the script returns blocker:\'az_not_logged_in\', orchestrator surfaces the message (\'Run `az login`...\') to the user and halts (entity-builder is NOT invoked)',({ fixture }) => {const log = fixture.workflowLog;if (!log) return fail('no workflow-log.md');- if (!/blocker[:\s]+['"]?az_not_logged_in['"]?/i.test(log)) {- return skip('az_not_logged_in blocker not in scenario');+ const calls = workflowCalls(fixture);+ const at = calls.findIndex((call) => isAuth(call.command) && resultObject(call)?.blocker === 'az_not_logged_in');+ if (at === -1) {+ // A log that names the blocker only in prose, with no result line to read it from.+ if (!/blocker[:\s]+['"]?az_not_logged_in['"]?/i.test(log)) return skip('az_not_logged_in blocker not in scenario');+ if (/genpage-entity-builder\s+invoked/i.test(log)) return fail('entity-builder invoked despite az_not_logged_in blocker');+ if (!/halt|halted|stopped|abort/i.test(log)) return fail('orchestrator did not halt after blocker');+ return pass();}- if (/genpage-entity-builder\s+invoked/i.test(log)) {- return fail('entity-builder invoked despite az_not_logged_in blocker');+ const result = resultObject(calls[at]);+ if (currentContract(fixture)) {+ if (!/\baz login\b/.test(result.message || '')) return fail('the az_not_logged_in result carries no `az login` advice');+ if (calls[at].userMessage !== result.message) return fail('the az_not_logged_in message was not surfaced to the user verbatim');+ } else if (!/\baz login\b/.test(log)) {+ return fail('the log records no `az login` advice for the az_not_logged_in blocker');}+ if (calls.slice(at + 1).some((call) => isMutation(call) || isGeneration(call.command))) return fail('entity-builder invoked despite az_not_logged_in blocker');if (!/halt|halted|stopped|abort/i.test(log)) return fail('orchestrator did not halt after blocker');return pass();});+// The builder is found among the recorded calls — its dispatch (`Task genpage-entity-builder`) or the+// provisioning only it runs (BUILDER_CALL) — and the latest check-auth.js result before the first of them must+// be ok:true. A capture that predates both says "entity-builder invoked" in prose, and is read by position.PHASE_EXPECTATIONS.set('Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true',({ fixture }) => {const log = fixture.workflowLog;if (!log) return fail('no workflow-log.md');+ const calls = workflowCalls(fixture);+ const builderAt = calls.findIndex((call) => BUILDER_CALL.test(call.command));+ if (builderAt !== -1) {+ const gate = calls.slice(0, builderAt).filter((call) => isAuth(call.command)).at(-1);+ if (!gate) return fail('entity-builder invoked before check-auth.js');+ if (resultObject(gate)?.ok !== true) return fail('entity-builder invoked although the check-auth.js result before it is not ok:true');+ return checkProblems(authGateProblems(fixture, { required: true }));+ }const idxCheck = log.search(/check-auth\.js/);const idxBuilder = log.search(/genpage-entity-builder\s+invoked|entity-builder\s+invoked/i);if (idxBuilder === -1) return skip('entity-builder not invoked');@@ -1934,6 +1996,84 @@ PHASE_EXPECTATIONS.set(({ fixture }) => checkProblems(authGateProblems(fixture, { required: true })));+// The table is the one the plan creates — `### widget` under the selected publisher's prefix (cnt_widget for+// a cnt publisher) — or the prompt's own cr_widget, whichever name the planner searched for (suffixOf); the+// verdict must rest on an exact logical-name match (missingEntityProblems `exact`), so a `cr_widgetpart` row+// a substring search returns is never read as the table existing.+PHASE_EXPECTATIONS.set(+ 'Phase 1 (Planner): cr_widget is identified as NOT existing (exact logical-name match, not fuzzy)',+ ({ fixture }) => {+ const prefix = planPrefix(fixture.genpagePlan);+ const names = [...new Set([prefix && `${prefix}_widget`, 'cr_widget'].filter(Boolean))];+ const verdicts = names.map((name) => missingEntityProblems(fixture, [name], { exact: true }));+ return resultOf(verdicts.find((problems) => !problems.length) || verdicts[0]);+ }+);++// check-auth.js answers a 403 from WhoAmI with the fix when pac is signed in as someone else:+// { "ok": false, "blocker": "whoami_403", "pacUser": "[email protected]", "identitiesMatch": false,+// "message": "WhoAmI returned 403. az is signed in as \"…\" but pac is using \"maker@…\". Run `az login --username maker@…` so both clients use the same identity." }+// With matching identities there is no such command (the user needs access to the environment instead), so+// only the verbatim message and the halt are required then. SKILL.md Phase 2a: `ok: false` → show the+// `message` field verbatim and stop the workflow.+PHASE_EXPECTATIONS.set(+ 'Phase 2a: If blocker:\'whoami_403\', orchestrator surfaces the message including the specific `az login --username <pacUser>` command and halts',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ const calls = workflowCalls(fixture);+ const at = calls.findIndex((call) => isAuth(call.command) && resultObject(call)?.blocker === 'whoami_403');+ if (at === -1) return skip('whoami_403 blocker not in scenario');+ const result = resultObject(calls[at]);+ const strict = currentContract(fixture);+ if (strict && result.identitiesMatch === false) {+ if (typeof result.pacUser !== 'string' || !result.pacUser) return fail('the whoami_403 result names no pacUser to sign in as');+ if (!String(result.message || '').includes(`az login --username ${result.pacUser}`)) return fail(`the whoami_403 message does not name \`az login --username ${result.pacUser}\``);+ }+ if (strict && calls[at].userMessage !== result.message) return fail('the whoami_403 message was not surfaced to the user verbatim');+ if (!strict && !/\baz login --username\b/.test(log)) return fail('the log records no `az login --username` advice for the whoami_403 blocker');+ if (calls.slice(at + 1).some((call) => isMutation(call) || isGeneration(call.command))) return fail('the run provisioned, generated or uploaded after the whoami_403 blocker');+ if (!/\bhalt(?:ed)?\b|\bstop(?:ped)?\b/i.test(log)) return fail('the workflow did not halt after the whoami_403 blocker');+ return pass();+ }+);++// check-auth.js answers a working sign-in whose az and pac identities differ with ok:true and a warning, not a+// blocker (scripts/check-auth.js):+// { "ok": true, "blocker": null, "identitiesMatch": false, "azUser": "admin@…", "pacUser": "maker@…",+// "message": "Ready, but az (\"admin@…\") and pac (\"maker@…\") use different identities. WhoAmI passed so this+// works for now — but if a later step returns 403, run `az login --username maker@…` to align them." }+// SKILL.md Phase 2a: proceed to 2b, but surface the `message` to the user as an inline warning. The orchestrator's+// gate is the one graded (a builder's re-probe logs its warning in the transaction log, which authGateProblems+// checks): its one-line message must reach the user verbatim, carry the `az login --username <pacUser>` fix, and+// the run must go on to the entity-builder rather than stop.+PHASE_EXPECTATIONS.set(+ 'Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ const calls = workflowCalls(fixture);+ const at = calls.findIndex((call) => isAuth(call.command) && call.by !== 'genpage-entity-builder'+ && resultObject(call)?.ok === true && resultObject(call).identitiesMatch === false);+ if (at === -1) return skip('no ok:true, identitiesMatch:false auth result in this scenario');+ const result = resultObject(calls[at]);+ if (currentContract(fixture)) {+ const warning = typeof result.message === 'string' ? result.message.trim() : '';+ if (!warning) return fail('the identity-mismatch result carries no warning message');+ if (calls[at].userMessage !== result.message) return fail('the identity-mismatch warning was not surfaced to the user verbatim');+ if (/[\r\n]/.test(warning)) return fail('the identity-mismatch warning is not one line');+ if (typeof result.pacUser === 'string' && result.pacUser && !warning.includes(`az login --username ${result.pacUser}`)) {+ return fail(`the identity-mismatch warning does not name \`az login --username ${result.pacUser}\``);+ }+ } else if (!/\baz login --username\b/.test(log)) {+ return fail('the log records no identity-mismatch warning naming `az login --username`');+ }+ if (fixture.manifest?.expectedOutcome === 'refused') return fail('the run stopped although its only auth finding was a warning-only identity mismatch');+ if (!calls.slice(at + 1).some((call) => isMutation(call) || isGeneration(call.command))) return fail('the run did not go on past the ok:true, identitiesMatch:false gate');+ return checkProblems(authGateProblems(fixture, { required: true }));+ }+);+// --- Eval 11 -----------------------------------------------------------------------------------PHASE_EXPECTATIONS.set(@@ -2409,8 +2549,21 @@ PHASE_EXPECTATIONS.set(if (!fixture.workflowLog) return fail('no workflow-log.md');const calls = workflowCalls(fixture);const at = (pattern) => calls.findIndex((c) => pattern.test(c.command));+ // commandCalls re-reads the log, so locate its calls in `calls` by their recorded command text.+ const positionOf = (entry) => calls.findIndex((c) => c.command === entry.call.command);const download = commandCalls(fixture, evidence.GENPAGE_DOWNLOAD)[0];- if (!download) return fail('genpage.js download was not run, so no page was selected');+ if (!download) {+ if (!noPagesRefusal(fixture)) return fail('genpage.js download was not run, so no page was selected');+ // The run stopped at an empty listing (the app has no pages), so that listing is what is graded: it must+ // be of an app the apps.js list output returned, run after that discovery.+ const list = stopListing(fixture);+ if (!list) return fail('genpage.js list --app-id <selected> was not run');+ const listedApp = String(list.flags['app-id'] || '').toLowerCase();+ const apps = commandCalls(fixture, LIST_APPS).at(-1);+ if (!apps || positionOf(apps) > positionOf(list)) return fail('pages were listed before the app was discovered with apps.js list');+ if (!listedApp || !listingRows(apps.call).some((r) => r.id === listedApp)) return fail(`genpage.js list ran for app ${listedApp || '(none)'}, which apps.js list did not return`);+ return pass();+ }const app = String(download.flags['app-id'] || '').toLowerCase();const page = String(download.flags['page-id'] || '').toLowerCase();const lists = commandCalls(fixture, GENPAGE_LIST).filter((c) => String(c.flags['app-id'] || '').toLowerCase() === app);@@ -2423,8 +2576,6 @@ PHASE_EXPECTATIONS.set(const listed = (c) => c.text.split(/\r?\n/).some((line) => !/\bselect/i.test(line) && line.toLowerCase().includes(page));if (!page || !lists.some(listed)) return fail(`page ${page || '(none)'} does not appear in the recorded genpage list output`);const appsAt = at(LIST_APPS);- // commandCalls re-reads the log, so locate its calls in `calls` by their recorded command text.- const positionOf = (entry) => calls.findIndex((c) => c.command === entry.call.command);const listAt = positionOf(lists[0]);if (appsAt === -1 || appsAt > listAt) return fail('pages were listed before the app was discovered with apps.js list');if (listAt > positionOf(download)) return fail('the page was downloaded before pages were listed');@@ -2578,7 +2729,10 @@ const pageFilesOf = (plan) => pageRowsOf(plan).map((r) => r.file);PHASE_EXPECTATIONS.set('Edit Phase 1a: Apps are presented to the user via AskUserQuestion using the actual app name and app-id GUID from the apps.js list output',- ({ fixture }) => resultOf(presentedFromListingProblems(fixture, { listing: LIST_APPS, noun: 'app', selected: downloadTarget(fixture)?.app }))+ // The app the run went on with: the one it downloaded from, or — for a run that stopped because that app+ // listed no pages — the one whose empty listing it stopped at.+ ({ fixture }) => resultOf(presentedFromListingProblems(fixture, { listing: LIST_APPS, noun: 'app',+ selected: downloadTarget(fixture)?.app ?? (String(stopListing(fixture)?.flags['app-id'] || '').toLowerCase() || undefined) })));PHASE_EXPECTATIONS.set(@@ -2707,6 +2861,17 @@ PHASE_EXPECTATIONS.set(});+// What the approved edit plan promised to keep, checked against the page the run downloaded and the+// page it uploaded (lib/preservation-contract.js): every identifier a Preservation Constraint quotes+// in a code span and the downloaded page uses must still be used after the edit.+PHASE_EXPECTATIONS.set(+ 'Edit Phase 5: Existing functionality is preserved per the edit plan\'s Preservation Constraints',+ ({ fixture }) => {+ const problems = preservationProblems(fixture);+ return Array.isArray(problems) ? resultOf(problems) : skip(problems.skip);+ }+);+// --- Eval 8 ------------------------------------------------------------------------------------function returnedAppId(entry) {@@ -2916,6 +3081,49 @@ PHASE_EXPECTATIONS.set(});+// "Realistic values (not lorem ipsum)", decided from the rows provision-entities.js was handed: the+// `sampleData` of the captured input JSON, e.g.+// "sampleData": { "cr_Project": [ { "cr_name": "Contoso Website Redesign", "cr_manager": "Avery Chen", … } ] }+// A text value is filler when it is lorem-ipsum Latin, a placeholder word on its own ("test", "sample",+// "foo", "TBD", "N/A", "xxx", optionally numbered) or the table's own name numbered ("Project 1",+// "Milestone #3"); and a table whose rows repeat one primary name holds copies, not records. Keys that+// start with `$` (the `$parent` reference) are not values. That is the line the expectation draws; whether a+// value is plausible for its column beyond it is left to a person (Layer 3).+const LOREM_IPSUM = /\b(?:lorem|ipsum|dolor\s+sit|consectetur|adipiscing|eiusmod|incididunt)\b/i;+const PLACEHOLDER_VALUE = /^\s*(?:test(?:ing)?|sample|dummy|placeholder|example|foo|bar|baz|qux|asdf|qwerty|x{2,}|abc|string|text|value|tbd|todo|n\/a|none|null|undefined)(?:[\s_#-]*\d+)?\s*$/i;++PHASE_EXPECTATIONS.set(+ 'Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js; realistic values (not lorem ipsum)',+ ({ fixture }) => {+ const seeded = provisionCalls(fixture).filter((c) => c.flags['sample-data'] === true);+ if (!seeded.length) return fail('no provision-entities.js --sample-data run');+ if (!seeded.some((c) => typeof c.flags.input === 'string')) return fail('sample data was not passed through an --input <json>');+ if (seeded.some((c) => !c.call.historical && resultObject(c.call)?.ok !== true)) return fail('the --sample-data run did not return ok:true');+ const input = provisionInput(fixture);+ if (input === null) return currentContract(fixture) ? fail('provision-input.json was not captured') : skip('provision-input.json was not captured');+ if (input === undefined) return fail('provision-input.json is not JSON');+ const tables = Object.entries(input.sampleData || {}).filter(([, rows]) => Array.isArray(rows) && rows.length);+ if (!tables.length) return fail('provision-input.json carries no sampleData rows');+ for (const [table, rows] of tables) {+ const entity = (input.entities || []).find((e) => String(e.schemaName || '').toLowerCase() === table.toLowerCase());+ const ownNames = [entity?.displayName, schemaSuffix(table)].filter((name) => typeof name === 'string' && name);+ const numberedName = new RegExp(`^\\s*(?:${ownNames.map(escapeRe).join('|')})\\s*#?\\s*\\d+\\s*$`, 'i');+ for (const [i, row] of rows.entries()) {+ for (const [column, value] of Object.entries(row || {})) {+ if (column.startsWith('$') || typeof value !== 'string') continue;+ if (LOREM_IPSUM.test(value)) return fail(`${table} row ${i + 1} ${column} is lorem ipsum: "${value}"`);+ if (PLACEHOLDER_VALUE.test(value) || numberedName.test(value)) return fail(`${table} row ${i + 1} ${column} is a placeholder, not a realistic value: "${value}"`);+ }+ }+ const primary = String(entity?.primaryAttribute?.schemaName || '').toLowerCase();+ const names = primary ? rows.map((row) => Object.entries(row || {}).find(([key]) => key.toLowerCase() === primary)?.[1]).filter((v) => typeof v === 'string') : [];+ const repeated = names.find((name, i) => names.indexOf(name) !== i);+ if (repeated !== undefined) return fail(`${table} rows repeat the name "${repeated}"`);+ }+ return pass();+ }+);+PHASE_EXPECTATIONS.set('Phase 2b (Entity Builder): Sample records respect relationships (milestones reference projects via $parent/match convention)',({ fixture }) => {@@ -3276,6 +3484,30 @@ PHASE_EXPECTATIONS.set(});+// --- Eval 3: an app with no pages ---------------------------------------------------------------------++PHASE_EXPECTATIONS.set(+ 'Edit Phase 1b: If the app has zero genpages, the user is told there are no pages to edit and the flow stops',+ ({ fixture }) => {+ // Any listing that came back empty puts the run on this branch, wherever it is in the run.+ const empty = commandCalls(fixture, GENPAGE_LIST).some((listing) => isEmptyPageListing(resultObject(listing.call)));+ if (!empty && !noPagesRefusal(fixture)) return skip('no page listing came back empty in this scenario');+ return resultOf(emptyPageListingProblems(fixture));+ }+);++// A run that stopped at Edit Phase 1b because the app has no pages never reaches a page choice, a download,+// an edit plan, an edit or an upload, so the expectations of those phases do not apply to it: they skip with+// that reason instead of failing. The stop itself is graded by the zero-pages expectation above and by+// refusalProblems (the common upload assertion and Layer 2's refusal gate).+const AFTER_PAGE_LISTING = /^Edit Phase (?:1b: Pages are presented\b|1c\b|[2-9])/;+for (const [text, check] of PHASE_EXPECTATIONS) {+ if (!AFTER_PAGE_LISTING.test(text)) continue;+ PHASE_EXPECTATIONS.set(text, (context) => (noPagesRefusal(context.fixture)+ ? skip('the run stopped at Edit Phase 1b: the app has no pages to edit')+ : check(context)));+}+module.exports = {WORKFLOW_ASSERTIONS,PHASE_EXPECTATIONS,diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.jsindex 3177430d3..631d77173 100644--- a/evals/model-apps/genpage/lib/assertions-layer-2.js+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js@@ -26,6 +26,12 @@ const { navigationProblems } = require('./navigation-contract.js');const { workerProblems } = require('./worker-contract.js');const { customApiProblems } = require('./custom-api-contract.js');const { gradeEvidence } = require('./evidence-utils.js');+const {+ reviewSummaryProblems, formFieldLabelProblems, searchAndFilterProblems,+ translateCoverageProblems, choiceEnumProblems,+} = require('./page-checks.js');+const { nestedDefinitionProblems } = require('./tsx-structure.js');+const { columnProblems } = require('./column-contract.js');let _verifiedIcons = null;function getVerifiedIcons() {@@ -88,6 +94,41 @@ function fail(reason) { return { status: 'fail', reason }; }function pass() { return { status: 'pass', reason: '' }; }function skip(reason) { return { status: 'skip', reason }; }+// A page check (lib/page-checks.js) over every file: a file it does not apply to returns null. Passes+// when every file it applies to has no problem, fails on the first problem, and skips with `none` when+// it applies to no file.+function everyFile(files, problemsOf, none) {+ let applied = false;+ for (const file of files) {+ const problems = problemsOf(file);+ if (problems === null) continue;+ applied = true;+ if (problems.length) return fail(`${file.name}: ${problems[0]}`);+ }+ return applied ? pass() : skip(none);+}++// A page check that one page of the fixture must meet (the wizard, the revised list page): passes when+// some file has no problem, else fails with the first problem of the first file.+function someFile(files, problemsOf) {+ let first = null;+ for (const file of files) {+ const problems = problemsOf(file);+ if (!problems.length) return pass();+ if (!first) first = `${file.name}: ${problems[0]}`;+ }+ return fail(first || 'no .tsx file');+}++// The column names the pages give their dataApi calls, checked against the RuntimeTypes.ts the run kept+// (lib/column-contract.js). Without it there is no schema to verify a name against.+function columnsVerified(files, fixture) {+ if (!fixture?.runtimeTypes) return skip('column-name verification requires RuntimeTypes.ts fixture');+ const problems = columnProblems(files, fixture.runtimeTypes);+ if (problems === null) return skip('the pages name no Dataverse column for RuntimeTypes.ts to verify');+ return problems.length ? fail(problems[0]) : pass();+}+const ASSERTIONS = new Map();ASSERTIONS.set(@@ -294,7 +335,9 @@ ASSERTIONS.set(ASSERTIONS.set('For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)',- () => skip('Rule 14 batched-setState requires AST analysis')+ // Not a parser gap: a correct check fails historical fixtures that set their rows in `try` and loading in+ // `finally` (the drift is recorded, with the fixtures, in evals/model-apps/tests/eval-coverage-baseline.json).+ () => skip('not graded yet: a correct Rule 14 check fails historical fixtures (see tests/eval-coverage-baseline.json)'));// A connector read is frequently factored into a local helper that the effect calls:@@ -499,7 +542,7 @@ PHASE5_EXPECTATIONS.set(PHASE5_EXPECTATIONS.set('Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names',- () => skip('column-name verification requires RuntimeTypes.ts fixture')+ ({ files, fixture }) => columnsVerified(files, fixture));PHASE5_EXPECTATIONS.set(@@ -563,7 +606,25 @@ PHASE5_EXPECTATIONS.set(PHASE5_EXPECTATIONS.set('Phase 5 (Page Builder): All form fields have aria-labels or aria-labelledby for accessibility',- () => skip('aria-label coverage requires AST analysis')+ ({ files }) => everyFile(files, (file) => formFieldLabelProblems(file.content), 'no form fields')+);++// eval 4's wizard: "Generated code includes step state management (current step tracking) and Next/Back+// navigation" has NO check. Whether Next and Back move the step is the value the step's setter receives,+// which a scan of the handler's text cannot prove (an updater can compute the next step and return the+// old one); grading it needs data-flow analysis, so tests/eval-coverage-baseline.json records it as+// unscored rather than registering a check that would pass a wizard that never advances.++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Step 3 (review) shows a summary of entered data before submission',+ ({ files }) => someFile(files, (file) => reviewSummaryProblems(file.content))+);++// eval 12: the page built from the REVISED plan has both the search box the revision added and the+// filter toolbar the first plan had (lib/page-checks.js searchAndFilterProblems).+PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated code implements the revised plan (includes BOTH filter toolbar AND search box)',+ ({ files }) => someFile(files, (file) => searchAndFilterProblems(file.content)));PHASE5_EXPECTATIONS.set(@@ -600,12 +661,16 @@ PHASE5_EXPECTATIONS.set(PHASE5_EXPECTATIONS.set('Phase 5 (Page Builder): All user-visible text goes through a translate() helper — no hardcoded display strings in JSX',- () => skip('translate() coverage requires AST analysis')+ ({ files }) => everyFile(files, (file) => translateCoverageProblems(file.content), 'no .tsx file'));+// The values are read from the captured RuntimeTypes.ts, the schema the type generator wrote: without+// it there is nothing to verify a choice value or its name against.PHASE5_EXPECTATIONS.set('Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)',- () => skip('choice enum verification requires RuntimeTypes.ts fixture')+ ({ files, fixture }) => (fixture?.runtimeTypes+ ? everyFile(files, (file) => choiceEnumProblems(file.content, fixture.runtimeTypes), 'the page compares no choice value')+ : skip('choice enum verification requires RuntimeTypes.ts fixture')));// Hardcoded currency symbols and date formats in the TEXT a page shows or formats with. The text@@ -817,12 +882,12 @@ PHASE5_EXPECTATIONS.set(PHASE5_EXPECTATIONS.set('Phase 5 (Page Builder): All components and utilities are separate top-level functions (no nested function definitions)',- () => skip('nested function detection requires AST analysis')+ ({ files }) => everyFile(files, (file) => nestedDefinitionProblems(file.content), 'no .tsx file'));PHASE5_EXPECTATIONS.set('Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts',- () => skip('column-name verification requires RuntimeTypes.ts fixture')+ ({ files, fixture }) => columnsVerified(files, fixture));PHASE5_EXPECTATIONS.set(diff --git a/evals/model-apps/genpage/lib/column-contract.js b/evals/model-apps/genpage/lib/column-contract.jsnew file mode 100644index 000000000..52c821c09--- /dev/null+++ b/evals/model-apps/genpage/lib/column-contract.js@@ -0,0 +1,237 @@+'use strict';++// "Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names" (references/rules.md,+// DataAPI Rules 2 and 4: "NEVER guess column names — always verify from the generated RuntimeTypes.ts schema";+// "Reference only columns that exist in the generated schema"). Graded against the RuntimeTypes.ts a run kept,+// the schema the type generator (`genpage.js types`) wrote from the live environment, e.g.+// export interface TableRegistrations extends BaseTableRegistrations {+// "cr_milestone": cr_milestone,+// }+// export type cr_milestone = TableRow<{+// readonly cr_milestoneid: string,+// _cr_project_value: `/cr_project(${string})`,+// cr_name: string,+// }>+// The columns a page names are read where a guessed name breaks the page at run time — the arguments of its+// dataApi calls — each table from the call's first argument:+// queryTable('t', { select: [...], orderBy: 'c asc, d desc', filter: "c eq 1 and contains(d, 'x')" })+// retrieveRow('t', { id, select: [...] }) createRow('t', { c: v }) updateRow('t', id, { c: v })+// and every `<column>@OData.Community.Display.V1.FormattedValue` annotation key the page reads.+// An options or select value written as a name (`queryTable('t', LIST_QUERY)`, `select: SELECT_COLUMNS`) is+// followed to its declaration one level; one that is built at run time cannot be read and is not graded.+//+// The type generator does not write the columns every user-owned table has — `createdon`, `modifiedon`, the+// created/modified-by and owner lookups, `versionnumber` (none of the committed RuntimeTypes.ts files lists+// them, though their pages sort by createdon) — so those are accepted without it: they are not guesses.+// See https://learn.microsoft.com/power-apps/developer/data-platform/reference/about-entity-reference+// (the common columns of a user-owned table). Write keys holding `@` (an `@odata.bind`) are another rule's.++const { sourceView, declarationSource, matchingClose, withoutComments } = require('./tsx-structure.js');++const SYSTEM_COLUMNS = new Set([+ 'createdon', 'modifiedon', 'overriddencreatedon', 'versionnumber', 'importsequencenumber',+ '_createdby_value', '_modifiedby_value', '_createdonbehalfby_value', '_modifiedonbehalfby_value',+ '_ownerid_value', '_owninguser_value', '_owningteam_value', '_owningbusinessunit_value',+ 'createdby', 'modifiedby', 'ownerid', 'owninguser', 'owningteam', 'owningbusinessunit',+]);+const CALLS = /\bdataApi\s*(?:\?\.|\.)\s*(queryTable|retrieveRow|createRow|updateRow)\s*\(/g;+const FORMATTED = /^([A-Za-z_][\w]*)@OData\.Community\.Display\.V1\.FormattedValue$/;++// RuntimeTypes.ts → Map(table logical name → Set(column logical names)).+function runtimeTables(source) {+ const text = String(source || '');+ const tables = new Map();+ const block = /interface\s+TableRegistrations\b[^{]*\{([^}]*)\}/.exec(text);+ for (const m of (block?.[1] || '').matchAll(/"([^"]+)"\s*:\s*([A-Za-z_$][\w$]*)/g)) {+ const body = new RegExp(`\\btype\\s+${m[2]}\\s*=\\s*TableRow<\\{([\\s\\S]*?)\\}>`).exec(text);+ const columns = new Set();+ for (const c of (body?.[1] || '').matchAll(/^\s*(?:readonly\s+)?["']?([A-Za-z_][\w]*)["']?\s*\??\s*:/gm)) columns.add(c[1].toLowerCase());+ tables.set(m[1].toLowerCase(), columns);+ }+ return tables;+}++// The top-level arguments of a call whose `(` is at `open` in the code view: [{ start, end }].+function callArguments(code, open) {+ const close = matchingClose(code, open);+ if (close < 0) return [];+ const args = [];+ let depth = 0;+ let start = open + 1;+ for (let i = open + 1; i < close; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (c === ',' && depth === 0) { args.push({ start, end: i }); start = i + 1; }+ }+ if (code.slice(start, close).trim()) args.push({ start, end: close });+ return args;+}++// A string literal's content: `'account'`, `"statecode eq 0 and contains(name, 'x')"`, or a template with no+// `${…}` (one with an interpolation is built at run time and cannot be read).+function stringValue(text) {+ const m = /^\s*(['"`])((?:(?!\1)[\s\S])*)\1\s*$/.exec(String(text));+ if (!m || (m[1] === '`' && m[2].includes('${'))) return null;+ return m[2];+}++// An argument's source, or — when it is a bare name — the value of that name's declaration in the page,+// with its comments blanked like the rest of what is read here.+function resolved(content, text) {+ const name = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(text)?.[1];+ if (!name) return text;+ const declared = declarationSource(content, name);+ const value = declared && /=\s*([\s\S]*?);?\s*$/.exec(withoutComments(declared));+ return value ? value[1].replace(/\s+as\s+const\s*$/, '') : null;+}++// The properties of an object literal's OWN top level, Map(key → value source): `{ select: [...], expand:+// { x: { select: [...] } } }` has select and expand, never the select nested in expand (another table's).+// A shorthand property (`{ id }`) maps to its name, a spread to nothing.+function topLevelProperties(src) {+ const { code } = sourceView(src);+ const open = code.indexOf('{');+ const close = open < 0 ? -1 : matchingClose(code, open);+ const props = new Map();+ if (close < 0) return props;+ let i = open + 1;+ while (i < close) {+ while (i < close && /[\s,]/.test(code[i])) i += 1;+ if (i >= close) break;+ let key = null;+ if (code[i] === '\'' || code[i] === '"') {+ const end = code.indexOf(code[i], i + 1);+ key = src.slice(i + 1, end);+ i = end + 1;+ } else if (code.startsWith('...', i)) {+ i += 3;+ } else {+ const word = /^[A-Za-z_$][\w$]*/.exec(code.slice(i));+ if (!word) { i += 1; continue; }+ key = word[0];+ i += word[0].length;+ }+ while (i < close && /\s/.test(code[i])) i += 1;+ let value = key;+ if (code[i] === ':') {+ const start = i + 1;+ let depth = 0;+ for (i += 1; i < close; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (c === ',' && depth === 0) break;+ }+ value = src.slice(start, i).trim();+ } else {+ // A spread, a shorthand or a method: skip to the next top-level comma.+ let depth = 0;+ for (; i < close; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (c === ',' && depth === 0) break;+ }+ }+ if (key !== null) props.set(key, value);+ }+ return props;+}++// The contents of the string literals in a short, comment-free source (an array of column names, an+// object's values).+const strings = (src) => [...String(src || '').matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]);++// The string literals of a whole page, found by the lexer (a quote in JSX text, "Don't", is no delimiter).+function pageStrings(content) {+ const { src, code } = sourceView(content);+ const out = [];+ for (let i = 0; i < code.length; i += 1) {+ const q = code[i];+ if ((q !== '\'' && q !== '"') || src[i] !== q) continue;+ const end = code.indexOf(q, i + 1);+ if (end < 0) break;+ out.push(src.slice(i + 1, end));+ i = end;+ }+ return out;+}++// The columns an OData $filter or orderBy expression names: `statecode eq 0 and contains(name, 'x')`,+// `name asc, createdon desc`. Quoted values are dropped first, so `name eq 'Open eq'` names only `name`.+function expressionColumns(text) {+ const bare = String(text).replace(/'[^']*'/g, "''");+ const out = [];+ for (const m of bare.matchAll(/\b([A-Za-z_][\w]*)\s+(?:eq|ne|gt|ge|lt|le|asc|desc)\b/gi)) out.push(m[1]);+ for (const m of bare.matchAll(/\b(?:contains|startswith|endswith)\s*\(\s*([A-Za-z_][\w]*)/gi)) out.push(m[1]);+ for (const part of bare.split(',')) {+ const only = /^\s*([A-Za-z_][\w]*)\s*$/.exec(part);+ if (only) out.push(only[1]);+ }+ return out.filter((name) => !/^(?:and|or|not|null|true|false|eq|ne|gt|ge|lt|le|asc|desc)$/i.test(name));+}++// Every column a page names in its dataApi calls, as { table, column, where }. Arguments, and the+// declarations a bare name resolves to, are read from the source with its comments blanked, so+// `select: ['accountid', /* was 'old_name' */ 'name']` names accountid and name only.+function namedColumns(content) {+ const { code } = sourceView(content);+ const src = withoutComments(content);+ const out = [];+ for (const m of code.matchAll(CALLS)) {+ const method = m[1];+ const args = callArguments(code, m.index + m[0].length - 1).map((a) => src.slice(a.start, a.end));+ const tableText = args[0] && (stringValue(args[0]) ?? stringValue(resolved(content, args[0]) || ''));+ if (!tableText) continue;+ const table = tableText.toLowerCase();+ const where = `${method}('${table}')`;+ if (method === 'createRow' || method === 'updateRow') {+ // `payload as unknown as WritableTableRow<account>` names the payload; a literal is read as written.+ const last = args.at(-1) || '';+ const payload = resolved(content, /^\s*\{/.test(last) ? last : last.replace(/\s+as\s+[\s\S]*$/, ''));+ for (const key of payload && /^\s*\{/.test(payload) ? topLevelProperties(payload).keys() : []) {+ if (!key.includes('@')) out.push({ table, column: key, where });+ }+ continue;+ }+ const options = args.slice(1).map((a) => resolved(content, a)).find((a) => a && /^\s*\{/.test(a));+ if (!options) continue;+ const props = topLevelProperties(options);+ const select = props.get('select');+ const list = select && (/^\s*\[/.test(select) ? select : resolved(content, select));+ for (const column of list ? strings(list) : []) out.push({ table, column, where: `${where} select` });+ for (const key of ['orderBy', 'filter']) {+ const text = props.has(key) ? stringValue(props.get(key)) : null;+ for (const column of text ? expressionColumns(text) : []) out.push({ table, column, where: `${where} ${key}` });+ }+ }+ return out;+}++// Returns null when RuntimeTypes.ts registers no table or the page names no column, else a list of problems.+function columnProblems(files, runtimeTypes) {+ const tables = runtimeTables(runtimeTypes);+ if (!tables.size) return null;+ const known = (columns, name) => columns.has(name.toLowerCase()) || SYSTEM_COLUMNS.has(name.toLowerCase());+ const problems = [];+ let named = 0;+ for (const file of files) {+ for (const { table, column, where } of namedColumns(file.content)) {+ named += 1;+ const columns = tables.get(table);+ if (!columns) problems.push(`${file.name}: ${where} reads table ${table}, which RuntimeTypes.ts does not register`);+ else if (!known(columns, column)) problems.push(`${file.name}: ${where} names ${column}, which RuntimeTypes.ts does not declare on ${table}`);+ }+ // A display name read through its annotation: the column before `@` must exist on some registered table.+ for (const text of pageStrings(file.content)) {+ const base = FORMATTED.exec(text)?.[1];+ if (!base) continue;+ named += 1;+ if (![...tables.values()].some((columns) => known(columns, base))) problems.push(`${file.name}: reads the FormattedValue of ${base}, which RuntimeTypes.ts does not declare`);+ }+ }+ return named ? problems : null;+}++module.exports = { columnProblems, runtimeTables, namedColumns, SYSTEM_COLUMNS };diff --git a/evals/model-apps/genpage/lib/page-checks.js b/evals/model-apps/genpage/lib/page-checks.jsnew file mode 100644index 000000000..eb28918c7--- /dev/null+++ b/evals/model-apps/genpage/lib/page-checks.js@@ -0,0 +1,584 @@+'use strict';++// Layer 2 checks of how a generated page is built, for the per-eval Phase 5 expectations that+// assertions-layer-2.js registers: the review step of a wizard and its submit, the labels of form fields,+// a search box beside a filter toolbar, text that goes through the translate helper, and choice values+// written as the enum names RuntimeTypes.ts declares. Each returns a list of problems (empty when the page+// meets the expectation), or null when the page holds nothing the expectation is about; the registrations+// turn that into pass / fail / skip.+//+// A wizard's Next/Back navigation is NOT graded here: whether a button moves the step is the value the+// step's setter receives — an updater's return value, a local, a helper's argument — and a scan of the+// handler's text cannot prove it (`setStep((s) => { const next = s + 1; return s; })` mentions the+// increment and never moves). It needs data-flow analysis, so tests/eval-coverage-baseline.json records it+// as unscored instead.+//+// Every check reads structure through lib/tsx-structure.js, so a word in a comment, a string or a+// label never counts as code, and code is never taken for text. What each one does NOT judge is said+// beside it; a person still judges the rest in the Layer 3 rubric.++const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose } = require('./tsx-structure.js');+const { runtimeEnums } = require('./expectation-evidence.js');+const { escapeRe } = require('./source-evidence.js');++const BUTTON_TAGS = /^(?:Button|ToolbarButton|CompoundButton|ToggleButton|MenuButton|SplitButton|button)$/;+// The Fluent UI V9 form controls (and their HTML counterparts) whose value a user enters.+const FORM_CONTROLS = /^(?:Input|Textarea|Dropdown|Combobox|Select|SpinButton|DatePicker|TimePicker|Checkbox|Switch|RadioGroup|Slider|SearchBox|input|textarea|select)$/;+const VALUE_ATTRS = ['value', 'selectedOptions', 'checked', 'selectedKey', 'selectedDate', 'defaultValue'];++const word = (name) => new RegExp(`(?<![.\\w$])${escapeRe(name)}(?![\\w$])`);+const hasLetter = (text) => /\p{L}/u.test(String(text));++// What a button says: its children with tags and expression braces removed, then its aria-label.+// `<Button onClick={…}>Next</Button>` → "Next"; `<Button>{translate('next')}</Button>` → "translate('next')".+function buttonLabel(src, element) {+ const children = src.slice(element.childrenStart, element.childrenEnd).replace(/<[^>]*>/g, ' ');+ const aria = element.attrs.get('aria-label');+ return `${children} ${aria ? aria.value : ''}`.replace(/\s+/g, ' ').trim();+}++// A handler's source followed one level: the attribute's expression, then the declaration of every+// function it calls by name, or of the name it is — `onClick={goNext}` reads `const goNext = () => setStep(…)`+// too. A method (`Math.max(…)`) is not followed.+function handlerSource(content, expression) {+ let out = String(expression || '');+ const code = sourceView(out).code;+ const names = new Set([...code.matchAll(/(?<![.\w$])([A-Za-z_$][\w$]*)\s*\(/g)].map((m) => m[1]));+ const bare = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(code);+ if (bare) names.add(bare[1]);+ for (const name of names) {+ const declared = declarationSource(content, name);+ if (declared) out += `\n${declared}`;+ }+ return out;+}++// The step state of a wizard: `const [step, setStep] = useState(…)` (or React.useState), where the+// state's name says it is the step — step, currentStep, activeStep, stepIndex.+function stepStates(content) {+ const { code } = sourceView(content);+ const out = [];+ for (const m of code.matchAll(/\bconst\s*\[\s*([A-Za-z_$][\w$]*)\s*,\s*([A-Za-z_$][\w$]*)\s*\]\s*=\s*(?:React\s*\.\s*)?useState\b/g)) {+ if (/step/i.test(m[1])) out.push({ value: m[1], setter: m[2] });+ }+ return out;+}++// The top-level pieces of `code` between `start` and `end` split at `separator` (a comma or an operator+// such as `&&`), as [start, end) ranges; brackets nest, and strings are already blank in the code view.+function splitTopLevel(code, start, end, separator) {+ const parts = [];+ let depth = 0;+ let from = start;+ for (let i = start; i < end; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (depth === 0 && code.startsWith(separator, i)) {+ parts.push([from, i]);+ i += separator.length - 1;+ from = i + 1;+ }+ }+ parts.push([from, end]);+ return parts;+}++// The JSX shown for each value of the step, as { step, start, end, kind } over the code view:+// {step === 3 && ( … )} {step === 3 ? ( … ) : …} switch (step) { case 3: return ( … ); }+function stepRegions(code, step) {+ const regions = [];+ const name = escapeRe(step);+ for (const m of code.matchAll(new RegExp(`(?<![.\\w$])${name}\\s*===?\\s*(\\d+)\\s*(?:&&|\\?)\\s*\\(`, 'g'))) {+ const open = m.index + m[0].length - 1;+ const close = matchingClose(code, open);+ if (close > open) regions.push({ step: Number(m[1]), start: open, end: close, kind: 'branch' });+ }+ for (const m of code.matchAll(new RegExp(`\\bswitch\\s*\\(\\s*${name}\\s*\\)\\s*\\{`, 'g'))) {+ const open = m.index + m[0].length - 1;+ const close = matchingClose(code, open);+ if (close < 0) continue;+ const cases = [...code.slice(open, close).matchAll(/\bcase\s+(\d+)\s*:/g)].map((c) => ({ step: Number(c[1]), start: open + c.index }));+ cases.forEach((c, i) => regions.push({ step: c.step, start: c.start, end: i + 1 < cases.length ? cases[i + 1].start : close, kind: 'case' }));+ }+ return regions;+}++// The data a form binds: for every form control, the state it shows — `value={form.title}` is the field+// `title` of `form`, `value={title}` the state `title`, `selectedOptions={[String(form.priority)]}` the+// field `priority`. Returned as { label, pattern, at } with a pattern that finds the same data elsewhere+// and the offset of the control that binds it.+function boundFields(content) {+ const fields = new Map();+ for (const control of jsxElements(content, FORM_CONTROLS)) {+ for (const name of VALUE_ATTRS) {+ const attr = control.attrs.get(name);+ if (!attr || attr.kind !== 'expression') continue;+ const code = sourceView(attr.value).code;+ const member = /([A-Za-z_$][\w$]*)\s*\??\.\s*([A-Za-z_$][\w$]*)/.exec(code);+ const bare = /^\s*!*\s*([A-Za-z_$][\w$]*)\s*$/.exec(code);+ if (member && !fields.has(member[2])) {+ fields.set(member[2], { label: `${member[1]}.${member[2]}`, pattern: new RegExp(`(?<![\\w$])${escapeRe(member[1])}\\s*\\??\\.\\s*${escapeRe(member[2])}(?![\\w$])`), at: control.start });+ } else if (!member && bare && !fields.has(bare[1])) {+ fields.set(bare[1], { label: bare[1], pattern: word(bare[1]), at: control.start });+ }+ break;+ }+ }+ return [...fields.values()];+}++// The nearest `{` around `at` in the code view that is not closed before it.+function enclosingContainer(code, at) {+ let depth = 0;+ for (let i = at - 1; i >= 0; i -= 1) {+ if (code[i] === '}') depth += 1;+ else if (code[i] === '{') {+ if (depth === 0) return i;+ depth -= 1;+ }+ }+ return -1;+}++// --- Which step values render an element -----------------------------------------------------------------+// A condition is read, over the values the step takes, for where its value MAY be truthy and where it MUST be+// (`may`, `must`), and likewise where it may and must be null or undefined (`mayNull`, `mustNull`). Both are+// needed because `??` is not `||`: `a ?? b` falls back to b only where a is nullish, so `false ?? (step !== 3)`+// is false and disables nothing, while `false || (step !== 3)` is the comparison. Comparisons of the step with+// a whole number are exact (a boolean, never nullish); the literals true, false, null, undefined, a number+// and a plain string are what they are; `&&`, `||`, `??` and `!` combine them as JavaScript evaluates them;+// a name declared as a condition (`const isReview = step === 3;`) is read through its declaration. Anything+// else may be truthy or not, and nullish or not, on every value, so it proves nothing.+const COMPARE = { '===': (a, b) => a === b, '==': (a, b) => a === b, '!==': (a, b) => a !== b, '!=': (a, b) => a !== b, '<': (a, b) => a < b, '<=': (a, b) => a <= b, '>': (a, b) => a > b, '>=': (a, b) => a >= b };+const FLIP = { '<': '>', '<=': '>=', '>': '<', '>=': '<=' };+const setOf = (values) => new Set(values);+const intersect = (a, b) => setOf([...a].filter((v) => b.has(v)));+const minus = (a, b) => setOf([...a].filter((v) => !b.has(v)));+const union = (a, b) => setOf([...a, ...b]);++function trimRange(code, start, end) {+ while (start < end && /\s/.test(code[start])) start += 1;+ while (end > start && /\s/.test(code[end - 1])) end -= 1;+ return [start, end];+}++// How each operator combines what is known of its two sides, a and b (JavaScript's own rules):+// a || b a if a is truthy, else b: truthy where either is; nullish only where a is falsy and b nullish+// a ?? b a unless a is nullish, else b: truthy where a is, or where a is nullish and b truthy+// a && b a if a is falsy, else b: truthy where both are; nullish where a is, or a is truthy and b nullish+const COMBINE = {+ '||': (all, a, b) => ({+ may: union(a.may, b.may), must: union(a.must, b.must),+ mayNull: intersect(minus(all, a.must), b.mayNull), mustNull: intersect(minus(all, a.may), b.mustNull),+ }),+ '??': (all, a, b) => ({+ may: union(a.may, intersect(a.mayNull, b.may)), must: union(a.must, intersect(a.mustNull, b.must)),+ mayNull: intersect(a.mayNull, b.mayNull), mustNull: intersect(a.mustNull, b.mustNull),+ }),+ '&&': (all, a, b) => ({+ may: intersect(a.may, b.may), must: intersect(a.must, b.must),+ mayNull: union(a.mayNull, intersect(a.may, b.mayNull)), mustNull: union(a.mustNull, intersect(a.must, b.mustNull)),+ }),+};++function conditionValues(content, text, state, domain, depth = 0) {+ const all = setOf(domain);+ const none = setOf([]);+ const unknown = { may: all, must: none, mayNull: all, mustNull: none };+ const constant = (truthy, nullish = false) => ({ may: truthy ? all : none, must: truthy ? all : none, mayNull: nullish ? all : none, mustNull: nullish ? all : none });+ const { code } = sourceView(text);+ const [start, end] = trimRange(code, 0, code.length);+ if (start >= end) return unknown;+ if (code[start] === '(' && matchingClose(code, start) === end - 1) return conditionValues(content, text.slice(start + 1, end - 1), state, domain, depth);+ // `||` and `??` cannot be mixed without parentheses, so the first that splits the condition is its loosest operator.+ for (const operator of ['||', '??', '&&']) {+ const parts = splitTopLevel(code, start, end, operator);+ if (parts.length > 1) {+ return parts.map(([s, e]) => conditionValues(content, text.slice(s, e), state, domain, depth))+ .reduce((a, b) => COMBINE[operator](all, a, b));+ }+ }+ const bare = code.slice(start, end);+ if (bare[0] === '!' && bare[1] !== '=') {+ const inner = conditionValues(content, text.slice(start + 1, end), state, domain, depth);+ return { may: minus(all, inner.must), must: minus(all, inner.may), mayNull: none, mustNull: none };+ }+ if (bare === 'true' || bare === 'false') return constant(bare === 'true');+ if (bare === 'null' || bare === 'undefined') return constant(false, true);+ if (/^\d+(?:\.\d+)?$/.test(bare)) return constant(Number(bare) !== 0);+ // A plain string literal, read from the source (the code view blanks its text): '' is falsy, anything else truthy.+ const literal = /^(['"])([^'"\\]*)\1$/.exec(text.slice(start, end));+ if (literal) return constant(literal[2] !== '');+ const name = escapeRe(state.value);+ const forward = new RegExp(`^${name}\\s*(===|!==|==|!=|<=|>=|<|>)\\s*(\\d+)$`).exec(bare);+ const backward = new RegExp(`^(\\d+)\\s*(===|!==|==|!=|<=|>=|<|>)\\s*${name}$`).exec(bare);+ if (forward || backward) {+ const op = forward ? forward[1] : FLIP[backward[2]] || backward[2];+ const n = Number(forward ? forward[2] : backward[1]);+ const holds = setOf(domain.filter((v) => COMPARE[op](v, n)));+ return { may: holds, must: holds, mayNull: none, mustNull: none };+ }+ const alias = /^[A-Za-z_$][\w$]*$/.test(bare) && depth < 2 ? declarationSource(content, bare) : null;+ const value = alias && /^\s*(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*([\s\S]*?);?\s*$/.exec(alias);+ if (value && !/=>/.test(value[1])) return conditionValues(content, value[1], state, domain, depth + 1);+ return unknown;+}++// The step values for which the branch of an expression `[start, end)` that holds `at` is rendered:+// cond ? A : B A on what cond may hold for, B on what it need not hold for+// a && b && X X on what every condition may hold for+// a || X X on what a need not hold for (a may be falsy)+// a ?? X X on what a may be null or undefined for — a comparison never is, so X never shows+// read down to the element (a JSX element or anything else restricts nothing further).+function branchValues(content, code, start, end, at, state, domain) {+ const all = setOf(domain);+ [start, end] = trimRange(code, start, end);+ if (start >= end) return all;+ if (code[start] === '(' && matchingClose(code, start) === end - 1) return branchValues(content, code, start + 1, end - 1, at, state, domain);+ const src = content;+ // The top-level `?` of a conditional (not `?.` or `??`) and its `:`.+ let depth = 0;+ let question = -1;+ for (let i = start; i < end; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (depth === 0 && c === '?' && code[i + 1] !== '?' && code[i - 1] !== '?' && !(code[i + 1] === '.' && !/\d/.test(code[i + 2] || ''))) { question = i; break; }+ }+ if (question > 0) {+ let nested = 0;+ let colon = -1;+ depth = 0;+ for (let i = question + 1; i < end; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (depth === 0 && c === '?' && code[i + 1] !== '?' && code[i - 1] !== '?' && !(code[i + 1] === '.' && !/\d/.test(code[i + 2] || ''))) nested += 1;+ else if (depth === 0 && c === ':') {+ if (nested === 0) { colon = i; break; }+ nested -= 1;+ }+ }+ if (colon > 0) {+ const cond = conditionValues(content, src.slice(start, question), state, domain);+ if (at > question && at < colon) return intersect(cond.may, branchValues(content, code, question + 1, colon, at, state, domain));+ if (at > colon) return intersect(minus(all, cond.must), branchValues(content, code, colon + 1, end, at, state, domain));+ return all;+ }+ }+ for (const operator of ['||', '??']) {+ const parts = splitTopLevel(code, start, end, operator);+ if (parts.length > 1) {+ const holder = parts.findIndex(([s, e]) => at >= s && at < e);+ if (holder < 0) return all;+ const before = parts.slice(0, holder).map(([s, e]) => conditionValues(content, src.slice(s, e), state, domain));+ const reached = before.reduce((acc, c) => intersect(acc, operator === '??' ? c.mayNull : minus(all, c.must)), all);+ return intersect(reached, branchValues(content, code, parts[holder][0], parts[holder][1], at, state, domain));+ }+ }+ const ands = splitTopLevel(code, start, end, '&&');+ if (ands.length > 1) {+ const holder = ands.findIndex(([s, e]) => at >= s && at < e);+ if (holder !== ands.length - 1) return all;+ const conditions = ands.slice(0, -1).map(([s, e]) => conditionValues(content, src.slice(s, e), state, domain));+ const reached = conditions.reduce((acc, c) => intersect(acc, c.may), all);+ return intersect(reached, branchValues(content, code, ands[holder][0], ands[holder][1], at, state, domain));+ }+ return all;+}++// The step values on which the element at `at` is rendered AND can be pressed: the switch case it sits+// in, every JSX expression around it up to the function body the JSX is returned from (a `{` after `)`+// or `=>`), and its own `disabled` (disabled for good, or on the values where the condition must hold).+function reachableSteps(content, code, element, state, domain, regions) {+ let values = setOf(domain);+ const cases = regions.filter((r) => r.kind === 'case' && r.start <= element.start && element.start < r.end);+ if (cases.length) values = intersect(values, setOf(cases.map((r) => r.step)));+ let pos = element.start;+ for (let open = enclosingContainer(code, pos); open >= 0; open = enclosingContainer(code, pos)) {+ let k = open - 1;+ while (k >= 0 && /\s/.test(code[k])) k -= 1;+ if (code[k] === ')' || (code[k] === '>' && code[k - 1] === '=')) break;+ const close = matchingClose(code, open);+ if (close > open) values = intersect(values, branchValues(content, code, open + 1, close, element.start, state, domain));+ pos = open;+ }+ const disabled = element.attrs.get('disabled');+ if (disabled?.kind === 'flag' || (disabled?.kind === 'string' && disabled.value !== 'false')) return setOf([]);+ if (disabled?.kind === 'expression') values = minus(values, conditionValues(content, disabled.value, state, domain).must);+ return values;+}++// The values the step takes: each value the page renders on its own, and the step state's initial value.+function stepDomain(code, state, regions) {+ const values = setOf(regions.map((r) => r.step));+ const init = new RegExp(`\\[\\s*${escapeRe(state.value)}\\s*,\\s*${escapeRe(state.setter)}\\s*\\]\\s*=\\s*(?:React\\s*\\.\\s*)?useState(?:<[^>()]*>)?\\s*\\(\\s*(\\d+)\\s*\\)`).exec(code);+ if (init) values.add(Number(init[1]));+ return [...values].sort((a, b) => a - b);+}++// eval 4: "Step 3 (review) shows a summary of entered data before submission". The review step is the+// last step the page renders on its own; it must show every value the earlier steps' form controls+// bind, and EVERY button that submits (labelled Submit/Create/Save/Finish, or whose handler writes with+// createRow/updateRow) must be reachable only on the review step: rendered and enabled for no other value+// of the step (reachableSteps), so the summary is always seen first. A second, unconditional submit, or a+// boundary that lets the submit show on an earlier step (`step < 1 ? Next : Submit`), fails it. A condition+// the reader cannot tie to the step (`ready ? Submit : null`) proves nothing and fails it too. It does not+// judge how the summary looks.+function reviewSummaryProblems(content) {+ const { src, code } = sourceView(content);+ const [state] = stepStates(content);+ if (!state) return ['no step state, so there is no review step'];+ const regions = stepRegions(code, state.value);+ if (!regions.length) return [`no JSX is rendered for a single value of ${state.value} (e.g. {${state.value} === 3 && (…)})`];+ const review = regions.reduce((last, region) => (region.step > last.step ? region : last));+ const shown = code.slice(review.start, review.end);+ // The fields the EARLIER steps enter: a control on the review step itself (a confirmation box) is not data to summarize.+ const fields = boundFields(content).filter((field) => field.at < review.start || field.at >= review.end);+ if (!fields.length) return ['the form binds no field the review step could summarize'];+ const problems = fields.filter((field) => !field.pattern.test(shown)).map((field) => `the review step (${state.value} === ${review.step}) does not show ${field.label}`);+ const submits = jsxElements(content, BUTTON_TAGS).filter((button) => {+ const onClick = button.attrs.get('onClick');+ const handler = onClick && onClick.kind === 'expression' ? handlerSource(content, onClick.value) : '';+ return /\b(?:submit|create|save|finish)\b/i.test(buttonLabel(src, button)) || /\b(?:createRow|updateRow)\b/.test(handler);+ });+ if (!submits.length) return [...problems, 'no button submits the entered data'];+ const domain = stepDomain(code, state, regions);+ for (const button of submits) {+ const reached = [...reachableSteps(content, code, button, state, domain, regions)];+ if (reached.some((value) => value !== review.step)) {+ problems.push(`the submit button "${buttonLabel(src, button)}" can be pressed when ${state.value} is ${reached.filter((v) => v !== review.step).join(' or ')}, not only on the review step (${state.value} === ${review.step})`);+ }+ }+ if (!submits.some((button) => reachableSteps(content, code, button, state, domain, regions).has(review.step))) {+ problems.push(`no submit button can be pressed on the review step (${state.value} === ${review.step})`);+ }+ return problems;+}++// eval 4: "All form fields have aria-labels or aria-labelledby for accessibility". A control is labelled+// by its own aria-label/aria-labelledby, or by what gives it the same accessible name: a Fluent UI+// `<Field label=…>` around it (Field wires its label to the control with aria-labelledby), a `label`+// prop on a Checkbox/Switch/Radio (rendered as its <label>), or an `id` that a `<label htmlFor>` (or+// Fluent `<Label htmlFor>`) that can show some text names. A label only counts when it can name something:+// an empty string, `{''}`, `{null}`, `{undefined}` or `{false}` is no label, whereas a computed one+// (`label={translate('title')}`) is; the same goes for the children of a label element (childrenShowText).+// A spread (`{...props}`) may carry a label the page does not show, so it is not reported. A hidden input+// (`type="hidden"`) is no field. Returns null when the page has no form control.+// Two known limits, left as they are on purpose (this grades eval evidence; it is no gate a page must pass): an+// empty value that also holds a comment (`{/* hidden */ null}`, `label={/* none */ ''}`) counts as a label, because+// STATIC_EMPTY is tested on the source with its comments; and a label element whose text is only character references+// (`Title`) is not counted, because jsxTextRuns reads a character reference as a space.+const STATIC_EMPTY = /^\s*(?:(['"`])\s*\1|null|undefined|false)\s*$/;+const names = (attr) => Boolean(attr) && ((attr.kind === 'string' && attr.value.trim() !== '')+ || (attr.kind === 'expression' && attr.value.trim() !== '' && !STATIC_EMPTY.test(attr.value)));++// Whether an element's children can show any text: a run of JSX text that is not blank, or an expression+// container that is not statically empty, at any depth of the markup inside it. `{null}`, `{''}`,+// `{undefined}`, `{false}` and a container holding only a comment (`{/* … */}`, blank in the code view)+// show nothing, and the tags and attributes of nested elements are no text:+// <label htmlFor="t">Title</label> shows text+// <label htmlFor="t">{translate('title')}</label> may show text (a computed value is not judged)+// <label htmlFor="t"><span>{null}</span></label> shows nothing+function childrenShowText(content, element) {+ const { src, code } = sourceView(content);+ const from = element.childrenStart;+ const to = element.childrenEnd;+ if (jsxTextRuns(content).some((run) => run.start >= from && run.end <= to && run.text.trim() !== '')) return true;+ const nested = jsxElements(content).filter((e) => e.start >= from && e.start < to);+ const inTag = (i) => nested.some((e) => (i >= e.start && i < e.openEnd) || (!e.selfClosing && i >= e.childrenEnd && i < e.end));+ for (let i = from; i < to; i += 1) {+ if (code[i] !== '{' || inTag(i)) continue;+ const close = matchingClose(code, i);+ if (close < 0 || close > to) return true;+ if (code.slice(i + 1, close).trim() !== '' && !STATIC_EMPTY.test(src.slice(i + 1, close))) return true;+ i = close;+ }+ return false;+}++function formFieldLabelProblems(content) {+ const controls = jsxElements(content, FORM_CONTROLS).filter((c) => c.attrs.get('type')?.value !== 'hidden');+ if (!controls.length) return null;+ const fields = jsxElements(content, /^Field$/).filter((f) => names(f.attrs.get('label')));+ const htmlFor = new Set(jsxElements(content, /^(?:Label|label)$/)+ .filter((l) => childrenShowText(content, l))+ .map((l) => l.attrs.get('htmlFor')?.value).filter((v) => typeof v === 'string' && v));+ const problems = [];+ for (const control of controls) {+ const { attrs } = control;+ if (names(attrs.get('aria-label')) || names(attrs.get('aria-labelledby')) || attrs.has('...')) continue;+ if (/^(?:Checkbox|Switch|Radio)$/.test(control.name) && names(attrs.get('label'))) continue;+ if (fields.some((field) => control.start >= field.childrenStart && control.start < field.childrenEnd)) continue;+ const id = attrs.get('id');+ if (id && id.kind === 'string' && htmlFor.has(id.value)) continue;+ problems.push(`<${control.name}> has no aria-label, aria-labelledby or label`);+ }+ return problems;+}++// eval 12: "Generated code implements the revised plan (includes BOTH filter toolbar AND search box)".+// A search box is a SearchBox, or an Input of type="search" or one whose placeholder or aria-label says+// search, wired to state by an onChange/onInput handler. A filter toolbar is a Fluent UI Toolbar (or an+// element with role="toolbar") holding at least one control — a Dropdown, Combobox, Select, toggle or+// radio, Checkbox, Switch, MenuButton or TabList — with a handler. Whether the two narrow the same rows+// is not judged.+const FILTER_CONTROLS = /^(?:Dropdown|Combobox|Select|ToggleButton|ToolbarToggleButton|ToolbarRadioButton|ToolbarRadioGroup|Checkbox|Switch|MenuButton|TabList|RadioGroup|select)$/;+const HANDLERS = ['onOptionSelect', 'onChange', 'onClick', 'onCheckedValueChange', 'onTabSelect', 'onSelectionChange', 'onInput'];+function searchAndFilterProblems(content) {+ const searchBoxes = jsxElements(content, /^(?:SearchBox|Input|input)$/).filter((el) => {+ if (el.name !== 'SearchBox') {+ const said = ['type', 'placeholder', 'aria-label'].map((name) => el.attrs.get(name)).filter((a) => a && a.kind === 'string').map((a) => a.value).join(' ');+ if (!/search/i.test(said)) return false;+ }+ return el.attrs.has('onChange') || el.attrs.has('onInput');+ });+ const toolbars = jsxElements(content, /^[A-Za-z][\w.]*$/).filter((el) => el.name === 'Toolbar' || el.attrs.get('role')?.value === 'toolbar');+ const filtering = toolbars.filter((toolbar) => jsxElements(content, FILTER_CONTROLS).some((control) => control.start >= toolbar.childrenStart && control.start < toolbar.childrenEnd+ && HANDLERS.some((name) => control.attrs.has(name))));+ const problems = [];+ if (!searchBoxes.length) problems.push('no search box (a SearchBox, or a search Input) wired to an onChange handler');+ if (!filtering.length) problems.push(toolbars.length ? 'the toolbar holds no filter control with a handler' : 'no filter toolbar (a Toolbar, or role="toolbar") with filter controls');+ return problems;+}++// eval 13: "All user-visible text goes through a translate() helper — no hardcoded display strings in JSX".+// The helper is `translate` (references/localization.md) or its usual short form `t`, declared in the+// page and called. Text is hardcoded when a JSX text run holds a letter (`<Text>Contacts</Text>`), a+// shown attribute is a string with a letter (`placeholder="Search"`), or a JSX expression — a child+// `{…}` or a shown attribute's value — can RESULT in a string or template with a letter+// (displayedLiterals): `{'No contacts'}`, `{rows.length ? 'Contacts' : t('empty')}`, `{error || 'Failed'}`,+// `{`${n} contacts`}`. A string passed to a call (`t('empty')`) is a key, not a result. Character+// references are not letters (` `), nor are punctuation and digits (`({rows.length})`, `{`${n}`}`).+// NOT read: a string a function returns to JSX (`renderHeaderCell: () => 'Name'`) or a variable holding one.+const SHOWN_ATTRIBUTES = new Set(['label', 'placeholder', 'title', 'aria-label', 'aria-description', 'alt', 'header', 'description', 'content', 'hint', 'validationMessage', 'text']);++// The string and template literals an expression can evaluate to, as { quote, text }: the expression+// itself, both sides of a conditional, the right side of `&&`, and every side of `||` and `??`, through+// parentheses. Anything else — a call, a name, a member, a JSX element — results in no literal.+function displayedLiterals(text) {+ const { code } = sourceView(text);+ const out = [];+ const visit = (from, to) => {+ let [start, end] = trimRange(code, from, to);+ if (start >= end) return;+ if (code[start] === '(' && matchingClose(code, start) === end - 1) { visit(start + 1, end - 1); return; }+ let depth = 0;+ for (let i = start; i < end; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') depth -= 1;+ else if (depth === 0 && c === '?' && code[i + 1] !== '?' && code[i - 1] !== '?' && !(code[i + 1] === '.' && !/\d/.test(code[i + 2] || ''))) {+ let nested = 0;+ let inner = 0;+ for (let j = i + 1; j < end; j += 1) {+ const d = code[j];+ if (d === '(' || d === '[' || d === '{') inner += 1;+ else if (d === ')' || d === ']' || d === '}') inner -= 1;+ else if (inner === 0 && d === '?' && code[j + 1] !== '?' && code[j - 1] !== '?' && !(code[j + 1] === '.' && !/\d/.test(code[j + 2] || ''))) nested += 1;+ else if (inner === 0 && d === ':') {+ if (nested === 0) { visit(i + 1, j); visit(j + 1, end); return; }+ nested -= 1;+ }+ }+ return;+ }+ }+ for (const operator of ['||', '??']) {+ const parts = splitTopLevel(code, start, end, operator);+ if (parts.length > 1) { for (const [s, e] of parts) visit(s, e); return; }+ }+ const ands = splitTopLevel(code, start, end, '&&');+ if (ands.length > 1) { visit(...ands.at(-1)); return; }+ const quote = code[start];+ if (/['"`]/.test(quote) && code[end - 1] === quote && !code.slice(start + 1, end - 1).trim()) out.push({ quote, text: text.slice(start + 1, end - 1) });+ };+ visit(0, text.length);+ return out;+}++// Letters a literal shows: a template's `${…}` parts are values, not text.+const shownLetters = ({ quote, text }) => hasLetter(quote === '`' ? text.replace(/\$\{[^}]*\}/g, ' ') : text);++function translateCoverageProblems(content) {+ const { src, code } = sourceView(content);+ const helper = ['translate', 't'].find((name) => declarationSource(content, name) && new RegExp(`(?<![.\\w$])${name}\\s*\\(`).test(code.replace(new RegExp(`\\b(?:const|let|var|function)\\s+${name}\\b`, 'g'), '')));+ if (!helper) return ['no translate() helper is declared and called'];+ const problems = [];+ for (const run of jsxTextRuns(content)) {+ if (hasLetter(run.text)) problems.push(`hardcoded JSX text "${run.text.trim().slice(0, 40)}"`);+ }+ for (const element of jsxElements(content)) {+ for (const [name, attr] of element.attrs) {+ if (!SHOWN_ATTRIBUTES.has(name)) continue;+ const literals = attr.kind === 'string' ? [{ quote: '"', text: attr.value }] : attr.kind === 'expression' ? displayedLiterals(attr.value) : [];+ for (const literal of literals.filter(shownLetters)) problems.push(`hardcoded ${name} ${literal.quote}${literal.text.slice(0, 40)}${literal.quote} on <${element.name}>`);+ }+ }+ for (let i = code.indexOf('{'); i >= 0; i = code.indexOf('{', i + 1)) {+ let k = i - 1;+ while (k >= 0 && /\s/.test(code[k])) k -= 1;+ // A JSX child container follows a tag's `>` or another container's `}` — not an arrow's `=>`.+ if ((code[k] !== '>' && code[k] !== '}') || (code[k] === '>' && code[k - 1] === '=')) continue;+ const close = matchingClose(code, i);+ if (close < 0) continue;+ for (const literal of displayedLiterals(src.slice(i + 1, close)).filter(shownLetters)) {+ problems.push(`hardcoded JSX string ${literal.quote}${literal.text.slice(0, 40)}${literal.quote}`);+ }+ }+ return problems;+}++// eval 15: "Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)". A choice+// value of a custom column is 100000000 or more (Dataverse's option value floor for a publisher's choices).+// Every such literal in the page's code must be NAMED by the enum member RuntimeTypes.ts declares for it:+// const PRIORITY_HIGH = 100000002; the constant's name ends with the member's label (High)+// { value: 100000002, label: 'High' } an option row that carries the member's label+// and the value must be that member's. A literal anywhere else (`row.cr_status === 100000002`) is a magic+// number, and a name whose value differs from RuntimeTypes.ts (`HIGH = 100000001`) is a wrong one. Using+// the enum itself (`cr_ticket_cr_priority.High`) needs no literal. Returns null when the page compares+// no choice value at all (nothing to name). Statecode/statuscode values (0, 1, 2…) are not read: below+// the floor a number cannot be told from a count or a size.+const CHOICE_FLOOR = 100000000;+const normalized = (text) => String(text).toLowerCase().replace(/[^a-z0-9]/g, '');+function choiceEnumProblems(content, runtimeTypes) {+ const { src, code } = sourceView(content);+ const members = [...runtimeEnums(runtimeTypes).enums.values()].flat().filter((m) => m.value >= CHOICE_FLOOR);+ const enumNames = [...runtimeEnums(runtimeTypes).enums.keys()];+ const literals = [...code.matchAll(/(?<![\w$.])(\d{9,})(?![\w$.])/g)].filter((m) => Number(m[1]) >= CHOICE_FLOOR);+ if (!literals.length) return enumNames.some((name) => word(name).test(code)) ? [] : null;+ const problems = [];+ for (const m of literals) {+ const value = Number(m[1]);+ const candidates = members.filter((member) => member.value === value);+ if (!candidates.length) { problems.push(`${value} is not a choice value RuntimeTypes.ts declares`); continue; }+ const before = code.slice(0, m.index);+ const constant = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[\w$.<>[\]|\s]+)?=\s*$/.exec(before) || /(?:^|[,{]\s*)([A-Za-z_$][\w$]*)\s*=\s*$/.exec(before.slice(-200));+ if (constant) {+ const named = members.filter((member) => normalized(constant[1]).endsWith(normalized(member.label)));+ if (!named.length) problems.push(`${constant[1]} = ${value} is not named after a RuntimeTypes.ts choice label`);+ else if (!named.some((member) => member.value === value)) {+ problems.push(`${constant[1]} = ${value}, but RuntimeTypes.ts gives ${named.map((member) => `${member.label} = ${member.value}`).join(', ')}`);+ }+ continue;+ }+ // An option row: the number is a property's value, and the object literal around it carries a label+ // that is the member's (`{ value: 100000002, label: 'High' }`).+ if (/[A-Za-z_$][\w$]*\s*:\s*$/.test(before)) {+ const open = enclosingContainer(code, m.index);+ const close = open >= 0 ? matchingClose(code, open) : -1;+ const row = close > m.index ? src.slice(open, close + 1) : '';+ const labels = [...row.matchAll(/\b(?:label|name|text)\s*:\s*(['"`])([^'"`]*)\1/g)].map((x) => x[2]);+ if (labels.some((label) => candidates.some((member) => normalized(member.label) === normalized(label)))) continue;+ }+ const line = src.slice(0, m.index).split('\n').length;+ problems.push(`magic number ${value} on line ${line}: name it after its RuntimeTypes.ts choice label`);+ }+ return problems;+}++module.exports = {+ reviewSummaryProblems, formFieldLabelProblems, searchAndFilterProblems,+ translateCoverageProblems, choiceEnumProblems, stepStates, boundFields,+};diff --git a/evals/model-apps/genpage/lib/preservation-contract.js b/evals/model-apps/genpage/lib/preservation-contract.jsnew file mode 100644index 000000000..2a4dcff12--- /dev/null+++ b/evals/model-apps/genpage/lib/preservation-contract.js@@ -0,0 +1,66 @@+'use strict';++// eval 3's "Edit Phase 5: Existing functionality is preserved per the edit plan's Preservation Constraints",+// graded from what the run kept: the page it downloaded before the edit (a `before/*.tsx` artifact of a+// contract-2 fixture) and the page it uploaded (the fixture's top-level .tsx of the same name).+//+// agents/genpage-edit-planner.md asks for constraints that are "independently verifiable", and the plan+// quotes the code it means in backticks, e.g.+// ## Preservation Constraints+// - The window cache and in-flight de-dupe keys (`__ppContactsDirectory_contactCache` /+// `__ppContactsDirectory_contactInflight`), the `[dataReady]` dependency and the single batched+// `setData` stay exactly as they are.+// So the identifiers in those code spans that the DOWNLOADED page uses are the functionality the plan+// promised to keep, and each must still be used by the EDITED page. A span that names nothing the old+// page has (`--connectors`, a column it never selected) promises nothing about it and is not read.+// Comments are left out of both pages, so a comment cannot keep a deleted cache key "present".+//+// It does not judge behaviour — that a kept query still returns the same rows — which the Layer 3 rubric+// does; and constraints written only in prose, with no code span, are skipped for a person to judge.++const { planSection } = require('./plan-evidence.js');+const { fileName } = require('./evidence-utils.js');+const { currentContract } = require('./workflow-evidence.js');+const { withoutComments } = require('./tsx-structure.js');++const IDENTIFIER = /[A-Za-z_$][\w$]*/g;++const uses = (text, name) => new RegExp(`(?<![\\w$])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(text);++// The identifiers the constraints quote in code spans, three characters or longer (a one-letter loop+// variable or `id` says nothing about which feature is meant).+function quotedIdentifiers(section) {+ const names = new Set();+ for (const span of String(section).matchAll(/`([^`\n]+)`/g)) {+ for (const name of span[1].match(IDENTIFIER) || []) if (name.length >= 3) names.add(name);+ }+ return [...names];+}++// Returns { skip } when there is nothing the constraints can be graded against, else a list of problems.+function preservationProblems(fixture) {+ if (!fixture.genpageEditPlan) return ['no genpage-edit-plan.md'];+ const section = planSection(fixture.genpageEditPlan, 'Preservation Constraints');+ if (section === null || !section.trim()) return ['genpage-edit-plan.md has no ## Preservation Constraints'];+ const before = Object.entries(fixture.artifacts || {}).filter(([name]) => /^before\/[^/]+\.tsx$/.test(name));+ if (!before.length) {+ return currentContract(fixture) ? ['the downloaded page (a before/<page>.tsx artifact) was not captured'] : { skip: 'the downloaded page was not captured' };+ }+ const names = quotedIdentifiers(section);+ const problems = [];+ let graded = 0;+ for (const [name, source] of before) {+ const edited = (fixture.files || []).find((file) => file.name === fileName(name));+ if (!edited) { problems.push(`the edited ${fileName(name)} was not captured beside before/${fileName(name)}`); continue; }+ const old = withoutComments(source);+ const now = withoutComments(edited.content);+ for (const identifier of names.filter((id) => uses(old, id))) {+ graded += 1;+ if (!uses(now, identifier)) problems.push(`${edited.name} no longer uses \`${identifier}\`, which the Preservation Constraints keep`);+ }+ }+ if (!problems.length && graded === 0) return { skip: 'the Preservation Constraints quote no code the downloaded page uses, so a person judges them' };+ return problems;+}++module.exports = { preservationProblems, quotedIdentifiers };diff --git a/evals/model-apps/genpage/lib/tsx-structure.js b/evals/model-apps/genpage/lib/tsx-structure.jsnew file mode 100644index 000000000..6e3695e01--- /dev/null+++ b/evals/model-apps/genpage/lib/tsx-structure.js@@ -0,0 +1,476 @@+'use strict';++// Structure read from a generated page's TSX: its JSX elements and their attributes, the text its JSX+// shows, and its named function definitions with the scopes around them. Used by the Layer 2 checks+// that ask how a page is BUILT (which control is labelled, which step a button moves to, which text a+// user sees, which function is nested in another) rather than whether some word appears in it.+//+// No parser: the plugin ships dependency-free and the harness grades with its own pure primitives.+// Everything is read from the plugin's lexer view (scripts/lib/source-literals.js `blankLiterals`),+// where every comment, string, template, regex body and JSX text run is blanked to spaces and the+// offsets stay 1:1 with the source, so a `>`, `{` or `=>` inside a label never moves a bracket count,+// and the original text at the same offsets gives the value back. For example+// source: <Field label="First name"><Input aria-label="First" value={form.x} /></Field>+// view: <Field label="··········"><Input aria-label="·····" value={form.x} /></Field>+// source: <Text>Hello {name} world</Text> view: <Text>······{name}······</Text>+// Limits, by design (each check that uses this says which it lives with):+// - an element is found where a `<Name` stands at the start of an expression (after `(`, `=`, `,`,+// `?`, `:`, `{`, `}`, `>`, `&&`, `return`, …); `useState<Row>(…)` and `a < b` are not elements;+// - a closing tag is matched by name, counting nested same-name elements;+// - JSX text is a blanked run whose nearest code character before it is `>` or `}` (a string's run+// follows its quote, a template's its backtick, a regex body its `/`), comments excluded;+// - a function's scope is a body `{…}` (or an arrow's expression) found from `=>` and `function`;+// a declaration with no semicolon may run on into the next statement.++const { blankLiterals, commentRanges } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');++const IDENT_CHAR = /[\w$]/;+// Words after which an expression (so an element) may start, as in source-literals.js EXPR_START_WORDS.+const EXPR_WORDS = new Set(['return', 'yield', 'await', 'default', 'case', 'else', 'do', 'in', 'of', 'typeof', 'void', 'throw']);+const OPENERS = { '(': ')', '[': ']', '{': '}' };++function sourceView(content) {+ const src = String(content || '');+ return { src, code: blankLiterals(src) };+}++function prevSignificant(code, i) {+ let k = i - 1;+ while (k >= 0 && /\s/.test(code[k])) k -= 1;+ return k;+}++function wordBefore(code, end) {+ let k = end;+ while (k >= 0 && IDENT_CHAR.test(code[k])) k -= 1;+ return code.slice(k + 1, end + 1);+}++// Whether a `<` at `at` (in the code view) may open an element: what stands before it starts an expression.+function elementMayStart(code, at) {+ const k = prevSignificant(code, at);+ if (k < 0) return true;+ if (IDENT_CHAR.test(code[k])) return EXPR_WORDS.has(wordBefore(code, k));+ return !/[)\]]/.test(code[k]);+}++// The index of the bracket that closes the one at `open` in the code view, or -1.+function matchingClose(code, open) {+ const close = OPENERS[code[open]];+ if (!close) return -1;+ let depth = 0;+ for (let i = open; i < code.length; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') {+ depth -= 1;+ if (depth === 0) return c === close ? i : -1;+ }+ }+ return -1;+}++// The end of an opening tag whose name ends at `from`: the index of its `>`, and whether it is `/>`.+function tagEnd(code, from) {+ let depth = 0;+ for (let i = from; i < code.length; i += 1) {+ const c = code[i];+ if (c === '{' || c === '(' || c === '[') depth += 1;+ else if (c === '}' || c === ')' || c === ']') depth -= 1;+ else if (c === '>' && depth === 0) return { end: i, selfClosing: code[prevSignificant(code, i)] === '/' };+ else if (c === '<' && depth === 0 && code[i + 1] !== '/') return null;+ }+ return null;+}++// The attributes of an opening tag, read from the code view between `from` and `end` (its `>`):+// name="text" | name='text' → { kind: 'string', value: text }+// name={expression} → { kind: 'expression', value: expression source }+// name → { kind: 'flag', value: true }+// A spread `{...props}` is kept under the key '...' (its presence can label a control the page cannot see).+function readAttributes(src, code, from, end) {+ const attrs = new Map();+ let i = from;+ while (i < end) {+ const c = code[i];+ if (/\s|\//.test(c)) { i += 1; continue; }+ if (c === '{') {+ const close = matchingClose(code, i);+ if (close < 0 || close > end) break;+ if (/^\{\s*\.\.\./.test(code.slice(i, close))) attrs.set('...', { kind: 'spread', value: src.slice(i + 1, close) });+ i = close + 1;+ continue;+ }+ const name = /^[A-Za-z_][\w:.-]*/.exec(code.slice(i, end));+ if (!name) { i += 1; continue; }+ let j = i + name[0].length;+ while (j < end && /\s/.test(code[j])) j += 1;+ if (code[j] !== '=') { attrs.set(name[0], { kind: 'flag', value: true }); i = j; continue; }+ j += 1;+ while (j < end && /\s/.test(code[j])) j += 1;+ if (code[j] === '"' || code[j] === '\'') {+ const close = code.indexOf(code[j], j + 1);+ if (close < 0 || close > end) break;+ attrs.set(name[0], { kind: 'string', value: src.slice(j + 1, close), start: j });+ i = close + 1;+ } else if (code[j] === '{') {+ const close = matchingClose(code, j);+ if (close < 0 || close > end) break;+ attrs.set(name[0], { kind: 'expression', value: src.slice(j + 1, close), start: j });+ i = close + 1;+ } else {+ i = j + 1;+ }+ }+ return attrs;+}++// Every element of the page whose tag name `accept` allows (a Set, a RegExp, or nothing for all), in+// source order: { name, start, openEnd, selfClosing, attrs, childrenStart, childrenEnd, end }. The+// children of a self-closing element, or of one whose closing tag cannot be found, are empty.+function jsxElements(content, accept = null) {+ const { src, code } = sourceView(content);+ const allowed = (name) => !accept || (accept instanceof Set ? accept.has(name) : accept.test(name));+ const out = [];+ for (const m of code.matchAll(/<([A-Za-z][\w.]*)(?=[\s/>])/g)) {+ const name = m[1];+ if (!allowed(name) || !elementMayStart(code, m.index)) continue;+ const tag = tagEnd(code, m.index + m[0].length);+ if (!tag) continue;+ const element = {+ name,+ start: m.index,+ openEnd: tag.end + 1,+ selfClosing: tag.selfClosing,+ attrs: readAttributes(src, code, m.index + m[0].length, tag.end),+ childrenStart: tag.end + 1,+ childrenEnd: tag.end + 1,+ end: tag.end + 1,+ };+ if (!tag.selfClosing) {+ const close = closingTag(code, name, tag.end + 1);+ if (close) Object.assign(element, { childrenEnd: close.start, end: close.end });+ }+ out.push(element);+ }+ return out;+}++// The `</name>` that closes an element whose opening tag ends before `from`, counting nested+// non-self-closing elements of the same name.+function closingTag(code, name, from) {+ const re = new RegExp(`<(/?)${name.replace(/[.$]/g, '\\$&')}(?=[\\s/>])`, 'g');+ re.lastIndex = from;+ let depth = 1;+ for (let m = re.exec(code); m; m = re.exec(code)) {+ if (m[1]) {+ depth -= 1;+ if (depth === 0) {+ const gt = code.indexOf('>', m.index);+ return gt < 0 ? null : { start: m.index, end: gt + 1 };+ }+ } else if (elementMayStart(code, m.index)) {+ const tag = tagEnd(code, m.index + m[0].length);+ if (tag && !tag.selfClosing) depth += 1;+ }+ }+ return null;+}++// The text a page's JSX shows as written: each run of JSX text, { start, end, text }. HTML character+// references (`&`, `—`) are decoded to a space so that `Review & submit` reads as words+// and ` ` alone reads as none.+function jsxTextRuns(content) {+ const { src, code } = sourceView(content);+ const comment = new Uint8Array(src.length);+ for (const { start, end } of commentRanges(src)) comment.fill(1, start, end);+ const runs = [];+ let opener = '';+ let run = null;+ for (let i = 0; i < src.length; i += 1) {+ const literal = code[i] !== src[i] && !comment[i];+ if (literal && (opener === '>' || opener === '}')) {+ if (!run) run = { start: i, end: i + 1 };+ else run.end = i + 1;+ continue;+ }+ if (!literal && !comment[i] && !/\s/.test(code[i])) {+ if (run) { runs.push(run); run = null; }+ opener = code[i];+ }+ }+ if (run) runs.push(run);+ return runs.map((r) => ({ ...r, text: src.slice(r.start, r.end).replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ') }));+}++// The source of a declaration named `name` — `const name = …`, `let`/`var`, or `function name(…) {…}` —+// up to the end of its body or its depth-0 `;`, or null. Used to follow a handler one level: an+// `onClick={goNext}` is read through `const goNext = () => setStep(…)`.+function declarationSource(content, name) {+ const { src, code } = sourceView(content);+ const escaped = name.replace(/\$/g, '\\$');+ const decl = new RegExp(`(?:\\b(?:const|let|var)\\s+${escaped}\\s*[:=]|\\bfunction\\s+${escaped}\\s*[<(])`).exec(code);+ if (!decl) return null;+ let depth = 0;+ let sawBlock = false;+ for (let i = decl.index + decl[0].length; i < code.length; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') { depth += 1; if (c === '{') sawBlock = true; continue; }+ if (c === ')' || c === ']' || c === '}') {+ depth -= 1;+ if (depth < 0) return src.slice(decl.index, i);+ if (depth === 0 && c === '}' && sawBlock && /^\s*(?:;|$|\n)/.test(code.slice(i + 1, i + 3))) return src.slice(decl.index, i + 1);+ continue;+ }+ if (depth === 0 && c === ';') return src.slice(decl.index, i + 1);+ }+ return src.slice(decl.index);+}++// --- Function definitions and their scopes ---------------------------------------------------------++// Skip a TypeScript return type after a parameter list: `): JSX.Element {` or `): Promise<void> =>`.+// Returns the index of the `{` or `=>` that follows, or -1.+function afterReturnType(code, from) {+ let i = from;+ while (i < code.length && /\s/.test(code[i])) i += 1;+ if (code[i] !== ':') return i;+ let angle = 0;+ for (i += 1; i < code.length; i += 1) {+ const c = code[i];+ if (c === '<') angle += 1;+ else if (c === '>' && code[i - 1] !== '=') angle -= 1;+ else if (angle === 0 && (c === '{' || (c === '=' && code[i + 1] === '>'))) return i;+ else if (angle === 0 && c === ';') return -1;+ }+ return -1;+}++// The extent of an arrow's or function's body that starts at `at` (a `{`, or the first character of an+// expression body): { start, end } with `end` exclusive.+function bodyExtent(code, at) {+ if (code[at] === '{') {+ const close = matchingClose(code, at);+ return { start: at, end: close < 0 ? code.length : close + 1 };+ }+ let depth = 0;+ for (let i = at; i < code.length; i += 1) {+ const c = code[i];+ if (c === '(' || c === '[' || c === '{') depth += 1;+ else if (c === ')' || c === ']' || c === '}') {+ if (depth === 0) return { start: at, end: i };+ depth -= 1;+ } else if (depth === 0 && (c === ';' || c === ',')) return { start: at, end: i };+ }+ return { start: at, end: code.length };+}++// Identifiers a parameter list or binding pattern declares, with type annotations and defaults left out:+// (props: GeneratedComponentProps) → props+// (e: React.DragEvent<HTMLDivElement>, id) → e, id+// [{ tasks, loading, error }, setData] → tasks, loading, error, setData+// { dataApi, pageInput: input = null } → dataApi, input+// A `:` inside an object pattern renames (`a: b` binds b); anywhere else it starts a type annotation,+// which — like a default after `=` — is skipped to the next `,` or closing bracket of its level.+function patternNames(text) {+ const s = String(text);+ const names = [];+ const stack = [];+ const skipValue = (from) => {+ let depth = 0;+ for (let k = from; k < s.length; k += 1) {+ const c = s[k];+ if (c === '(' || c === '[' || c === '{' || c === '<') depth += 1;+ else if (c === ')' || c === ']' || c === '}' || (c === '>' && s[k - 1] !== '=')) {+ if (depth === 0) return k;+ depth -= 1;+ } else if (c === ',' && depth === 0) return k;+ }+ return s.length;+ };+ let i = 0;+ while (i < s.length) {+ const c = s[i];+ if (c === '(' || c === '[' || c === '{') { stack.push(c); i += 1; continue; }+ if (c === ')' || c === ']' || c === '}') { stack.pop(); i += 1; continue; }+ // A `:` or `=` after a whole pattern (`{ item }: Props`, `[a] = []`) annotates or defaults it.+ if (c === ':' || c === '=') { i = skipValue(i + 1); continue; }+ const word = /^[A-Za-z_$][\w$]*/.exec(s.slice(i));+ if (!word) { i += 1; continue; }+ let j = i + word[0].length;+ while (j < s.length && /\s/.test(s[j])) j += 1;+ if (s[j] === ':' && stack.at(-1) === '{') { i = j + 1; continue; }+ if (!/^(?:const|let|var|async|readonly|public|private|protected)$/.test(word[0])) names.push(word[0]);+ if (s[j] === '?') j += 1;+ while (j < s.length && /\s/.test(s[j])) j += 1;+ i = s[j] === ':' || s[j] === '=' ? skipValue(j + 1) : j;+ }+ return names;+}++// The source with every comment replaced by spaces (line breaks kept), so offsets still map 1:1 and a+// name or a quoted word inside a comment is never read as code or as a string the code holds.+function withoutComments(content) {+ const src = String(content || '');+ const out = src.split('');+ for (const { start, end } of commentRanges(src)) for (let i = start; i < end; i += 1) if (out[i] !== '\n' && out[i] !== '\r') out[i] = ' ';+ return out.join('');+}++// Every function body in the page — of an arrow, a `function` declaration or expression, or a+// method — with its parameter names: { start, end, params }.+function functionScopes(code) {+ const scopes = [];+ for (const m of code.matchAll(/=>/g)) {+ let body = m.index + 2;+ while (body < code.length && /\s/.test(code[body])) body += 1;+ // The parameters: `(…)` before the arrow (after an optional return type), or one bare name.+ let k = prevSignificant(code, m.index);+ let params = '';+ if (code[k] === ')') {+ let depth = 0;+ for (let j = k; j >= 0; j -= 1) {+ if (code[j] === ')') depth += 1;+ else if (code[j] === '(' && --depth === 0) { params = code.slice(j + 1, k); break; }+ }+ } else if (IDENT_CHAR.test(code[k])) {+ params = wordBefore(code, k);+ }+ scopes.push({ ...bodyExtent(code, body), params: patternNames(params) });+ }+ for (const m of code.matchAll(/\bfunction\b\s*\*?\s*(?:[A-Za-z_$][\w$]*)?\s*(?:<[^>()]*>)?\s*\(/g)) {+ const open = m.index + m[0].length - 1;+ const close = matchingClose(code, open);+ if (close < 0) continue;+ const at = afterReturnType(code, close + 1);+ if (at < 0 || code[at] !== '{') continue;+ scopes.push({ ...bodyExtent(code, at), params: patternNames(code.slice(open + 1, close)) });+ }+ return scopes;+}++// A named function definition: `function name(…) {…}`, or a `const|let|var name =` whose value is an+// arrow, a function expression, or one wrapped in memo/forwardRef. A value that is a CALL of something+// else (`useCallback(…)`, `useMemo(…)`) is not a definition of the name.+function namedFunctions(code) {+ const out = [];+ for (const m of code.matchAll(/\bfunction\b\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>()]*>)?\s*\(/g)) {+ const before = prevSignificant(code, m.index);+ // `const f = function g() {}` is the const's definition, read below.+ if (code[before] === '=' || (code[before] === '(' && /\b(?:memo|forwardRef)\s*$/.test(code.slice(0, before)))) continue;+ const open = m.index + m[0].length - 1;+ const close = matchingClose(code, open);+ const at = close < 0 ? -1 : afterReturnType(code, close + 1);+ if (at < 0 || code[at] !== '{') continue;+ out.push({ name: m[1], start: m.index, body: bodyExtent(code, at), params: patternNames(code.slice(open + 1, close)) });+ }+ const DECL = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+?)?=(?!=|>)\s*/g;+ for (const m of code.matchAll(DECL)) {+ let i = m.index + m[0].length;+ const rest = code.slice(i);+ const wrapper = /^(?:React\s*\.\s*)?(?:memo|forwardRef)\s*(?:<[^>()]*>)?\s*\(\s*/.exec(rest);+ if (wrapper) i += wrapper[0].length;+ const value = code.slice(i);+ const asyncWord = /^async\s+/.exec(value);+ const start = i + (asyncWord ? asyncWord[0].length : 0);+ const head = code.slice(start);+ let params = null;+ let arrowAt = -1;+ if (/^function\b/.test(head)) {+ const open = code.indexOf('(', start);+ const close = matchingClose(code, open);+ const at = close < 0 ? -1 : afterReturnType(code, close + 1);+ if (at < 0 || code[at] !== '{') continue;+ out.push({ name: m[1], start: m.index, body: bodyExtent(code, at), params: patternNames(code.slice(open + 1, close)) });+ continue;+ }+ const generic = /^<[^>()]*>\s*/.exec(head);+ const paramsAt = start + (generic ? generic[0].length : 0);+ if (code[paramsAt] === '(') {+ const close = matchingClose(code, paramsAt);+ if (close < 0) continue;+ const at = afterReturnType(code, close + 1);+ if (at < 0 || code[at] !== '=' || code[at + 1] !== '>') continue;+ params = code.slice(paramsAt + 1, close);+ arrowAt = at;+ } else {+ const single = /^([A-Za-z_$][\w$]*)\s*=>/.exec(code.slice(paramsAt));+ if (!single) continue;+ params = single[1];+ arrowAt = paramsAt + single[0].length - 2;+ }+ let body = arrowAt + 2;+ while (body < code.length && /\s/.test(code[body])) body += 1;+ out.push({ name: m[1], start: m.index, body: bodyExtent(code, body), params: patternNames(params) });+ }+ return out.sort((a, b) => a.start - b.start);+}++// Every binding the page declares, with where: const/let/var names (destructured too) and function+// declarations, as { name, at } over the code view. A binding belongs to the innermost function scope+// around `at` (innermostScope); one in no function scope belongs to the module.+function declarations(code) {+ const out = [];+ for (const m of code.matchAll(/\b(?:const|let|var)\s+(\[[^\]=]*\]|\{[^}=]*\}|[A-Za-z_$][\w$]*)/g)) {+ for (const name of patternNames(m[1])) out.push({ name, at: m.index });+ }+ for (const m of code.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)/g)) out.push({ name: m[1], at: m.index });+ return out;+}++function innermostScope(scopes, at) {+ let best = null;+ for (const scope of scopes) {+ if (scope.start <= at && at < scope.end && (!best || scope.end - scope.start < best.end - best.start)) best = scope;+ }+ return best;+}++// Rule 3 of references/rules.md: "All code (components, utilities) in one file; each as separate+// top-level function (no nesting)". A function defined inside another one is reported when it is+// - a COMPONENT: its name is PascalCase (React's convention for a component, which also remounts —+// and loses its state — on every render of the one it is nested in); or+// - a UTILITY: it reads nothing the functions around it declare (their parameters, state, setters,+// props), so nothing keeps it from being top level.+// A nested function that does read their bindings is a handler or an effect's loader — the rules'+// own samples write those inside the component — and is not reported. Unnamed callbacks (`onClick={() => …}`,+// `useEffect(() => …)`, `rows.map((r) => …)`) are not definitions and are not reported either.+// What a function reads from around it is decided by scope: a binding counts when it is declared directly+// in an enclosing function (its innermost function scope is one of them) or is one of their parameters —+// never a binding declared inside the function itself or inside a sibling — and the function's own+// parameters and locals shadow an enclosing name of the same spelling, so+// const percent = (n) => { const rounded = Math.round(n * 100); return rounded; };+// reads nothing from the component, whatever the component itself declares.+// Returns a list of problems, empty when every component and utility is top level.+function nestedDefinitionProblems(content) {+ const { code } = sourceView(content);+ const scopes = functionScopes(code);+ const declared = declarations(code);+ const homes = declared.map((d) => ({ ...d, home: innermostScope(scopes, d.at) }));+ const problems = [];+ for (const fn of namedFunctions(code)) {+ const around = scopes.filter((s) => s.start < fn.start && fn.start < s.end && !(s.start === fn.body.start && s.end === fn.body.end));+ if (!around.length) continue;+ if (/^[A-Z]/.test(fn.name)) {+ problems.push(`component ${fn.name} is defined inside another function`);+ continue;+ }+ const outer = new Set();+ for (const scope of around) for (const name of scope.params) outer.add(name);+ for (const d of homes) if (d.home && around.includes(d.home)) outer.add(d.name);+ outer.delete(fn.name);+ const own = new Set(fn.params);+ const fnScope = innermostScope(scopes, fn.body.start);+ for (const d of homes) if (d.home && d.home === fnScope) own.add(d.name);+ for (const name of own) outer.delete(name);+ const body = code.slice(fn.body.start, fn.body.end);+ const closes = [...outer].some((name) => new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(body));+ if (!closes) problems.push(`utility ${fn.name} is defined inside another function but reads nothing from it`);+ }+ return problems;+}++module.exports = {+ sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, patternNames,+ namedFunctions, nestedDefinitionProblems, withoutComments,+};diff --git a/evals/model-apps/genpage/lib/workflow-evidence.js b/evals/model-apps/genpage/lib/workflow-evidence.jsindex 0e228181e..5d4d5f7c5 100644--- a/evals/model-apps/genpage/lib/workflow-evidence.js+++ b/evals/model-apps/genpage/lib/workflow-evidence.js@@ -121,6 +121,14 @@ function unassociatedCallProblems(fixture) {.map(([key]) => `${key}: logged command has no associated result event`);}+// The entity-builder's one-line identity warning in genpage-entity-creation-log.md: a line that says it is a+// warning and names both identities check-auth.js reported, e.g. under the log's `## Environment`:+// - Warning: az ([email protected]) and pac ([email protected]) use different identities; WhoAmI passed, so provisioning proceeds.+function identityWarningLogged(log, result) {+ const names = [result.azUser, result.pacUser].filter((name) => typeof name === 'string' && name);+ return String(log || '').split(/\r?\n/).some((line) => /\bwarn/i.test(line) && names.every((name) => line.includes(name)));+}+function authGateProblems(fixture, { required = false } = {}) {const calls = workflowCalls(fixture);const gates = calls.filter((call) => isAuth(call.command));@@ -155,8 +163,16 @@ function authGateProblems(fixture, { required = false } = {}) {|| (plannedEnv && normalizedEnv(plannedEnv) !== normalizedEnv(result.envUrl)))) {problems.push('successful auth gate belongs to a different command/plan environment');}- if (strict && result.identitiesMatch === false && call.userMessage !== result.message) {- problems.push('warning-only identity mismatch was not surfaced verbatim');+ if (strict && result.identitiesMatch === false) {+ // A working sign-in whose az and pac identities differ is a warning, not a blocker. SKILL.md Phase 2a+ // has the orchestrator proceed and show the result's `message` to the user; the entity-builder re-probes+ // the same way but is headless, so agents/genpage-entity-builder.md Step 2 has it log a one-line warning+ // in its transaction log instead. Each is graded where its spec says the warning goes.+ if (call.by === 'genpage-entity-builder') {+ if (!identityWarningLogged(fixture.entityCreationLog, result)) problems.push('the entity-builder did not log its identity-mismatch warning in genpage-entity-creation-log.md');+ } else if (call.userMessage !== result.message) {+ problems.push('warning-only identity mismatch was not surfaced verbatim');+ }}timeoutAttempts = 0;} else {@@ -253,6 +269,47 @@ function discoveryProblems(fixture, { required = false, needsBinding = false } =return problems;}+// edit-flow.md Edit Phase 1b: "0 pages: Tell the user 'This app has no generative pages to edit. Did you mean to+// create a new page?' and stop the edit flow." The page listing (scripts/genpage.js list) answers+// { "ok": true, "scope": "app", "appId": "…", "layer": "published", "count": 0, "pages": [] }+// and an entry whose page is gone (`"exists": false`) is no page to offer, so a listing of only those is empty+// too. A failed listing (`"ok": false`) is never "no pages" (edit-flow.md: "a failed read is never 'no pages'").+function isEmptyPageListing(result) {+ return Boolean(result) && result.ok === true && Array.isArray(result.pages) && !result.pages.some((page) => page && page.exists !== false);+}++// What the run must show once a listing came back empty: the user was told (an empty listing's `userMessage`+// in a current trace, the log's prose in an older one), nothing was downloaded, planned, generated or written+// after it, and the log says the flow stopped. The flow stops at the FIRST empty listing, so everything after+// it is graded against that stop: another read later cannot take back what the run did in between. Returns+// the problems, empty when that stop is shown.+function emptyPageListingProblems(fixture) {+ // Loaded here, not at the top: expectation-evidence.js builds on this module, so a top-level require would+ // hand it a half-initialized copy of these exports.+ const { GENPAGE_LIST, GENPAGE_DOWNLOAD } = require('./expectation-evidence.js');+ const calls = workflowCalls(fixture);+ const listings = calls.flatMap((call, at) => (GENPAGE_LIST.test(call.command) ? [{ call, at }] : []));+ if (!listings.length) return ['genpage.js list was not run, so no page listing came back empty'];+ const stop = listings.find(({ call }) => isEmptyPageListing(resultObject(call)));+ if (!stop) {+ const last = resultObject(listings.at(-1).call);+ return [last?.ok === true && Array.isArray(last.pages) ? 'the page listing returned pages to edit' : 'the page listing did not succeed, and a failed listing is never "no pages"'];+ }+ const problems = [];+ const toldNoPages = (text) => typeof text === 'string' && /\bno\b[^.\n]*\bpages?\b/i.test(text);+ // Told at an empty listing: the stop itself, or a read after it.+ const told = currentContract(fixture)+ ? listings.some(({ call }) => isEmptyPageListing(resultObject(call)) && toldNoPages(call.userMessage))+ : toldNoPages(fixture.workflowLog);+ if (!told) problems.push('the user was not told the app has no pages to edit');+ if (calls.slice(stop.at + 1).some((call) => GENPAGE_DOWNLOAD.test(call.command) || /\bgenpage-edit-planner\b/.test(call.command)+ || isGeneration(call.command) || isMutation(call))) {+ problems.push('the run went on to download, plan, edit or upload after the app listed no pages');+ }+ if (!/\bstop(?:s|ped)?\b|\bhalt(?:s|ed)?\b/i.test(fixture.workflowLog || '')) problems.push('the workflow does not record that the edit flow stopped');+ return problems;+}+function refusalProblems(fixture) {if (fixture.manifest?.expectedOutcome !== 'refused') return ['fixture does not declare an expected refusal'];const stage = fixture.manifest.refusal?.stage;@@ -267,6 +324,10 @@ function refusalProblems(fixture) {const { customApiGateProblems } = require('./custom-api-contract.js');return problems.concat(customApiGateProblems(fixture));}+ // A run refused at Edit Phase 1b because the chosen app has no generative pages: its "gate" is the empty+ // page listing, and an auth call it made on the way (the edit flow captures its environment with+ // check-auth.js) must still be well formed.+ if (stage === 'edit-pages') return problems.concat(emptyPageListingProblems(fixture), authGateProblems(fixture));const predicate = stage === 'auth' ? isAuth : stage === 'discovery' ? isDiscovery : null;if (!predicate) return [...problems, `unsupported refusal stage: ${stage}`];const gate = calls.filter((call) => predicate(call.command)).at(-1);@@ -276,6 +337,6 @@ function refusalProblems(fixture) {module.exports = {currentContract, isObject, isUpload, isAuth, isDiscovery, isMutation, isGeneration,- resultObject, workflowCalls, authGateProblems, discoveryProblems, refusalProblems,- unassociatedCallProblems,+ resultObject, workflowCalls, authGateProblems, discoveryProblems, refusalProblems, emptyPageListingProblems,+ isEmptyPageListing, unassociatedCallProblems,};diff --git a/evals/model-apps/genpage/tests/page-expectations.test.js b/evals/model-apps/genpage/tests/page-expectations.test.jsnew file mode 100644index 000000000..e59b9bbf4--- /dev/null+++ b/evals/model-apps/genpage/tests/page-expectations.test.js@@ -0,0 +1,367 @@+'use strict';++// Unit tests for the Phase 5 page checks graded from how a generated page is BUILT+// (lib/page-checks.js, lib/tsx-structure.js and lib/column-contract.js, registered in+// lib/assertions-layer-2.js): eval 4's review summary and field labels (its step navigation is recorded as+// unscored instead, and a test pins why), eval 5's top-level functions, eval 12's search box beside a filter+// toolbar, eval 13's translated text, eval 15's choice names, and the column names evals 1 and 7 verify+// against RuntimeTypes.ts.+//+// Each check PASSES on the committed fixture it grades, FAILS on an in-memory mutation of that page+// that introduces exactly the regression it exists to catch, and SKIPs only where its evidence is not+// part of a page. Mutations go through `edit`, which asserts the text it replaces is really there, so a+// fixture change cannot silently turn a failing case into a vacuous one. Small inline pages pin the+// equivalent forms a check accepts (a condition read through a declaration, a Fluent Field's label).++const { test } = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');++const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');+const { loadFixtures } = require('../lib/fixture-loader.js');+const { nestedDefinitionProblems, jsxElements, jsxTextRuns, patternNames } = require('../lib/tsx-structure.js');+const layer1 = require('../run-layer-1.js');+const layer2 = require('../run-layer-2.js');+const BASELINE = require('../../tests/eval-coverage-baseline.json');++const FIXTURES = loadFixtures(path.join(__dirname, '..', 'fixtures'));++function committed(dirName) {+ const fixture = FIXTURES.find((f) => f.dirName === dirName);+ assert.ok(fixture, `committed fixture ${dirName} exists`);+ return fixture;+}++function edit(text, from, to) {+ // A Windows checkout may hold a fixture with CRLF line ends; multi-line edits follow the file's.+ if (typeof text === 'string' && text.includes('\r\n')) [from, to] = [from, to].map((s) => s.replace(/\r?\n/g, '\r\n'));+ assert.ok(typeof text === 'string' && text.includes(from), `fixture text contains ${JSON.stringify(from)}`);+ return text.split(from).join(to);+}++// A copy of a committed fixture whose page `name` has each [from, to] edit applied.+function withPage(dirName, name, ...edits) {+ const base = committed(dirName);+ assert.ok(base.files.some((f) => f.name === name), `${dirName} has ${name}`);+ return {+ ...base,+ files: base.files.map((f) => (f.name === name ? { ...f, content: edits.reduce((text, [from, to]) => edit(text, from, to), f.content) } : f)),+ };+}++function inline(content, extra = {}) {+ return { files: [{ path: '/fake/page.tsx', name: 'page.tsx', content }], ...extra };+}++function grade(text, fixture) {+ const check = PHASE5_EXPECTATIONS.get(text);+ assert.ok(check, `a check is registered for: ${text}`);+ return check({ files: fixture.files, fixture, eval: { id: fixture.id } });+}++function assertPass(result) { assert.equal(result.status, 'pass', result.reason); }+function assertFail(result, reason) {+ assert.equal(result.status, 'fail', `expected a failure, got ${result.status}: ${result.reason}`);+ assert.match(result.reason, reason);+}+function assertSkip(result, reason) {+ assert.equal(result.status, 'skip', `expected a skip, got ${result.status}: ${result.reason}`);+ assert.match(result.reason, reason);+}++// --- The structure reader ------------------------------------------------------------------------++test('tsx structure: elements, attributes and JSX text are read from code, never from strings or comments', () => {+ const page = `// <Input placeholder="in a comment" />+const label = '<Input aria-label="in a string" />';+const C = () => <Field label="First name"><Input aria-label="First" value={form.x} onChange={(_, d) => set(d.value > 1)} /></Field>;+const D = () => <Text>Hello {name} world & more</Text>;+const n = useState<Row>(null);`;+ const inputs = jsxElements(page, /^Input$/);+ assert.equal(inputs.length, 1);+ assert.equal(inputs[0].attrs.get('aria-label').value, 'First');+ assert.equal(inputs[0].attrs.get('value').value, 'form.x');+ assert.equal(inputs[0].selfClosing, true);+ const field = jsxElements(page, /^Field$/)[0];+ assert.ok(field.childrenStart <= inputs[0].start && inputs[0].start < field.childrenEnd);+ assert.deepEqual(jsxElements(page, /^Row$/), [], 'a type argument is not an element');+ assert.deepEqual(jsxTextRuns(page).map((r) => r.text.trim()), ['Hello', 'world more']);+ assert.deepEqual(patternNames('[{ tasks, loading, error }, setData]'), ['tasks', 'loading', 'error', 'setData']);+ assert.deepEqual(patternNames('(e: React.DragEvent<HTMLDivElement>, id: string)'), ['e', 'id']);+ assert.deepEqual(patternNames('{ dataApi, pageInput: input = null }'), ['dataApi', 'input']);+ assert.deepEqual(patternNames('{ item, dragging }: TaskCardProps'), ['item', 'dragging']);+});++// --- Eval 4: the wizard ----------------------------------------------------------------------------++const E4 = '4-case-wizard';+const WIZARD = 'Phase 5 (Page Builder): Generated code includes step state management (current step tracking) and Next/Back navigation';+const REVIEW = 'Phase 5 (Page Builder): Step 3 (review) shows a summary of entered data before submission';+const LABELS = 'Phase 5 (Page Builder): All form fields have aria-labels or aria-labelledby for accessibility';++// The step navigation is recorded as unscored (tests/eval-coverage-baseline.json): whether Next and Back move+// the step is the value the step's setter RECEIVES, and a syntactic scan of a handler cannot prove that —+// `setStep((s) => { const next = s + 1; return s; })` computes the next step and returns the old one, so the+// wizard never advances, though the increment is right there in the handler. Grading it needs data-flow+// analysis, so no check is registered in either runner rather than one that passes a page like that.+test('eval 4: step state and Next/Back navigation stay unscored, because what the setter receives needs data-flow analysis', () => {+ assert.equal(PHASE5_EXPECTATIONS.has(WIZARD), false, 'no Layer 2 check is registered for the step navigation');+ assert.equal(layer2.getExpectationCheck(WIZARD), undefined, 'the Layer 2 runner finds no check for it');+ assert.equal(layer1.getExpectationCheck(WIZARD), undefined, 'the Layer 1 runner finds no check for it');+ const entry = BASELINE.genpage.unscored.find((e) => e.text === WIZARD);+ assert.ok(entry, 'the coverage baseline records the expectation as unscored');+ assert.equal(entry.eval, 4);+ assert.equal(entry.status, 'deferred');+ assert.match(entry.reason, /data-flow analysis/);+});++test('eval 4: the review step shows every entered field and gates the submit', () => {+ assertPass(grade(REVIEW, committed(E4)));+ assertFail(grade(REVIEW, withPage(E4, 'page.tsx', ['<Text weight="semibold">{form.contactEmail}</Text>', '<Text weight="semibold">—</Text>'])), /does not show form\.contactEmail/);+ assertFail(grade(REVIEW, withPage(E4, 'page.tsx', ['{step === 3 && (', '{step === 9 && false && ('])), /does not show form\./);+ const ungated = `const GeneratedComponent = () => {+ const [step, setStep] = useState(1);+ const [title, setTitle] = useState('');+ return <div>+ {step === 1 && (<Input aria-label="Title" value={title} onChange={(_, d) => setTitle(d.value)} />)}+ {step === 2 && (<Text>{title}</Text>)}+ <Button onClick={() => dataApi.createRow('incident', { title })}>Submit</Button>+ </div>;+};`;+ assertFail(grade(REVIEW, inline(ungated)), /submit button "Submit" can be pressed when step is 1, not only on the review step/);+ assertPass(grade(REVIEW, inline(ungated.replace('<Button onClick', '{step === 2 && <Button onClick').replace('Submit</Button>', 'Submit</Button>}'))));+});++test('eval 4: every form field is labelled, a Fluent Field label included', () => {+ assertPass(grade(LABELS, committed(E4)));+ // The Field around a control labels it (Field wires aria-labelledby), so dropping only the control's own aria-label keeps it labelled ...+ assertPass(grade(LABELS, withPage(E4, 'page.tsx', ['<Input\n aria-label="Title"', '<Input'])));+ // ... and dropping both leaves the Title input with no accessible name.+ assertFail(grade(LABELS, withPage(E4, 'page.tsx', ['<Field label="Title">\n <Input\n aria-label="Title"', '<Field>\n <Input'])), /<Input> has no aria-label, aria-labelledby or label/);+ assertPass(grade(LABELS, inline('const P = () => <div><Label htmlFor="due">Due</Label><Input id="due" /><Checkbox label="Urgent" /><input type="hidden" /></div>;')));+ assertSkip(grade(LABELS, inline('const P = () => <Text>No fields</Text>;')), /no form fields/);+});++// --- Eval 5: top-level functions --------------------------------------------------------------------++const E5 = '5-kanban-task-board';+const TOP_LEVEL = 'Phase 5 (Page Builder): All components and utilities are separate top-level functions (no nested function definitions)';++test('eval 5: components and utilities are top level; handlers that close over state are not reported', () => {+ assertPass(grade(TOP_LEVEL, committed(E5)));+ assertFail(grade(TOP_LEVEL, withPage(E5, 'task-board.tsx', [' const handleDragEnd = () => {', ' const Spacer = () => <div className={styles.root} />;\n const handleDragEnd = () => {'])), /component Spacer is defined inside another function/);+ assertFail(grade(TOP_LEVEL, withPage(E5, 'task-board.tsx', [' const handleDragEnd = () => {', ' const percent = (n: number) => Math.round(n * 100);\n const handleDragEnd = () => {'])), /utility percent is defined inside another function but reads nothing from it/);+ assertFail(grade(TOP_LEVEL, withPage(E5, 'task-board.tsx', [' const handleDragEnd = () => {', ' function label(t: task) { return t.subject; }\n const handleDragEnd = () => {'])), /utility label is defined inside another function/);+ // An effect's loader reads the component's state and setters: a closure, not a utility.+ assert.deepEqual(nestedDefinitionProblems(`const GeneratedComponent = (props) => {+ const { dataApi } = props;+ const [rows, setRows] = useState([]);+ useEffect(() => { async function load() { setRows((await dataApi.queryTable('task', {})).rows); } load(); }, []);+ return <div>{rows.length}</div>;+};`), []);+});++// --- Eval 12: the revised plan -----------------------------------------------------------------------++const E12 = '12-account-plan-revision';+const REVISED = 'Phase 5 (Page Builder): Generated code implements the revised plan (includes BOTH filter toolbar AND search box)';++test('eval 12: the page has the search box the revision added AND the filter toolbar', () => {+ assertPass(grade(REVISED, committed(E12)));+ assertFail(grade(REVISED, withPage(E12, 'account-list.tsx', ["onChange={(_, data) => setSearch(data.value ?? '')}", ''])), /no search box/);+ assertFail(grade(REVISED, withPage(E12, 'account-list.tsx',+ ['<Toolbar className={styles.toolbar} aria-label="Account filters">', '<div className={styles.toolbar} aria-label="Account filters">'],+ ['</Toolbar>', '</div>'])), /no filter toolbar/);+ assertPass(grade(REVISED, inline('const P = () => <div><Input type="search" onChange={(_, d) => setQ(d.value)} /><div role="toolbar"><Dropdown onOptionSelect={pick} /></div></div>;')));+});++// --- Eval 13: translated text -------------------------------------------------------------------------++const E13 = '13-contact-localization';+const TRANSLATED = 'Phase 5 (Page Builder): All user-visible text goes through a translate() helper — no hardcoded display strings in JSX';++test('eval 13: shown text goes through the translate helper', () => {+ assertPass(grade(TRANSLATED, committed(E13)));+ assertFail(grade(TRANSLATED, withPage(E13, 'page.tsx', ["<Text>{t('empty')}</Text>", '<Text>No contacts.</Text>'])), /hardcoded JSX text "No contacts\."/);+ assertFail(grade(TRANSLATED, withPage(E13, 'page.tsx', ["<Spinner label={t('title')} />", '<Spinner label="Loading" />'])), /hardcoded label "Loading" on <Spinner>/);+ assertFail(grade(TRANSLATED, withPage(E13, 'page.tsx', ["<Text>{t('empty')}</Text>", "<Text>{'No contacts.'}</Text>"])), /hardcoded JSX string/);+ assertFail(grade(TRANSLATED, inline('const P = () => <Text>{label}</Text>;')), /no translate\(\) helper/);+ assertPass(grade(TRANSLATED, inline("const translate = (k: string) => k;\nconst P = () => <Text>{translate('title')} ({count}) </Text>;")));+});++// --- Eval 15: choice names ------------------------------------------------------------------------------++const E15 = '15-support-tickets-real';+const CHOICES = 'Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)';++test('eval 15: every choice value is named after the RuntimeTypes.ts member it is', () => {+ assertPass(grade(CHOICES, committed(E15)));+ assertFail(grade(CHOICES, withPage(E15, 'support-tickets.tsx', ['if (status === STATUS_RESOLVED || status === STATUS_CLOSED) return false;', 'if (status === 100000002 || status === STATUS_CLOSED) return false;'])), /magic number 100000002/);+ assertFail(grade(CHOICES, withPage(E15, 'support-tickets.tsx', ['const PRIORITY_HIGH = 100000002;', 'const PRIORITY_HIGH = 100000001;'])), /PRIORITY_HIGH = 100000001, but RuntimeTypes\.ts gives High = 100000002/);+ assertFail(grade(CHOICES, withPage(E15, 'support-tickets.tsx', ['const PRIORITY_LOW = 100000000;', 'const PRIORITY_LOW = 100000009;'])), /100000009 is not a choice value RuntimeTypes\.ts declares/);+ assertSkip(grade(CHOICES, { ...committed(E15), runtimeTypes: null }), /requires RuntimeTypes\.ts fixture/);+ const runtimeTypes = committed(E15).runtimeTypes;+ assertPass(grade(CHOICES, inline("const OPTIONS = [{ value: 100000000, label: 'Low' }, { value: 100000003, label: 'Critical' }];", { runtimeTypes })));+ assertFail(grade(CHOICES, inline("const OPTIONS = [{ value: 100000000, label: 'Urgent' }];", { runtimeTypes })), /magic number 100000000/);+ assertSkip(grade(CHOICES, inline('const P = () => <Text>{row.cr_name}</Text>;', { runtimeTypes })), /compares no choice value/);+});++// --- Evals 1 and 7: column names verified from RuntimeTypes.ts --------------------------------------------++const E1 = '1-account-cards-verified-columns';+const COLUMNS_5B = 'Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names';+const COLUMNS_7 = 'Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts';++test('evals 1 and 7: every column a dataApi call names is one RuntimeTypes.ts declares', () => {+ assertPass(grade(COLUMNS_5B, committed(E1)));+ assertFail(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["select: ['accountid', 'name', 'websiteurl',", "select: ['accountid', 'name', 'website',"])), /queryTable\('account'\) select names website, which RuntimeTypes\.ts does not declare on account/);+ assertFail(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["orderBy: 'name asc'", "orderBy: 'accountname asc'"])), /orderBy names accountname/);+ assertFail(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["dataApi.queryTable('account', {", "dataApi.queryTable('accounts', {"])), /reads table accounts, which RuntimeTypes\.ts does not register/);+ // Columns every user-owned table has, which the type generator does not write, are no guesses.+ assertPass(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["orderBy: 'name asc'", "orderBy: 'createdon desc'"])));+ // The historical eval-1 and eval-7 traces kept no RuntimeTypes.ts: nothing to verify against.+ assertSkip(grade(COLUMNS_5B, committed('1-account-card-gallery')), /column-name verification requires RuntimeTypes\.ts fixture/);+ assertSkip(grade(COLUMNS_7, committed('7-job-candidates-new-entities')), /column-name verification requires RuntimeTypes\.ts fixture/);+});++test('eval 7: the job-candidates run kept the RuntimeTypes.ts it generated, so its page\'s columns are graded', () => {+ const E7 = '7-job-candidates-verified-columns';+ const PAGE = 'job-candidates.tsx';+ assertPass(grade(COLUMNS_7, committed(E7)));+ assertFail(grade(COLUMNS_7, withPage(E7, PAGE, ["'cr_interviewscore', 'cr_recruiter',", "'cr_score', 'cr_recruiter',"])), /queryTable\('cr_candidate'\) select names cr_score, which RuntimeTypes\.ts does not declare on cr_candidate/);+ assertFail(grade(COLUMNS_7, withPage(E7, PAGE, ["'_cr_jobrequisition_value'],", "'_cr_requisition_value'],"])), /select names _cr_requisition_value/);+ assertFail(grade(COLUMNS_7, withPage(E7, PAGE, ["orderBy: 'cr_name asc',", "orderBy: 'cr_fullname asc',"])), /orderBy names cr_fullname/);+ assertFail(grade(COLUMNS_7, withPage(E7, PAGE, ["dataApi.queryTable('cr_candidate', {", "dataApi.queryTable('cr_candidates', {"])), /reads table cr_candidates, which RuntimeTypes\.ts does not register/);+});++test('evals 1 and 7: payload keys, annotations and named options are read; another table\'s expand is not', () => {+ const runtimeTypes = committed(E1).runtimeTypes;+ const page = (body) => inline(`const LIST = { select: SELECT, orderBy: 'name asc' };\nconst SELECT = ['accountid', 'name'] as const;\n${body}`, { runtimeTypes });+ assertPass(grade(COLUMNS_7, page("dataApi.queryTable('account', LIST);")));+ assertFail(grade(COLUMNS_7, page("dataApi.queryTable('account', { ...LIST, filter: \"statecode eq 0 and contains(nickname, 'x')\" });")), /filter names nickname/);+ assertPass(grade(COLUMNS_7, page("dataApi.queryTable('account', { select: ['name'], expand: { _primarycontactid_value: { select: ['fullname'] } } });")));+ assertFail(grade(COLUMNS_7, page("dataApi.createRow('account', { name: 'A', creditlimit: 5, '[email protected]': '/accounts(1)' });")), /createRow\('account'\) names creditlimit/);+ assertPass(grade(COLUMNS_7, page("dataApi.updateRow('account', id, { telephone1: phone } as WritableTableRow<account>);")));+ assertPass(grade(COLUMNS_7, page("const label = row['_primarycontactid_value@OData.Community.Display.V1.FormattedValue'];")));+ assertFail(grade(COLUMNS_7, page("const label = row['_parentcustomerid_value@OData.Community.Display.V1.FormattedValue'];")), /FormattedValue of _parentcustomerid_value/);+ assertSkip(grade(COLUMNS_7, inline('const P = () => <Text>static</Text>;', { runtimeTypes })), /name no Dataverse column/);+});++// --- Graded holes the first version let through -------------------------------------------------------------+// Each test below failed on the first version of these checks: a page that breaks the expectation was graded+// PASS, or a correct page FAIL. The checks now read the evidence the expectation is about.++test('columns: a column quoted in a comment is not a column the page names', () => {+ assertPass(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["select: ['accountid', 'name',", "select: ['accountid', /* formerly 'retired_name' */ 'name',"])));+ assertPass(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["select: ['accountid', 'name',", "select: [\n 'accountid', // was 'legacy_id'\n 'name',"])));+ assertPass(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["orderBy: 'name asc',", "orderBy: /* was 'createdate desc' */ 'name asc',"])));+ // The real names around the comments are still read.+ assertFail(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["select: ['accountid', 'name', 'websiteurl',", "select: ['accountid', /* 'name' */ 'name', 'website',"])), /select names website, which RuntimeTypes\.ts does not declare/);+ assertFail(grade(COLUMNS_5B, withPage(E1, 'account-gallery.tsx', ["orderBy: 'name asc',", "orderBy: /* sort */ 'nickname asc',"])), /orderBy names nickname/);+ // A select list the call names through a constant is read from the constant's declaration, without its comments.+ const declared = (list) => withPage(E1, 'account-gallery.tsx',+ ["select: ['accountid', 'name', 'websiteurl', 'emailaddress1', 'telephone1'],", 'select: ACCOUNT_COLUMNS,'],+ ["const CACHE_KEY = '__ppAccountsGallery_accountCache';", `const ACCOUNT_COLUMNS = ${list};\nconst CACHE_KEY = '__ppAccountsGallery_accountCache';`]);+ assertPass(grade(COLUMNS_5B, declared("['accountid', /* was 'retired_name' */ 'name', 'websiteurl', 'emailaddress1', 'telephone1']")));+ assertFail(grade(COLUMNS_5B, declared("['accountid', /* 'name' */ 'website']")), /select names website, which RuntimeTypes\.ts does not declare/);+});++test('eval 5: a nested utility\'s own locals are not bindings it closes over', () => {+ const insert = (helper) => withPage(E5, 'task-board.tsx', [' const handleDragEnd = () => {', `${helper}\n const handleDragEnd = () => {`]);+ assertFail(grade(TOP_LEVEL, insert(' const percent = (n: number) => {\n const rounded = Math.round(n * 100);\n return rounded;\n };')), /utility percent is defined inside another function but reads nothing from it/);+ // A parameter or a local that shadows the component's own names (tasks, hoverCol) reads nothing from it either.+ assertFail(grade(TOP_LEVEL, insert(' const share = (tasks: number) => {\n const hoverCol = tasks * 100;\n return hoverCol;\n };')), /utility share is defined inside another function/);+ // A handler with locals of its own that sets the component's state still closes over it.+ assertPass(grade(TOP_LEVEL, insert(' const clearHover = () => {\n const none = null;\n setHoverCol(none);\n };')));+ // A name a SIBLING declares is not one the component declares: `percent` reads the module's `scale`.+ const sibling = withPage(E5, 'task-board.tsx',+ ['// ---- Status constants', 'const scale = 100;\n\n// ---- Status constants'],+ [' const handleDragEnd = () => {', ' const handleScale = () => {\n const scale = 2;\n setHoverCol(null);\n return scale;\n };\n const percent = (n: number) => Math.round(n * scale);\n const handleDragEnd = () => {']);+ assertFail(grade(TOP_LEVEL, sibling), /utility percent is defined inside another function but reads nothing from it/);+});++// A two-step page whose review step (step 2) shows the title step 1 enters, with `submit` placed as given.+const twoStepPage = (submit) => inline(`const GeneratedComponent = () => {+ const [step, setStep] = useState(1);+ const [title, setTitle] = useState('');+ return <div>+ {step === 1 && (<Input aria-label="Title" value={title} onChange={(_, d) => setTitle(d.value)} />)}+ {step === 2 && (<Text>{title}</Text>)}+ ${submit}+ </div>;+};`);+const SUBMIT = "<Button onClick={() => dataApi.createRow('incident', { title })}>Submit</Button>";++test('eval 4: every submit is reachable only on the review step', () => {+ assertFail(grade(REVIEW, withPage(E4, 'page.tsx', ['{step < 3 ? (', '{step < 1 ? ('])), /submit button .*not only on the review step/);+ assertFail(grade(REVIEW, withPage(E4, 'page.tsx', [' <div className={styles.nav}>', ' <Button onClick={handleSubmit}>Submit now</Button>\n <div className={styles.nav}>'])), /submit button .*not only on the review step/);+ const page = twoStepPage;+ // Disabled on every step but the review is gated too; so is the false side of a boundary that ends at it.+ assertPass(grade(REVIEW, page(SUBMIT.replace('<Button ', '<Button disabled={step !== 2} '))));+ assertPass(grade(REVIEW, page(`{step < 2 ? <Button onClick={() => setStep(step + 1)}>Next</Button> : ${SUBMIT}}`)));+ // With steps 1 and 2, `step !== 1` IS the review step; `step !== 2` is the first step.+ assertPass(grade(REVIEW, page(`{step !== 1 && ${SUBMIT}}`)));+ assertFail(grade(REVIEW, page(`{step !== 2 && ${SUBMIT}}`)), /can be pressed when step is 1, not only on the review step/);+ assertFail(grade(REVIEW, page(`{ready ? ${SUBMIT} : null}`)), /not only on the review step/);+ // A condition read through a declaration counts like the comparison it holds.+ const aliased = inline(page(`{isReview && ${SUBMIT}}`).files[0].content.replace('const [title', 'const isReview = step === 2;\n const [title'));+ assertPass(grade(REVIEW, aliased));+});++// `a ?? b` falls back to b only when a is null or undefined, so it is not `||`: `false ?? (step !== 3)` is+// false, and the button it disables can be pressed. Literals are read for what they are.+test('eval 4: `??` and literal conditions decide whether a submit can be pressed the way JavaScript evaluates them', () => {+ const extra = (disabled) => withPage(E4, 'page.tsx', [' <div className={styles.nav}>', ` <Button onClick={handleSubmit} disabled={${disabled}}>Submit now</Button>\n <div className={styles.nav}>`]);+ assertPass(grade(REVIEW, extra('submitting || (step !== 3)')));+ assertFail(grade(REVIEW, extra('submitting ?? (step !== 3)')), /submit button "Submit now" can be pressed when step is 1 or 2, not only on the review step/);+ // A nullish left side does fall back, and a literal true disables for good ...+ for (const disabled of ['undefined ?? (step !== 3)', 'null ?? (step !== 3)', 'true']) assertPass(grade(REVIEW, extra(disabled)));+ // ... while false, null and undefined disable nothing.+ for (const disabled of ['false', 'null', 'undefined']) assertFail(grade(REVIEW, extra(disabled)), /submit button "Submit now" can be pressed when step is 1 or 2/);+ // The only submit, disabled for good, leaves nothing to press on the review step.+ assertFail(grade(REVIEW, twoStepPage(`{step === 2 && ${SUBMIT.replace('<Button ', '<Button disabled={true} ')}}`)), /no submit button can be pressed on the review step/);+ // In JSX, `x ?? <Submit/>` shows the fallback wherever x may be nullish; inside a step's branch it stays there.+ assertFail(grade(REVIEW, twoStepPage(`{pending ?? ${SUBMIT}}`)), /can be pressed when step is 1, not only on the review step/);+ assertPass(grade(REVIEW, twoStepPage(`{step === 2 && (pending ?? ${SUBMIT})}`)));+ // A comparison is never nullish, so the fallback after it is never shown, on any step.+ assertFail(grade(REVIEW, twoStepPage(`{(step !== 2) ?? ${SUBMIT}}`)), /no submit button can be pressed on the review step/);+});++test('eval 4: an empty label is no label', () => {+ const TITLE = '<Field label="Title">\n <Input\n aria-label="Title"';+ assertFail(grade(LABELS, withPage(E4, 'page.tsx', [TITLE, '<Field label="">\n <Input'])), /<Input> has no aria-label, aria-labelledby or label/);+ assertFail(grade(LABELS, withPage(E4, 'page.tsx', [TITLE, '<Field label={null}>\n <Input'])), /<Input> has no aria-label/);+ assertFail(grade(LABELS, withPage(E4, 'page.tsx', [TITLE, "<Field>\n <Input\n aria-label={''}"])), /<Input> has no aria-label/);+ // A translated or computed label still names the control.+ assertPass(grade(LABELS, withPage(E4, 'page.tsx', [TITLE, "<Field label={translate('title')}>\n <Input"])));+});++// A `<label htmlFor>` (or Fluent `<Label htmlFor>`) names its control only if it can show some text: an+// expression that is statically empty (`{null}`, `{''}`, `{undefined}`, `{false}`, a comment) shows nothing,+// at any depth of the markup inside it, and a nested element's attributes are no text. Text, a non-empty+// literal and a computed or translated value do.+test('eval 4: a label element that shows nothing names no control', () => {+ const TITLE = '<Field label="Title">\n <Input\n aria-label="Title"';+ const labelled = (label) => withPage(E4, 'page.tsx', [TITLE, `<Field>\n ${label}\n <Input\n id="title"`]);+ for (const tag of ['label', 'Label']) {+ for (const nothing of ['{null}', "{''}", '{undefined}', '{false}', '{/* the title */}', '<span>{null}</span>', '<span className={styles.title}>{null}</span>', ' ']) {+ assertFail(grade(LABELS, labelled(`<${tag} htmlFor="title">${nothing}</${tag}>`)), /<Input> has no aria-label, aria-labelledby or label/);+ }+ for (const shown of ['Title', "{'Title'}", "{translate('title')}", '{titleLabel}', '<span>Title</span>']) {+ assertPass(grade(LABELS, labelled(`<${tag} htmlFor="title">${shown}</${tag}>`)));+ }+ }+});++test('eval 13: literal text in a conditional or a template child is hardcoded too', () => {+ const child = (expression) => withPage(E13, 'page.tsx', ["<Text>{t('empty')}</Text>", `<Text>{${expression}}</Text>`]);+ assertFail(grade(TRANSLATED, child("rows.length ? 'Contacts' : 'No contacts.'")), /hardcoded JSX string '(?:Contacts|No contacts\.)'/);+ assertFail(grade(TRANSLATED, child("rows.length === 0 && 'No contacts.'")), /hardcoded JSX string 'No contacts\.'/);+ assertFail(grade(TRANSLATED, child("error || 'Something went wrong'")), /hardcoded JSX string 'Something went wrong'/);+ assertFail(grade(TRANSLATED, child("error ?? 'Unknown error'")), /hardcoded JSX string 'Unknown error'/);+ assertFail(grade(TRANSLATED, child('`${rows.length} contacts`')), /hardcoded JSX string `/);+ assertFail(grade(TRANSLATED, withPage(E13, 'page.tsx', ["<Spinner label={t('title')} />", "<Spinner label={rows.length ? 'Loading' : t('title')} />"])), /hardcoded label 'Loading' on <Spinner>/);+ // Keys inside the helper's call, and branches that are translated or only numbers, are not text.+ assertPass(grade(TRANSLATED, child("rows.length ? t('title') : t('empty')")));+ assertPass(grade(TRANSLATED, child('error ? t(\'empty\') : `${rows.length}`')));+});diff --git a/evals/model-apps/genpage/tests/run-layer-2.test.js b/evals/model-apps/genpage/tests/run-layer-2.test.jsindex 7405dd36b..e1851aa76 100644--- a/evals/model-apps/genpage/tests/run-layer-2.test.js+++ b/evals/model-apps/genpage/tests/run-layer-2.test.js@@ -239,8 +239,9 @@ export default GeneratedComponent;`,assert.match(green.stdout, /Phase 5b: Generated \.tsx uses only column names verified from RuntimeTypes\.ts/);assert.match(green.stdout, /# SKIP column-name verification requires RuntimeTypes\.ts fixture/);- // The column oracle is intentionally still a SKIP. Inject a failing result at its real- // registry entry to prove routing invokes that callback and propagates failure, not just text.+ // A fixture without RuntimeTypes.ts has no schema for the column oracle (lib/column-contract.js) to+ // check against, so it SKIPs. Inject a failing result at its real registry entry to prove routing+ // invokes that callback and propagates failure, not just text.const preload = path.join(root, 'phase-5b-probe.cjs');const library = path.join(__dirname, '..', 'lib', 'assertions-layer-2.js');fs.writeFileSync(preload, `diff --git a/evals/model-apps/genpage/tests/workflow-expectations.test.js b/evals/model-apps/genpage/tests/workflow-expectations.test.jsnew file mode 100644index 000000000..b08b1920f--- /dev/null+++ b/evals/model-apps/genpage/tests/workflow-expectations.test.js@@ -0,0 +1,300 @@+'use strict';++// Unit tests for the per-eval workflow expectations that grade a run's recorded evidence+// (lib/assertions-layer-1.js and lib/preservation-contract.js): eval 3's Preservation Constraints and+// its stop at an app with no pages, eval 9's realistic sample data, eval 1's column names in the workflow+// layer, and eval 10's discovery, its auth-blocker branches and the branch that proceeds past an identity+// warning.+//+// Each check PASSES on the committed fixture whose evidence it reads, FAILS on an in-memory mutation+// of that fixture that introduces exactly the regression it exists to catch, and SKIPs only where its+// evidence is not part of a fixture's shape. Mutations go through `edit`, which asserts the text it+// replaces is really there, so a fixture change cannot silently turn a failing case into a vacuous one.++const { test } = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');++const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');+const { loadFixtures } = require('../lib/fixture-loader.js');+const { quotedIdentifiers } = require('../lib/preservation-contract.js');+const { refusalProblems } = require('../lib/workflow-evidence.js');++const FIXTURES = loadFixtures(path.join(__dirname, '..', 'fixtures'));++function committed(dirName) {+ const fixture = FIXTURES.find((f) => f.dirName === dirName);+ assert.ok(fixture, `committed fixture ${dirName} exists`);+ return fixture;+}++function edit(text, from, to) {+ // A Windows checkout may hold a fixture with CRLF line ends; multi-line edits follow the file's.+ if (typeof text === 'string' && text.includes('\r\n')) [from, to] = [from, to].map((s) => s.replace(/\r?\n/g, '\r\n'));+ assert.ok(typeof text === 'string' && text.includes(from), `fixture text contains ${JSON.stringify(from)}`);+ return text.split(from).join(to);+}++function grade(text, fixture) {+ const check = PHASE_EXPECTATIONS.get(text);+ assert.ok(check, `a check is registered for: ${text}`);+ return check({ fixture, eval: { id: fixture.id } });+}++function assertPass(result) { assert.equal(result.status, 'pass', result.reason); }+function assertFail(result, reason) {+ assert.equal(result.status, 'fail', `expected a failure, got ${result.status}: ${result.reason}`);+ assert.match(result.reason, reason);+}+function assertSkip(result, reason) {+ assert.equal(result.status, 'skip', `expected a skip, got ${result.status}: ${result.reason}`);+ assert.match(result.reason, reason);+}++// A copy of a fixture with one event's result replaced (the events are the contract-2 record of each command).+function withEvent(fixture, id, change) {+ assert.ok(fixture.events.some((e) => e.id === id), `${fixture.dirName} records event ${id}`);+ return { ...fixture, events: fixture.events.map((e) => (e.id === id ? change(structuredClone(e)) : e)) };+}++// --- Eval 3: Preservation Constraints --------------------------------------------------------------++const E3 = '3-contacts-edit-search-sort';+const PRESERVED = 'Edit Phase 5: Existing functionality is preserved per the edit plan\'s Preservation Constraints';++test('eval 3: every identifier the Preservation Constraints quote and the downloaded page uses survives the edit', () => {+ const base = committed(E3);+ assertPass(grade(PRESERVED, base));+ const page = base.files.find((f) => f.name === 'page.tsx');+ const dropped = (from, to) => ({ ...base, files: base.files.map((f) => (f === page ? { ...f, content: edit(f.content, from, to) } : f)) });+ assertFail(grade(PRESERVED, dropped('__ppContactsDirectory_contactInflight', '__ppContactsDirectory_pending')), /no longer uses `__ppContactsDirectory_contactInflight`/);+ assertFail(grade(PRESERVED, dropped('navigateTo', 'openForm')), /no longer uses `navigateTo`/);+ // A comment cannot keep a removed name alive.+ assertFail(grade(PRESERVED, dropped("const INFLIGHT_KEY = '__ppContactsDirectory_contactInflight';", "const INFLIGHT_KEY = '__ppContactsDirectory_pending'; // was __ppContactsDirectory_contactInflight")), /no longer uses `__ppContactsDirectory_contactInflight`/);+ assertFail(grade(PRESERVED, { ...base, genpageEditPlan: edit(base.genpageEditPlan, '## Preservation Constraints', '## Kept As Is') }), /no ## Preservation Constraints/);+ const prose = base.genpageEditPlan.replace(/(## Preservation Constraints\r?\n)[\s\S]*?(\r?\n## )/, '$1- The existing sort logic on the name column must still work.$2');+ assertSkip(grade(PRESERVED, { ...base, genpageEditPlan: prose }), /quote no code the downloaded page uses/);+ const noBefore = { ...base, artifacts: Object.fromEntries(Object.entries(base.artifacts).filter(([name]) => !name.startsWith('before/'))) };+ assertFail(grade(PRESERVED, noBefore), /downloaded page .* was not captured/);+ assert.deepEqual(quotedIdentifiers('- Keep `queryTable(\'contact\')` and `[dataReady]`; omit `--connectors`.'), ['queryTable', 'contact', 'dataReady', 'connectors']);+});++// --- Eval 3: an app with no pages ---------------------------------------------------------------------------++const NO_PAGES = '3-edit-no-pages-stop';+const ZERO_PAGES = 'Edit Phase 1b: If the app has zero genpages, the user is told there are no pages to edit and the flow stops';+const LISTED_FOR_APP = 'Edit Phase 1b: After app selection, genpage.js list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names';+const APPS_PRESENTED = 'Edit Phase 1a: Apps are presented to the user via AskUserQuestion using the actual app name and app-id GUID from the apps.js list output';+const PAGES_PRESENTED = 'Edit Phase 1b: Pages are presented to the user via AskUserQuestion using the actual page names and page-id GUIDs from genpage.js list output';+const DOWNLOADED = 'Edit Phase 2: genpage.js download produces <working-dir>/<page-id>/ with page.tsx, config.json, prompt.txt';+const CONTACTS_PAGE = { pageId: '22222222-3333-4444-5555-666666666666', name: 'Contacts Directory', title: 'Contacts Directory' };+const DOWNLOAD = { id: 'download', command: "node 'D:/repo/plugins/model-apps/scripts/genpage.js' download --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --page-id '22222222-3333-4444-5555-666666666666' --output-directory 'D:/work/contacts-search-sort'", exitCode: 0, result: { ok: true } };++test('eval 3: an app with no pages is reported to the user and the edit flow stops', () => {+ const base = committed(NO_PAGES);+ assertPass(grade(ZERO_PAGES, base));+ assertSkip(grade(ZERO_PAGES, committed(E3)), /no page listing came back empty in this scenario/);+ assertFail(grade(ZERO_PAGES, withEvent(base, 'list-pages', (e) => { delete e.userMessage; return e; })), /the user was not told the app has no pages to edit/);+ assertFail(grade(ZERO_PAGES, withEvent(base, 'list-pages', (e) => ({ ...e, userMessage: 'Done.' }))), /the user was not told the app has no pages to edit/);+ // A listing that returned a page is not this branch, and a failed listing is never "no pages".+ assertFail(grade(ZERO_PAGES, withEvent(base, 'list-pages', (e) => ({ ...e, result: { ...e.result, count: 1, pages: [CONTACTS_PAGE] } }))), /the page listing returned pages to edit/);+ assertFail(grade(ZERO_PAGES, withEvent(base, 'list-pages', (e) => ({ ...e, exitCode: 1, result: { ok: false, error: 'request failed' } }))), /a failed listing is never "no pages"/);+ // A navigation entry whose page no longer exists is no page to offer.+ assertPass(grade(ZERO_PAGES, withEvent(base, 'list-pages', (e) => ({ ...e, result: { ...e.result, count: 1, pages: [{ ...CONTACTS_PAGE, name: null, exists: false }] } }))));+ // Going on after the empty listing is the regression, and so is a log that never says the flow stopped.+ assertFail(grade(ZERO_PAGES, { ...base, events: [...base.events, DOWNLOAD] }), /went on to download, plan, edit or upload after the app listed no pages/);+ assertFail(grade(ZERO_PAGES, { ...base, events: [...base.events, { id: 'planner', command: 'Task genpage-edit-planner (intent, app/page ids)', result: { action: 'plan' } }] }), /went on to download, plan, edit or upload/);+ assertFail(grade(ZERO_PAGES, { ...base, workflowLog: base.workflowLog.replace(/\bstop(?:s|ped)?\b/gi, 'went on') }), /does not record that the edit flow stopped/);+});++// The flow stops at the FIRST listing that came back empty; another read after it cannot take back what the+// run did in between, and a listing that returns pages later does not make going on legitimate.+test('eval 3: a later page listing does not hide what the run did after the app listed no pages', () => {+ const base = committed(NO_PAGES);+ const listing = base.events.find((e) => e.id === 'list-pages');+ const planner = { id: 'late-planner', command: 'Task genpage-edit-planner (intent, app/page ids)', result: { action: 'plan' } };+ const again = { ...structuredClone(listing), id: 'list-pages-again' };+ const relisted = { ...base, events: [...base.events, planner, again] };+ assertFail(grade(ZERO_PAGES, relisted), /went on to download, plan, edit or upload after the app listed no pages/);+ assert.match(refusalProblems(relisted).join('\n'), /went on to download, plan, edit or upload after the app listed no pages/);+ // A second read on its own goes on with nothing, and the user may be told at it.+ assertPass(grade(ZERO_PAGES, { ...base, events: [...base.events, again] }));+ const toldLater = { ...base, events: [...base.events.map((e) => (e === listing ? (({ userMessage, ...rest }) => rest)(e) : e)), again] };+ assertPass(grade(ZERO_PAGES, toldLater));+ // In a full edit run, an empty listing of another app before the one it edits is still a stop it went past.+ const edit = committed(E3);+ const pages = edit.events.find((e) => e.id === 'list-pages');+ const otherApp = { ...structuredClone(pages), id: 'list-other-app', command: pages.command.replace('11111111-2222-3333-4444-555555555555', '44444444-5555-6666-7777-888888888888'), result: { ...pages.result, appId: '44444444-5555-6666-7777-888888888888', count: 0, pages: [] }, userMessage: 'This app has no generative pages to edit. Did you mean to create a new page?' };+ const at = edit.events.indexOf(pages);+ assertFail(grade(ZERO_PAGES, { ...edit, events: [...edit.events.slice(0, at), otherApp, ...edit.events.slice(at)] }), /went on to download, plan, edit or upload after the app listed no pages/);+ // The listing the refusal stopped at is the one whose app is graded: a later listing of an offered app does not+ // make an earlier listing of an app apps.js list never returned right.+ const guessed = withEvent(base, 'list-pages', (e) => ({ ...e, command: e.command.replace('11111111-2222-3333-4444-555555555555', '99999999-2222-3333-4444-555555555555') }));+ const guessedThenOffered = { ...guessed, events: [...guessed.events, again] };+ assertFail(grade(LISTED_FOR_APP, guessedThenOffered), /genpage\.js list ran for app 99999999-2222-3333-4444-555555555555, which apps\.js list did not return/);+ assertFail(grade(APPS_PRESENTED, guessedThenOffered), /the app the run continued with \(99999999-2222-3333-4444-555555555555\) is not in the listing/);+});++test('eval 3: a run that stopped at an app with no pages is graded as that refusal, not as a broken edit', () => {+ const base = committed(NO_PAGES);+ assert.deepEqual(refusalProblems(base), []);+ assert.match(refusalProblems({ ...base, events: [...base.events, DOWNLOAD] }).join('\n'), /went on to download/);+ // The create flow's plan checks and the edit phases after the listing do not apply to it ...+ assertSkip(WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md')({ fixture: base }), /edit flow/);+ for (const text of [PAGES_PRESENTED, DOWNLOADED]) assertSkip(grade(text, base), /the run stopped at Edit Phase 1b: the app has no pages to edit/);+ // ... while a full edit run is still graded by them.+ assertPass(grade(PAGES_PRESENTED, committed(E3)));+ assertPass(grade(DOWNLOADED, committed(E3)));+ // The listing it stopped at must be of an app apps.js list returned and the user was offered.+ assertPass(grade(LISTED_FOR_APP, base));+ assertPass(grade(APPS_PRESENTED, base));+ const elsewhere = withEvent(base, 'list-pages', (e) => ({ ...e, command: e.command.replace('11111111-2222-3333-4444-555555555555', '99999999-2222-3333-4444-555555555555') }));+ assertFail(grade(LISTED_FOR_APP, elsewhere), /genpage\.js list ran for app 99999999-2222-3333-4444-555555555555, which apps\.js list did not return/);+ assertFail(grade(APPS_PRESENTED, elsewhere), /the app the run continued with \(99999999-2222-3333-4444-555555555555\) is not in the listing/);+ // Without the declared refusal, the same evidence is a broken edit run.+ const undeclared = { ...base, manifest: { ...base.manifest, expectedOutcome: 'deployed', refusal: undefined } };+ assertFail(grade(LISTED_FOR_APP, undeclared), /genpage\.js download was not run/);+ assertFail(grade(DOWNLOADED, undeclared), /genpage\.js download \(or pac model genpage download\) not invoked/);+});++// --- Eval 9: realistic sample data ---------------------------------------------------------------------++const E9 = '9-project-tracker-new-entities';+const REALISTIC = 'Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js; realistic values (not lorem ipsum)';++test('eval 9: sample rows handed to provision-entities.js are realistic', () => {+ const base = committed(E9);+ assertPass(grade(REALISTIC, base));+ const input = (from, to) => ({ ...base, artifacts: { ...base.artifacts, 'provision-input.json': edit(base.artifacts['provision-input.json'], from, to) } });+ assertFail(grade(REALISTIC, input('"cr_name": "Warehouse Scanner Rollout"', '"cr_name": "Lorem ipsum dolor sit amet"')), /cr_Project row 2 cr_name is lorem ipsum/);+ assertFail(grade(REALISTIC, input('"cr_manager": "Avery Chen"', '"cr_manager": "Test 1"')), /cr_Project row 1 cr_manager is a placeholder/);+ assertFail(grade(REALISTIC, input('"cr_name": "Launch and DNS cutover"', '"cr_name": "Milestone 4"')), /cr_Milestone row 4 cr_name is a placeholder/);+ assertFail(grade(REALISTIC, input('"cr_name": "Customer Portal Migration"', '"cr_name": "Contoso Website Redesign"')), /cr_Project rows repeat the name "Contoso Website Redesign"/);+ assertFail(grade(REALISTIC, { ...base, events: base.events.filter((e) => !/--sample-data/.test(e.command)) }), /no provision-entities\.js --sample-data run/);+ const { 'provision-input.json': _, ...withoutInput } = base.artifacts;+ assertFail(grade(REALISTIC, { ...base, artifacts: withoutInput }), /provision-input\.json was not captured/);+});++// --- Eval 1: column names, in the workflow layer -------------------------------------------------------++test('eval 1: the workflow layer grades the same column names against the RuntimeTypes.ts the run kept', () => {+ const text = 'Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names';+ const base = committed('1-account-cards-verified-columns');+ assertPass(grade(text, base));+ const guessed = { ...base, files: base.files.map((f) => ({ ...f, content: edit(f.content, "'emailaddress1', 'telephone1']", "'email', 'telephone1']") })) };+ assertFail(grade(text, guessed), /names email, which RuntimeTypes\.ts does not declare on account/);+ assertSkip(grade(text, committed('1-account-card-gallery')), /requires RuntimeTypes\.ts fixture/);+});++// --- Eval 10: discovery and the auth-blocker branches ---------------------------------------------------++const MISSING = 'Phase 1 (Planner): cr_widget is identified as NOT existing (exact logical-name match, not fuzzy)';+const WHOAMI = 'Phase 2a: If blocker:\'whoami_403\', orchestrator surfaces the message including the specific `az login --username <pacUser>` command and halts';+const SIGNED_OUT = 'Phase 2a: If the script returns blocker:\'az_not_logged_in\', orchestrator surfaces the message (\'Run `az login`...\') to the user and halts (entity-builder is NOT invoked)';+const E10 = ['10-auth-timeout-halt', '10-az-signed-out-halt', '10-whoami-403-halt'];++test('eval 10: the missing table is confirmed absent by an exact logical-name search', () => {+ for (const dir of E10) assertPass(grade(MISSING, committed(dir)));+ const base = committed('10-auth-timeout-halt');+ assertFail(grade(MISSING, withEvent(base, 'list-tables-search', (e) => ({ ...e, result: { ok: true, search: ['cnt_widget'], exact: true, count: 1, tables: [{ logicalName: 'cnt_widget' }], missing: [] } }))), /does not record cnt_widget as absent/);+ // A fuzzy search whose rows include a longer name is no exact verdict.+ assertFail(grade(MISSING, withEvent(base, 'list-tables-search', (e) => ({ ...e, command: e.command.replace(' --exact', ''), result: { ok: true, search: ['cnt_widget'], count: 1, tables: [{ logicalName: 'cnt_widgetpart' }] } }))), /does not rest on an exact logical-name match/);+ assertFail(grade(MISSING, withEvent(base, 'list-tables-search', (e) => ({ ...e, result: { ok: false, error: 'request failed' } }))), /list-tables failed/);+ assertFail(grade(MISSING, { ...base, events: base.events.filter((e) => e.id !== 'list-tables-search') }), /list-tables --search was not run/);+});++test('eval 10: a WhoAmI 403 surfaces the az login --username advice verbatim and halts', () => {+ const base = committed('10-whoami-403-halt');+ assertPass(grade(WHOAMI, base));+ assertSkip(grade(WHOAMI, committed('10-auth-timeout-halt')), /whoami_403 blocker not in scenario/);+ assertFail(grade(WHOAMI, withEvent(base, 'auth', (e) => ({ ...e, userMessage: 'Your sign-in did not work. Please try again.' }))), /not surfaced to the user verbatim/);+ const generic = 'WhoAmI returned 403. Please sign in again.';+ assertFail(grade(WHOAMI, withEvent(base, 'auth', (e) => ({ ...e, result: { ...e.result, message: generic }, userMessage: generic }))), /does not name `az login --username maker@contoso\.com`/);+ const proceeded = { ...base, events: [...base.events, { id: 'provision', command: 'node scripts\\provision-entities.js --env https://contoso.crm.dynamics.com --input @provision-input.json --apply', result: { ok: true } }] };+ assertFail(grade(WHOAMI, proceeded), /provisioned, generated or uploaded after the whoami_403 blocker/);+ assertFail(grade(WHOAMI, { ...base, workflowLog: base.workflowLog.replace(/Halted/g, 'Noted') }), /did not halt/);+});++test('eval 10: a signed-out Azure CLI surfaces the az login advice verbatim and halts', () => {+ const base = committed('10-az-signed-out-halt');+ assertPass(grade(SIGNED_OUT, base));+ assertSkip(grade(SIGNED_OUT, committed('10-whoami-403-halt')), /az_not_logged_in blocker not in scenario/);+ assertFail(grade(SIGNED_OUT, withEvent(base, 'auth', (e) => ({ ...e, userMessage: 'Please sign in.' }))), /not surfaced to the user verbatim/);+ const dispatched = { ...base, events: [...base.events, { id: 'builder', command: 'Task genpage-entity-builder (plan genpage-plan.md)', result: { ok: true } }] };+ assertFail(grade(SIGNED_OUT, dispatched), /entity-builder invoked despite az_not_logged_in blocker/);+ assertFail(grade(SIGNED_OUT, { ...base, workflowLog: base.workflowLog.replace(/Halted/g, 'Noted') }), /did not halt/);+ // A historical log is read from its `Result:` line and its prose advice.+ const historical = { dirName: 'historical', id: 10, contractVersion: 1, manifest: { contractVersion: 1 }, events: undefined, files: [],+ workflowLog: '- Command: `node scripts/check-auth.js`\n - Result: ok=false, blocker=az_not_logged_in\n- Told the user to run `az login`; halted.\n' };+ assertPass(grade(SIGNED_OUT, historical));+ assertFail(grade(SIGNED_OUT, { ...historical, workflowLog: historical.workflowLog.replace('Told the user to run `az login`; ', '') }), /no `az login` advice/);+});++// --- Eval 10: the branch that proceeds ----------------------------------------------------------------------+// A working sign-in whose az and pac identities differ is a warning, not a blocker: the run shows it and goes on.++const PROCEEDS = '10-identity-mismatch-proceeds';+const MISMATCH = 'Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning';+const BUILDER_AFTER_OK = 'Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true';+const TIMEOUT = 'Phase 2a: Auth timeout retries once then halts before provisioning or upload';+const GATE_FIRST = 'Phase 2a: Orchestrator runs scripts/check-auth.js BEFORE invoking entity-builder; parses the returned JSON';++// The same event with its result's message and the message the user saw replaced together.+const withMessage = (change) => (e) => {+ const message = change(e.result.message);+ return { ...e, result: { ...e.result, message }, userMessage: message };+};++test('eval 10: an ok:true gate with mismatched identities shows its one-line warning verbatim and goes on', () => {+ const base = committed(PROCEEDS);+ assertPass(grade(MISMATCH, base));+ // The refusals have no such gate, nor does a run whose identities match.+ for (const dir of E10) assertSkip(grade(MISMATCH, committed(dir)), /no ok:true, identitiesMatch:false auth result/);+ assertSkip(grade(MISMATCH, committed('9-project-tracker-new-entities')), /no ok:true, identitiesMatch:false auth result/);+ assertFail(grade(MISMATCH, withEvent(base, 'auth-preflight', (e) => { delete e.userMessage; return e; })), /not surfaced to the user verbatim/);+ assertFail(grade(MISMATCH, withEvent(base, 'auth-preflight', (e) => ({ ...e, userMessage: 'Heads up: az and pac differ.' }))), /not surfaced to the user verbatim/);+ assertFail(grade(MISMATCH, withEvent(base, 'auth-preflight', withMessage((m) => m.replace(' WhoAmI passed', '\nWhoAmI passed')))), /is not one line/);+ assertFail(grade(MISMATCH, withEvent(base, 'auth-preflight', withMessage((m) => m.replace(/ — but if a later step.*$/, '.')))), /does not name `az login --username maker@contoso\.onmicrosoft\.com`/);+ // Stopping at a warning is the regression: the run must go on to the entity-builder.+ const stopped = { ...base, events: base.events.slice(0, base.events.findIndex((e) => e.id === 'auth-preflight') + 1) };+ assertFail(grade(MISMATCH, stopped), /did not go on past the ok:true, identitiesMatch:false gate/);+ assertFail(grade(MISMATCH, { ...base, manifest: { ...base.manifest, expectedOutcome: 'refused', refusal: { stage: 'auth' } } }), /run stopped although its only auth finding was a warning-only identity mismatch/);+});++test('eval 10: a builder re-probe that sees the mismatch logs the warning in its transaction log', () => {+ const base = committed(PROCEEDS);+ assertPass(grade(GATE_FIRST, base));+ const unlogged = { ...base, entityCreationLog: base.entityCreationLog.split(/\r?\n/).filter((line) => !/^- Warning:/.test(line)).join('\n') };+ assertFail(grade(GATE_FIRST, unlogged), /the entity-builder did not log its identity-mismatch warning/);+ // The orchestrator's own gate still owes the user the verbatim warning.+ assertFail(grade(GATE_FIRST, withEvent(base, 'auth-preflight', (e) => { delete e.userMessage; return e; })), /warning-only identity mismatch was not surfaced verbatim/);+});++test('eval 10: the entity-builder is dispatched only after an ok:true gate, read from the recorded calls', () => {+ const base = committed(PROCEEDS);+ assertPass(grade(BUILDER_AFTER_OK, base));+ for (const dir of E10) assertSkip(grade(BUILDER_AFTER_OK, committed(dir)), /entity-builder not invoked/);+ const builder = base.events.find((e) => e.id === 'entity-builder-1');+ assertFail(grade(BUILDER_AFTER_OK, { ...base, events: [builder, ...base.events.filter((e) => e !== builder)] }), /entity-builder invoked before check-auth\.js/);+ const blocked = withEvent(base, 'auth-preflight', (e) => ({ ...e, result: { ...e.result, ok: false, blocker: 'whoami_403' } }));+ assertFail(grade(BUILDER_AFTER_OK, blocked), /the check-auth\.js result before it is not ok:true/);+ // A capture made before the calls were recorded is read from its log lines.+ const historical = { dirName: 'historical', id: 10, contractVersion: 1, manifest: { contractVersion: 1 }, events: undefined, files: [],+ workflowLog: '- Command: `node scripts/check-auth.js`\n - Result: ok=true\n- genpage-entity-builder invoked with the plan\n' };+ assertPass(grade(BUILDER_AFTER_OK, historical));+ assertFail(grade(BUILDER_AFTER_OK, { ...historical, workflowLog: '- genpage-entity-builder invoked with the plan\n- Command: `node scripts/check-auth.js`\n - Result: ok=true\n' }), /entity-builder invoked before check-auth\.js/);+});++test('eval 10: the timeout expectation grades a refusal whole, and a run that went on only when it timed out', () => {+ assertPass(grade(TIMEOUT, committed('10-auth-timeout-halt')));+ const base = committed(PROCEEDS);+ assertSkip(grade(TIMEOUT, base), /no auth timeout in this scenario/);+ const gate = base.events.find((e) => e.id === 'auth-preflight');+ const advice = 'Azure CLI did not answer within 60 s; retry once or set POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000.';+ const slow = (id) => ({ id, command: gate.command, exitCode: 1, result: { ok: false, blocker: 'az_timeout', message: advice, warnings: [], envUrl: null, identitiesMatch: false, whoAmI: null }, userMessage: advice });+ const at = base.events.indexOf(gate);+ const retried = (...extra) => ({ ...base, events: [...base.events.slice(0, at), ...extra, ...base.events.slice(at)] });+ // One timeout, one retry that passes: the run went on legitimately.+ assertPass(grade(TIMEOUT, retried(slow('auth-slow'))));+ assertFail(grade(TIMEOUT, retried(slow('auth-slow-1'), slow('auth-slow-2'), slow('auth-slow-3'))), /auth timeout retried more than once/);+});diff --git a/evals/model-apps/tests/eval-coverage-baseline.json b/evals/model-apps/tests/eval-coverage-baseline.jsonindex 08c4d675e..7644b9403 100644--- a/evals/model-apps/tests/eval-coverage-baseline.json+++ b/evals/model-apps/tests/eval-coverage-baseline.json@@ -8,7 +8,7 @@"status is \"deferred\" when an offline check could grade the stored artifacts, \"manual\" when a person has to","judge the generated page (Layer 3).","neverGraded: registered checks that return SKIP on every fixture they run on, so they verify nothing yet.",- "eval null is a common assertion. reason is the SKIP reason the check gives."+ "eval null is a common assertion. Every entry's reason says why it is not graded yet, and what would close it."],"genpage": {"uncaptured": [],@@ -16,130 +16,40 @@{"eval": 2,"status": "deferred",- "text": "Phase 1 (Planner): Plan mentions mock data, D3.js for chart, DataGrid for customers table, KPI cards"- },- {- "eval": 3,- "status": "deferred",- "text": "Edit Phase 1b: If the app has zero genpages, the user is told there are no pages to edit and the flow stops"- },- {- "eval": 3,- "status": "manual",- "text": "Edit Phase 5: Existing functionality is preserved per the edit plan's Preservation Constraints"- },- {- "eval": 4,- "status": "manual",- "text": "Phase 5 (Page Builder): Generated code includes step state management (current step tracking) and Next/Back navigation"+ "text": "Phase 1 (Planner): Plan mentions mock data, D3.js for chart, DataGrid for customers table, KPI cards",+ "reason": "Gradeable from the plan text, but the captured run 2-mock-dashboard-real shows real drift: its plan draws the chart in inline SVG and uses Table, not D3.js and DataGrid (references/rules.md: D3.js for all charts). A correct check fails that capture, the runners have no expected-failure mark, and a check loosened to accept SVG or Table would hide the drift."},{"eval": 4,- "status": "manual",- "text": "Phase 5 (Page Builder): Step 3 (review) shows a summary of entered data before submission"- },- {- "eval": 9,- "status": "manual",- "text": "Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js; realistic values (not lorem ipsum)"- },- {- "eval": 10,"status": "deferred",- "text": "Phase 1 (Planner): cr_widget is identified as NOT existing (exact logical-name match, not fuzzy)"- },- {- "eval": 10,- "status": "deferred",- "text": "Phase 2a: If blocker:'whoami_403', orchestrator surfaces the message including the specific `az login --username <pacUser>` command and halts"- },- {- "eval": 10,- "status": "deferred",- "text": "Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning"- },- {- "eval": 12,- "status": "manual",- "text": "Phase 5 (Page Builder): Generated code implements the revised plan (includes BOTH filter toolbar AND search box)"+ "text": "Phase 5 (Page Builder): Generated code includes step state management (current step tracking) and Next/Back navigation",+ "reason": "Gradeable offline only with data-flow analysis. Whether Next and Back move the step is the value the step's setter receives: what an updater callback returns, or what a local or a helper's argument holds when the setter runs. A syntactic scan of the handler can find an increment but cannot prove the setter receives it: setStep((s) => { const next = s + 1; return s; }) computes the next step and returns the old one, so the wizard never advances. Grading it needs a parse of the handler and the updater's return value, which the lexer-based page checks do not have; a check that scans the handler's text would pass that page."},{"eval": 13,"status": "deferred",- "text": "Phase 5 (Page Builder): Generated .tsx fetches usersettings via dataApi.retrieveRow and uses formatDate/formatNumber/formatCurrency helpers"+ "text": "Phase 5 (Page Builder): Generated .tsx fetches usersettings via dataApi.retrieveRow and uses formatDate/formatNumber/formatCurrency helpers",+ "reason": "Gradeable from the page source, but the only eval-13 fixture, 13-contact-localization, shows real drift: it never reads usersettings and formats nothing through formatDate/formatNumber/formatCurrency (references/localization.md makes the usersettings read mandatory). A correct check fails it, and the runners have no expected-failure mark."},{"eval": 15,"status": "deferred",- "text": "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; picklist options include {value,label} pairs"+ "text": "Phase 2b (Entity Builder): cr_ticket is provisioned with choice columns via provision-entities.js input JSON; picklist options include {value,label} pairs",+ "reason": "The expectation names an input shape provision-entities.js refuses: its input validation reads each Choice option as a label (a string, or a map of LCID to label) and rejects a {label, value} object ('label' is not an LCID); values are assigned 100000000 + index. It needs rewording to the label form together with agents/genpage-entity-builder.md Step 4, which documents the same refused shape, and the only eval-15 fixture, 15-support-tickets-real, did not capture its input JSON."}],"neverGraded": [- {- "runner": "layer-1",- "eval": 1,- "text": "Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names",- "reason": "column-name verification needs schema cross-check"- },{"runner": "layer-2","eval": null,"text": "For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)",- "reason": "Rule 14 batched-setState requires AST analysis"- },- {- "runner": "layer-2",- "eval": 1,- "text": "Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names",- "reason": "column-name verification requires RuntimeTypes.ts fixture"- },- {- "runner": "layer-2",- "eval": 4,- "text": "Phase 5 (Page Builder): All form fields have aria-labels or aria-labelledby for accessibility",- "reason": "aria-label coverage requires AST analysis"- },- {- "runner": "layer-2",- "eval": 5,- "text": "Phase 5 (Page Builder): All components and utilities are separate top-level functions (no nested function definitions)",- "reason": "nested function detection requires AST analysis"- },- {- "runner": "layer-2",- "eval": 7,- "text": "Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts",- "reason": "column-name verification requires RuntimeTypes.ts fixture"- },- {- "runner": "layer-1",- "eval": 10,- "text": "Phase 2a: If the script returns blocker:'az_not_logged_in', orchestrator surfaces the message ('Run `az login`...') to the user and halts (entity-builder is NOT invoked)",- "reason": "az_not_logged_in blocker not in scenario"- },- {- "runner": "layer-1",- "eval": 10,- "text": "Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true",- "reason": "entity-builder not invoked"- },- {- "runner": "layer-2",- "eval": 13,- "text": "Phase 5 (Page Builder): All user-visible text goes through a translate() helper — no hardcoded display strings in JSX",- "reason": "translate() coverage requires AST analysis"- },- {- "runner": "layer-2",- "eval": 15,- "text": "Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)",- "reason": "choice enum verification requires RuntimeTypes.ts fixture"+ "reason": "Gradeable from the page source, but a correct check fails historical fixtures 1-account-card-gallery, 7-job-candidates-new-entities, 11-recruitment-multi-page and 13-contact-localization: each sets its rows in try and calls setLoading(false) in finally, the pattern Rule 14 names as an intermediate render. Rule 14 predates them, so it is real drift; the runners have no expected-failure mark, and skipping historical fixtures would hide it."},{"runner": "layer-2","eval": 6,"text": "Phase 5 (Page Builder): Generated code has no unnecessary complexity matching the 'clean and minimal' request",- "reason": "subjective; defer to Layer 3 UX rubric"+ "reason": "Subjective: whether code is more complex than a clean and minimal request needs is a judgement, not a property the source can be checked for; the Layer 3 UX rubric scores it."}]},diff --git a/evals/model-apps/tests/eval-coverage-contract.test.js b/evals/model-apps/tests/eval-coverage-contract.test.jsindex e3a0887b9..6675e2aae 100644--- a/evals/model-apps/tests/eval-coverage-contract.test.js+++ b/evals/model-apps/tests/eval-coverage-contract.test.js@@ -98,7 +98,7 @@ function unregisteredCommonProblems(data, { workflow, code }) {];}-// Every per-eval expectation is checked, or recorded as deferred or manual.+// Every per-eval expectation is checked, or recorded as deferred or manual with the reason no check grades it.function unscoredProblems({ evals, hasCheck, unscored }) {const problems = [];const expectations = new Map();@@ -110,6 +110,7 @@ function unscoredProblems({ evals, hasCheck, unscored }) {if (listed.has(key)) problems.push(`unscored lists ${label} twice`);listed.add(key);if (!STATUSES.has(entry.status)) problems.push(`unscored ${label}: status must be "deferred" or "manual", got ${JSON.stringify(entry.status)}`);+ if (typeof entry.reason !== 'string' || !entry.reason.trim()) problems.push(`unscored ${label} needs a reason: why no offline check grades it yet`);if (!expectations.has(key)) problems.push(`unscored ${label} is no longer in evals.json — remove it`);else if (hasCheck(entry.text)) problems.push(`${label} now has a check — remove it from unscored`);}@@ -422,6 +423,7 @@ test('negative controls: expectation and grading drift is reported', () => {const [first] = unscored;assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: (t) => t === first.text || hasGenpageCheck(t), unscored }).join('\n'), /now has a check/);assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [{ ...first, status: 'later' }, ...unscored.slice(1)] }).join('\n'), /status must be/);+ assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [{ ...first, reason: ' ' }, ...unscored.slice(1)] }).join('\n'), /needs a reason/);assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [...unscored, { eval: first.eval, status: 'deferred', text: 'Phase 1: gone' }] }).join('\n'), /no longer in evals.json/);assert.match(unscoredProblems({ evals: genpageData.evals, hasCheck: hasGenpageCheck, unscored: [...unscored, first] }).join('\n'), /twice/);diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex ada50e4ca..4a4bb71ca 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.18.0",+ "version": "2.19.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.jsonindex ada50e4ca..4a4bb71ca 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.18.0",+ "version": "2.19.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.mdindex 241780dea..300193ae6 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -1704,7 +1704,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belochecks what the lists name before it writes anything** (`lib/page-binding-targets.js`, called from`checkPageBindingsBeforeWriting` next to the navigation check, and in a dry run's plan): it reads theenvironment's `connectionreference` rows and `customapi` rows for the names the pages it writes state —- the pages a changed-only run selects and the navigation targets it may have to make — and **stops**+ every page of a full build; in a changed-only run, the pages it selects and a navigation target only when the+ target is absent (below) — and **stops**(`BuildHalt`, phase `preflight`, code `pages-binding-reference-conflict`, never retried, nothing written) at aconnection reference of that name whose connector is another than the binding's `connectorId` (compared by theconnector's name, the last segment of its id). It never guesses and never makes a reference: the author gives the@@ -1731,6 +1732,24 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloversion than the page was made with. A reference whose row names no custom connector gets no definition read, andits binding's operations are said as not checked: a null lookup is what a connector the platform publishes has, butit is no proof of one (a reference made through the Web API can leave it unset).+ **A changed-only run checks the pages it writes, and no page it leaves alone.** Its pages phase makes an ABSENT+ navigation target from the target's spec entry, bindings and all, and leaves one that exists as it is — but it+ learns which targets exist only after the check. So the changed-only flow tells the build the pages its snapshot+ records the last verified apply deployed (`changedOnly.deployedKeys`, the keys with a page id): such a target is+ neither read nor judged, and one it is not told of is checked (fail closed). A target it was told of and that the+ pages phase finds absent after all (deleted in Maker since) is checked there, before it is made+ (`pagesMadeUnchecked`), with the same verdict and the same halt; the fast apply runs the pages phase alone, so+ nothing is written yet. **Both checks of one attempt share what it has read** (`bindingReads`): a name is read+ once per attempt, and that answer — a row, no row, a failure — stands for both, so the pages-phase check reads+ only names the first did not, and a second read can never fail and turn a conflict the first one proved into "not+ checked" (only names it could not read at all are said by name as not checked — `unread`). A run with an earlier+ phase ignores `deployedKeys` (`bindingCheckScope`) and checks every navigation target before it writes anything.+ A dry run's plan applies the same rule, but has no pages phase to find a target absent, so for each target it was+ told is deployed and would leave unread (`pagesLeftOutAsDeployed`) it asks the environment, read only, whether the+ page is still there (`confirmDeployedTargets`: the page manifest, then the generative pages in the SAVED layer by+ the ids the spec and the manifest give it — `savedPageRows`); a target none of whose ids answers is checked, as the+ apply checks it, and one it cannot settle (no id, a read that fails, which it says) is checked too: the record of an+ earlier apply is never taken as proof that a page is there.**What a rebuild cannot bring to another environment is what the lists name,and the download says so**: when any page holds a binding it prints `NOTE:` on stderr and returns`pageBindings` — `pages` (each page's key, name and the connection references / Custom APIs its bindings go by),@@ -1747,7 +1766,11 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`page-bindings-real-bundle.test.js` what the real SDK does with the lists: a page read with them, a rebuildthat writes no row, a changed list that keeps what the spec could not state, a create in another environment, andthe record of an older publish (the build-level version, with the real pages phase, is in- `sdk-build-pages-deploy.test.js`).+ `sdk-build-pages-deploy.test.js`, which also pins what a changed-only run checks).+ `page-binding-targets-real-bundle.test.js` runs a changed-only apply through the flow over the real SDK and the+ real page backend: an edit of one page leaves an existing navigation target's binding unread, an edit of the target+ itself is refused, and a target deleted since the last apply is refused before it is made — also when it shares a+ reference name with the edited page, by the attempt's one read of that name.**A download is written in a fixed order, so two downloads of one app match byte for byte** and a diffbetween them shows only what changed. Dataverse promises no row order for a query without `$orderby`,and a directory listing is in the file system's order (name order on NTFS, hash order on ext4), so@@ -2158,13 +2181,65 @@ the pipeline and delegates each script's **behavioral spec** to the entries belothe name, or of the lookup column's owner, proves, and any other relationship holding it — or an answer the read cannot prove —stops the build.The codes only add recognition, and prove no more than the English words of the same refusal: the 409 and English-word rules are- unchanged, and they apply whatever code the answer carries, an unlisted one included — an English `0x80060894` answer (another key- over the same columns, "An entity key with the selected attributes already exists on entity.") is still a skip, as it was. A code- another create answers, a generic code (`0x80040216`) and a code the message only quotes do not count by themselves: such an answer- stops the build unless the 409 or the English words read it as an already-exists one — an answer worded in another language, which- the English rule does not read, stops. Pinned by+ unchanged, and they apply whatever code the answer carries, an unlisted one included — with one exception: a key create answered+ `0x80060894` (EntityKeyWithSelectedAttributesExists, "An entity key with the selected attributes already exists on entity.": the+ platform allows one key per set of columns, and another key is over the declared key's) is never read by its words. Those words+ read as an already-exists answer, so where the platform's message was in English the build skipped a key that was never created+ (and its verification then found it missing), and where it was in another language the build stopped — the language of the+ message, not of the environment: one whose only language is Spanish answered in English. The key step decides that code, whatever+ the language of the answer, from the table's keys, read once more by+ the table probe's narrow request (`keyOverSameColumns`, `lib/entity-provision.js`): the declared key over those columns (its+ schema name in any case) is a skip, as an existing key is; a key of another name stops the build — a refusal, not retried —+ naming that key, the columns and what to do: declare that key's name instead, or delete it in Power Apps if it is a leftover;+ where the spec declares both over those columns, keep one; and where the spec declares that key over OTHER columns — the key+ in the environment drifted from the spec, and the build, which skips a key whose name exists, does not change its columns —+ the stop names both column sets and asks for that key to be reconciled (deleted where nothing relies on it) first, never for+ a valid declaration to be dropped. A read that fails or shows no key over exactly those columns stops it with the+ platform's own error. A code another create answers, a generic code (`0x80040216`) and a code the message only quotes do not+ count by themselves: such an answer stops the build unless the 409 or the English words read it as an already-exists one — an+ answer worded in another language, which the English rule does not read, stops. Pinned by`already-exists-codes-real-bundle.test.js`, which runs each of those creates through the real bundle answered in English and- in another language, and requires the same outcome.+ in another language, and requires the same outcome; the key that waits for its table's name column length, and the key made+ ahead of it, by `table-columns-in-create.test.js`.+ Separately, the generic codes are retried in one window only — the lag of a table this build attempt has just created+ (`entity-provision.js`, "The lag of a table this attempt just created"): a column create (in the change set or on its own) or a+ status-reason insert for that table, refused with HTTP 400 `0x80040216` or `0x80090457`, is sent again only after a read made+ after the refusal proves it absent — a list that holds the table's primary name column (or a stock status reason), every entry+ of which names a column with its id (or carries its option value once), and not this one; a column the list names without its+ id proves nothing and is read again, never created again — within the table's budget (60 seconds of the check's own reads, waits+ and sends, the one-by-one creates of the change set's proved-absent columns included; 8 reads; 4 resends of one create, 1 of the+ change set). A create the read shows is adopted, never sent again; a read that fails stops the build with that failure; a status+ reason is read and sent again only after every other labelled create of the phase. A spent check still stops the build — at the+ next create, before any further POST, even of one a read proved absent — with the original refusal (`retry: NEVER`) and a halt —+ printed after the build lease is let go — that says the build may be run again. Neither code is read as "already exists" or as a reason to run the build again, and a table that existed+ or any other error keeps its existing handling. Pinned by `post-create-lag.test.js`.+- **One apply of an app at a time in its workspace (the build lease).** Two builds of the same app that overlap both read+ "missing" and both create — measured over the real bundle: two lookups of the generated `<app>_icon`, two creates, two+ icons in the solution — and the same check-then-create reaches the app, the authored web resources, the views, forms,+ charts, commands, dashboards and pages; the platform's own uniqueness answers are no lock. So every apply holds+ `app-build.<sha256 of the lower-cased app unique name>.lock` in its workspace (`lib/app-operation-lease.js`+ `withAppBuildLease`) for ALL of its work: the CLI takes it after the arguments, the spec and the paths are checked and+ before the auth check, the language read, the SDK's workspace, the journal, the snapshot and the baseline; it covers every+ phase, the build's automatic re-runs and their waits, the settlement of a halt, the inline verify and the baseline written+ last, and is let go before the result is printed (emitResult ends the process, so the command's body answers its result+ and `main()` prints it after the release). `runChangedOnlyApply` takes it — or borrows the one it is handed — before it+ reads the spec's content, the snapshot or the live identity. A second apply is refused at once (`build-locked`, phase+ `preflight`, `retry: NEVER`; stderr, exit 1, no stdout JSON) and has sent nothing and touched no file; there is no wait,+ no age limit and no flag that skips it. A nested apply borrows its caller's capability (`opts.buildLease`, an opaque object+ only the lease makes); a string, a capability already released or one for another app or folder is `build-lease-invalid`,+ and no apply runs without a lease. A dry run takes none. The pages phase keeps its own two locks inside it+ (`app-pages.<hash>.lock`, then the legacy `pages-<spelling>.lock`), so two spellings of one app's name share the lock on a+ case-sensitive file system as they share the page-publish record, and a build of an earlier release — which takes no build+ lock — is still kept out of the pages phase when it spells the app the same way. A lock is taken over only from a build+ proven gone (`process-owner.js`), and said; a warning callback that throws never leaves a lock held (the release is guarded+ from the moment a lock is taken, and a warning given while locks are let go cannot stop the release). The limits:+ builds in different workspaces are not excluded (do not bypass a refusal with `--workspace`); a teardown, a download,+ `/genpage`, `apps.js` and a workspace clear take no build lock; a build of 2.17/2.18 does its pre-pages work without one;+ different apps in one workspace hold different locks. Pinned by+ `app-build-lease.test.js`, `build-lease-cli.test.js`, `build-lease-real-bundle.test.js` (two builds over the real bundle,+ the second started inside the first's icon lookup, authored web resource write or pages-only app create: one of each, and+ a build that meets no other sends exactly the requests it sent before), `app-pages-lease.test.js` and+ `pages-lock-dead-owner.test.js`.- **Bounded parallelism in the read-heavy and publish-heavy paths.** Each item below has tests that countrequests and prove the overlap (`verify-parallel-checks`, `verify-page-code-batch`,`download-parallel-reads`, `teardown-publish-once`, `table-columns-in-create`, and the check-auth tests),@@ -2231,7 +2306,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`Attributes` collection. Dataverse runs the operations in order and, if one fails, rolls back the ones already done([change sets](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets)),so a refused change set has created nothing, and the build then creates the columns one by one as it always did,- with a warning that says why (the platform's own message when its answer carries one). The same fallback covers a+ with a warning that says why (the platform's own message when its answer carries one) — unless the refusal is the+ lag of the table this attempt just created (HTTP 400 `0x80040216` or `0x80090457` in the change set's first part):+ then the table's columns are read first, a column the read shows is adopted, and only what a read proves absent is+ sent again, within the table's budget (the generic codes, above). The same fallback covers atransport that cannot send a change set — the SDK refuses before sending anything when its HTTP client has no`postRaw` (`DataverseClient.supportsAtomicBatch`; `lib/sdk-http-client.js` has it) — and a change set whose answerwas lost or could not be read (a transport failure, a server error, an unreadable success), which may have@@ -2627,7 +2705,7 @@ scripts/check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below)capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/- entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column (unless the run's throttle budget refused to wait for the change set: the phase then stops, `stop`); the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; `makeRunner`, whose runner stops the phase at the next step once the run's throttle budget has refused a wait (`stopIfRefused`: `run` and each item of its `mapLimit`; a step that pays the name column length a table the run created is owed is let through); and `mapLimit`, the bounded fan-out every parallel path reuses+ entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column (unless the run's throttle budget refused to wait for the change set: the phase then stops, `stop`); a column create or status-reason insert for a table this attempt just created that is refused with that table's lag (HTTP 400 `0x80040216`/`0x80090457`) is read, and sent again only when a read proves it absent, within the table's budget (`createInLagWindow`, `recoverRefusedBatch`, `drainLagStatuses`; a spent check is the original refusal, its halt saying the build may be run again); the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; `makeRunner`, whose runner stops the phase at the next step once the run's throttle budget has refused a wait (`stopIfRefused`: `run` and each item of its `mapLimit`; a step that pays the name column length a table the run created is owed is let through; a step taken up again later in its phase — a status reason its table's lag deferred — keeps its number and names the outcome it replaces, so every step stays within the plan's total and the summary counts it once); and `mapLimit`, the bounded fan-out every parallel path reusesretry-policy.js ← when the build runs a failed phase again, decided from what the SERVICE said and never from what the maker named: `RETRY` (`NEVER` — a refusal of the spec, an identity or ownership conflict, an approval, a prerequisite, a file on the maker's machine; `SERVICE` — what the failure it wraps says), `judgeFailure(error, { declares })` (an explicit `transient: false` anywhere along the causes wins; then the HTTP status 429, 502, 503, 504; then a condition the service names by the `error.code` of its answer — `TRANSIENT_SERVICE_CODES`, a SQL deadlock victim (the generic SQL error code `0x80044150` AND the platform's `Sql Number: 1205` — the last SQL number the answer gives — in the service's own answer, `isDeadlockVictimAnswer`), and the lag of a column the spec creates (`declares`) — on any status; then a timeout or reset of the transport (by Node's own code when the error carries one, by its words only when it has none); then **any other HTTP status is final** whatever the answer's words say; then the SDK's or plugin's own type — a refusal, whatever it quotes (bar the SDK's wrapper of a failed publish, read by the status of the answer it embeds); then, only for a failure that carries no status at all, the service's own words, never a halt's message), `throttleAskOf` (what a throttled failure asks of the next send: `retryAfterMs` and `retryNotBefore`), `retryPolicyFor` / `retryFrom` (the policy a halt is raised with), `refusal` / `serviceFailure` (the errors the engine itself makes; `serviceFailure`'s `answered` records the OData error of an answer the engine read with a request of its own — its `code` and `message`, nothing else — and the rule reads that code as it reads the SDK's) and `withCause` (the failure a by-value result carries); `BuildHalt` takes `retry`, `retryText` and `statusCode`; build-model-app.js `isTransientHalt` is its one reader, and `tests/halt-retry-policy.test.js` holds every halt in the sources to a row of its table; an error that WRAPS the failure it carries as its `cause` (`CAUSE_WRAPPER_CODES`: `WEB_RESOURCE_UNVERIFIED`) is judged by that cause, read whether or not it is enumerable, and never by its own code or words — and one that carries no cause is run againthrottle-budget.js ← the budget a run allows itself for the waiting it does when a service throttles — five minutes, shared by the HTTP client's waits before it sends a throttled read, publish, delete or column create again (`deps.throttle` of `lib/sdk-http-client.js`), the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and the build's own waits before it runs a phase again (the upload script makes one for its run) (`makeThrottleBudget({ totalMs, warn })`: `fits(ms, at)` and `spend(ms, at)`, which answers what the wait added — a wait the client PLACES on the clock (`at`) adds only what runs past the waits placed before it, because requests sent together are throttled together and wake together, while the backend's and the build's, which wait one at a time, place nothing and add whole; `announce` for a wait longer than five seconds, on the `warn` seam the build wires to stderr; `decline` / `declined`, where the client says that a wait did not fit — in the words of `refusedWait`: what the service asked and that the request was not sent again, with no advice on what to run, because a refused request can follow a write that committed — and the build's retry loop and the engine's runner read it (the loop to stop with the halt, the runner so that no step starts after it), since the answer the client hands back carries nothing of what the service asked; `note`; `waitDoesNotFit`, the sentence of the `throttle-budget-exhausted` halt: what the service asked, how much is spent, that a later run of the same command continues); it only counts, each layer waits with its own seam. What is not drawn from it is a wait that is not for a throttle — a 5xx, a reset connection, a deadlock victim's re-send — and the waits of a client given no budgetprovision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, `autoNumberFormatProblem` and `requiredValueProblem`, so a name-column length, an AutoNumber column with no format and a `required` that is not `true`, `false` or `"recommended"` are refused here exactly as in `validateAppSpec`)@@ -2636,6 +2714,7 @@ scripts/cli-failure.js ← how a CLI child failed (timeout / missing / failed), the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out; `commandArg` writes an argument of a command a message tells you (or the agent) to paste so that, run from PowerShell (Windows PowerShell 5.1 or PowerShell 7) or a POSIX shell, the program gets it unchanged as one argument — bare when it is plain, single-quoted otherwise (a path from an untrusted checkout can hold `;`, `$(…)` or backticks) — or not at all when no spelling does that in every one of those shells: a quote or a line break, and the values Windows PowerShell changes on their way to a native program (a `"`, white space with a final `\`, the empty value) or both PowerShells read as the stop-parsing token (`--%`), all measured. `commandArgOrPlaceholder` then writes a placeholder and names the value outside the commandnearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators, `fieldOptions` keys)compare-text.js ← `compareText`, the text order for any list a script writes and a diff between two runs then reads: UTF-16 code units after lower-casing, the raw text breaking a tie; never `localeCompare`, whose order follows the host's ICU locale and version (the download's lists use it)+ own-keys.js ← `ownValue(map, key)`: a map keyed by a name a maker writes freely or a service returns (a dashboard's, a page's key, a persona's, a status reason's label) answers only an entry it holds as its OWN — a name can be `__proto__`, `constructor` or `toString`, which a plain object answers with an inherited member. The rule beside it: a map BUILT from such names is a null-prototype object (`Object.create(null)`), so every name, `__proto__` included, is stored as an entry; JSON.stringify writes it as it writes a plain objectlcid-cultures.js ← pure: a Windows language id (LCID) → culture code and right-to-left, from a table of Windows' own culture data (what `pac` printed; the SDK reports numbers only, and no Intl API maps an LCID); a language id with no entry stays numeric and is reported, never guessed (`list-languages.js`)supported-dependencies.js ← Single source of truth for runtime + dev deps versionsfeature-flags.js ← Feature flag probe with fail-closed fallback + Custom API script backstop@@ -2663,20 +2742,21 @@ scripts/app-source-path.js ← shared lexical + realpath confinement for app source reads/uploads and hashespage-ownership-records.js ← local CREATE receipts and pre-delete ownership records, scoped to app/key/id; and the `pending` records of a page create that was started and not acknowledged (written before the create is sent, under the id it will use, with the name and the SHA-256 of the source it sends — one per create sent under the id; intent, never ownership: `readPageOwnership` does not see it, `readPendingCreations` / `completePendingCreations` settle it, and only evidence settles it — an acknowledged create, a page proven to be the one sent, a teardown that deleted the page — never an absence from a listing)page-publish-records.js ← `page-published.<hash>.json`, one file per app and environment in the build workspace: per page, the hash of the content (`contentFingerprint`) it was last PUBLISHED with and the version number of every one of its file rows and of its own row (the plain reads `genpage.fileVersions` and `genpage.projectVersions`), written only after a publish seen to take effect, and with versions only when they were read on both sides of a read-back of the page's published copy (`genpage.publishedDiffers`), were the same set, and the copy held the content and the compiled output the draft held when it was published (`runtimeSha256`). The build hands the hash back to `genpage.update` as `publishedFingerprint` only for a page whose rows read now are exactly the recorded set at the recorded versions (`sameFileVersions`), so an unchanged page is not published again and a page published, renamed or saved from elsewhere is; a cache, never an authority — anything missing, damaged, for other content, without versions or with a moved version reads as "not known to be published" and costs one publish, and the schema (3) is the proof's version: a record of an earlier schema is read for its hashes and skips nothing; it grants and blocks nothing (`readPublishedPages` never throws, `writePublishedPages` failing is one warning)- web-resource-records.js ← `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace: the web resources this workspace's builds wrote and could not confirm were published (`WEB_RESOURCE_UNVERIFIED`), by name and id. `openUnconfirmedWebResources` is a run's view of it (`idOf`, `note`, `clear`; it never throws: a record it cannot read is "nothing recorded", said once, and a run with no workspace records nothing). A name it holds is written again by id by the next run (sdk-build.js `writeOwnedWebResource`, `persistPageManifest`) instead of being reused untouched; the entry is cleared once that write verified and the row is in the solution. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, so builds sharing the workspace keep each other's entries: a note never replaces an entry with another row's id that another build recorded since this run read the file (said once; `note` answers false; a note of the same row is a later unconfirmed write of it and takes the entry's place with a revision of its own), and a clear removes only the entry its run knows — its id AND the revision of the note that made it (`revisions`, written beside the name-to-id map), so a later unconfirmed write of the same row that another build noted survives a clear by a build that verified an earlier one; an entry written without a revision is matched by its id, as before+ web-resource-records.js ← `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace: the web resources this workspace's builds wrote and could not confirm were published (`WEB_RESOURCE_UNVERIFIED`), by name and id. `openUnconfirmedWebResources` is a run's view of it (`idOf`, `note`, `clear`; it never throws: a record it cannot read is "nothing recorded", said once, and a run with no workspace records nothing). A name it holds is written again by id by the next run (sdk-build.js `writeOwnedWebResource`) instead of being reused untouched — the page manifest only where its published copy is not what that run wants, and kept where it is (`persistPageManifest`); the entry is cleared once the row is confirmed (that write verified, or the manifest's published copy found right) and is in the solution. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, so builds sharing the workspace keep each other's entries: a note never replaces an entry with another row's id that another build recorded since this run read the file (said once; `note` answers false; a note of the same row is a later unconfirmed write of it and takes the entry's place with a revision of its own), and a clear removes only the entry its run knows — its id AND the revision of the note that made it (`revisions`, written beside the name-to-id map), so a later unconfirmed write of the same row that another build noted survives a clear by a build that verified an earlier one; an entry written without a revision is matched by its id, as beforedashboard-creation-records.js ← `dashboard-creation.<hash>.json`, one file per environment, app and solution in the build workspace: the dashboards this workspace's builds CREATED and have not yet seen join the solution, by name — the id the create was sent with (the SDK sends the workspace's own id as `systemform.formid`), noted before the push, and the id the push reported when that is another. `openDashboardCreations` is a run's view of it (`idsOf`, `note`, `observe`, `clear`, `path`; it never throws: a record it cannot read — an entry it does not write included — is "nothing recorded" and is never written over or removed, said once; a run with no workspace, environment or solution records nothing). Cleared once the row is in the solution or the build's own undo deleted it; the next run reads each recorded id in the saved layer before any name lookup and adds the row the create made to the solution — after a re-key only the reported one (sdk-build.js `recoverRecordedDashboard`) — never a namesake, never a delete, never teardown authority. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, comparing the whole entry (both ids), so builds sharing the workspace keep each other's entries: `note` never replaces an entry another build recorded or changed since this run read the file (said once), and a note of the id the entry already holds keeps its reported id; `observe` adds only to the entry as its run noted it; `clear` removes only the entry as its run knows it, and answers null when another build has changed it since — when every id it recorded read as absent, `recoverRecordedDashboard` then stops instead of creating a dashboard on the word of the older entry (after the row joined the solution, a changed entry is left and the build goes on)record-lease.js ← the writer lease of a workspace record (`withRecordLease(root, file, change)`): the change runs while `<record file>.lock` is held — the workspace lease protocol (`apply-snapshot-store.js acquireLease`: exclusive create, exclusive reclaim, owner-checked release), stamped and judged as the pages lock is (`process-owner.js`: taken over only from a build proven gone, never by age). A lock another build holds is tried `LEASE_ATTEMPTS` (10) times `LEASE_WAIT_MS` (100 ms) apart and then given up — the change is not made and its record says so once — so a build never hangs on it. Used by `web-resource-records.js` and `dashboard-creation-records.js`; reads take no lease+ app-operation-lease.js ← the local leases that keep two builds of ONE app in ONE workspace from writing at the same time: `withAppBuildLease({ workspaceDir, appUniqueName, buildLease, warn }, operation)` holds `app-build.<sha256 of the lower-cased app unique name>.lock` for one whole apply — the CLI takes it before its auth check, and `buildModelApp`, `runSdkBuild` and `runChangedOnlyApply` take it when called on their own or borrow the opaque capability their caller hands them (`opts.buildLease`; a string, a released capability or one for another app or folder is `build-lease-invalid`); a held lock is `build-locked` at once, with no wait. `acquireAppPagesLease(wsDir, appUnique)` (re-exported from `sdk-build.js`) takes `app-pages.<hash>.lock` and then the legacy `pages-<spelling>.lock` every earlier release takes, lets go of the first when the second refuses, and releases them in reverse order. Every file is taken through `apply-snapshot-store.js acquireLease` (exclusive create, exclusive reclaim, owner-checked release), stamped and judged by `process-owner.js` (taken over only from a build proven gone, never by age), checked with the `safe-fs.js` refusals first (a link or folder at a lock name is that error); a release that cannot confirm its own lock is gone says which file. `applyWorkspaceOf(opts)` is the one default workspace (`<app folder>/.maker-workspace`)source-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" belowsdk-teardown.js ← app-builder teardown engine (planTeardown is pure)sdk-http-client.js ← az-token HttpClient for the vendored SDK; a caller can name requests that are sent exactly once (`sendOnce(method, url)`: no retry on a transport failure, a 429 or 5xx, or a 401 refresh, and none of the replays special to a record delete and a `$batch` either) — `solution-settings.js` does for the three long solution actions; a caller can hand it the run's throttle budget (`deps.throttle`, lib/throttle-budget.js): every wait it takes before it sends a throttled request (HTTP 429, alone or as every operation of a `$batch`) again is then drawn from the budget — the answer's `Retry-After` whole, past the cap of a minute, or the schedule's wait when that is longer, placed on the clock so that requests throttled together are charged once — and a wait that does not fit is not taken: the 429 comes back as it came and the budget is told what the service asked (`decline`); every other wait (a 5xx, a reset connection, a deadlock victim's re-send) keeps its own schedule, and the budget is duck-typed and never loaded here, so the pcf copy, which has none, waits as it always did; an answer that is not a success comes back with the access token taken out of it (and a transport failure's text too, the error that carries Node's code included), a success untouched — the one `scrub` / `scrubAnswer` the Power Apps client uses as well; `needlesOf(token)` and `TOKEN_MARKER` are `lib/output-redaction.js`'s: the one list of texts a scrubber takes out of one token (the token and each of its parts of 24 characters or more) and the one marker, so the client's scrubber and what the process writes are kept free of a token by the same list, and each token the client sends is noted there (`noteToken`); `throttleBackoffMs(attempt, random)` is the capped, jittered schedule every throttled request waits on (1 s, 2 s, 4 s, 8 s, 8 s), exported because the page backend waits out a throttled page write on it (the client never re-sends a page's `$batch`: `lib/genpage-sdk.js` does, a push at a time); `retryAfterMs(headers, now, cap)` and `batchRetryAfterMs(res, now, cap)` cap what a response asks at a minute for the client's own retries, and a caller with a bound of its own passes `Infinity`: the page backend spends it inside the run's budget, the client itself does when it has that budget, and `solution-settings.js` inside the one budget of its import resend; `completeBatchStatus(res)` is the one status a COMPLETE multipart answer reports for every operation (the page backend reads a change set refused as a whole with it); the parser behind it, `isBatchThrottled` and `isBatchDeadlockVictim` is strict — an answer is read only when its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line; a part that declares a change set (`Content-Type: multipart/mixed; boundary=…`) must open and close exactly that boundary before the outer one goes on, a part with no response in it is an operation nobody answered, and a body is as long as the `Content-Length` its response gives, counted by the line breaks the answer has; a part that declares a `Transfer-Encoding` (chunked or any other) is not read at all, whole stream or not — the delimiters around it say nothing of whether its chunk stream is finished, so it never certifies a refusal or a deadlock victim; anything missing or malformed makes the WHOLE answer unproven (an answer that closes its outer boundary and is incomplete inside proves nothing); `isTransientTransportFailure(text, code)` says which failures of the transport are sent again — decided by Node's own error code when `makeRequest` reported one (`TRANSIENT_TRANSPORT_CODES`: `ECONNRESET`, `ETIMEDOUT`, `ESOCKETTIMEDOUT`, `ECONNABORTED`, `EPIPE`, `EAI_AGAIN`; any other code is final whatever the words say) and by the words only when it did not (a certificate's own phrases first): a reset, a timeout, an answer cut off, a temporary DNS failure, the same list `lib/retry-policy.js` calls a blip, and nothing else — a certificate that does not verify (whatever names it quotes), an unknown host and a message nobody recognises return at once; the error it throws carries the code beside the same message (this file is copied into the pcf plugin, so a test holds the two lists equal); a publish (`PublishXml`, `PublishAllXml`) is sent ONCE but for a 401 and a 429 of the service protection limits (`isServiceProtectionRefusal`, `SERVICE_PROTECTION_CODES`: the three codes the api-limits page documents) — never for the customization lock's 429, a 5xx or a failure of the transport — and its deadlock victim is the layer above's to re-send (`isSqlDeadlockVictim` and `DEADLOCK_RESENDS` are exported for `publish-xml.js`). Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`)maker-sdk.js ← the one way a script makes an SDK: the vendored bundle with the vendored TypeScript compiler as its page compiler, and with the client it is handed guarded by `app-header-text.js`; `connectivity: true` (opt-in) also gives the instance the Power Apps service client, so no script wires a credential-carrying client by hand; and the `httpClient` it is given is handed over with the read of the environment's TABLE LIST held to being a list (`lib/collection-answers.js` `guardTableLists`), so every script's `findTables()` meets a failure (`TABLES_UNREADABLE`, an `SdkError`, so `error.code`) where the bundle alone would read a sign-in page, `{}` or `null` as "no tables" — none can forget it; and the `workspaceStorage` it is given is handed over with every text it is asked to write taken clean of the access tokens the process obtained (`lib/output-redaction.js` `guardWorkspaceStorage`: the SDK writes every file of its workspace through `writeTextAtomic`, and the wrapper is the storage in everything else), so a token a service repeated in an answer cannot land in a workspace file. The SDK itself — its errors, its warnings, its results — is exactly what the bundle makes: what a script WRITES is what is cleaned- output-redaction.js ← keeps every access token the process obtained out of everything it WRITES, and out of nothing the service or the SDK made: `noteToken(token)` (called where a token is read from the Azure CLI — `dataverse-auth.js`, both reads — and where `dataverseRequest` and the SDK's HTTP client send one) is the registry, and the first token noted guards the process: `guardStream` wraps `process.stdout.write` and `process.stderr.write` (every `console.*` call, every script's result and warning printer, a library's own output end there; a text cleaned as a string, bytes — a Buffer, a Uint8Array, a string in `base64` or `hex` — masked byte for byte with as many `*` in a copy, the very bytes when they hold none), and `guardFatalErrors` prints — cleaned — what Node itself prints when an error ends the process, which never passes through `process.stderr.write` (only when nothing else handles the error: a test runner's own listener is left alone). `redactOutput(text)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`) and `guardWorkspaceStorage` wraps the SDK's `writeTextAtomic` (`maker-sdk.js`). `redactTokens(text, tokens)` is the matcher: it reads the text as it SPELLS a token, one character at a time — the character itself or an escape of it (`\uXXXX` in either case, `\xXX`, `\/`), with a fold between any two of them (white space, `\r\n` `\t` `\b` and the like as JSON writes them, a run of backslashes before an escape: JSON inside JSON, a stray backslash, a terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not) and an escape that can also be a literal backslash and letters (`\n` before a signature that starts with `n`) read both ways — every needle (the token and each part of 24 characters or more: `needlesOf`, and its base64, percent-encoded and HTML spellings: `spellingsOf`) in ONE linear pass with a bounded set of readings beside it (a text that would need more is refused: the writer fails closed), the whole span from the token's first character to its last becoming `<token>`, so that JSON that was written is JSON still. It never touches an error, a warning or an answer: the SDK's errors keep every word the SDK gave them, and the strict `$batch` readers see the bytes the service sent. The beginning of a needle, 24 characters or more, goes too where a text says it was cut (`util.inspect`'s `... N more characters`, an ellipsis) and at the end of a whole text the process writes, and the end of a needle at its start (`redactOutput`; `redactTokens(text, tokens, { edges: true })`); `maskTokenBytes(bytes, tokens)` is the same for bytes. Not read: a token another process obtained, a piece of a token shorter than 24 characters, a piece from the middle of one, and bytes given to a file writer. `makeWritesBlocking(...streams)` makes a stream's writes blocking for the last writes of a process — `emitResult`, `guardFatalErrors`, and every printer of a script's own that ends the process after writing (a result, a usage error, a last-resort handler, a hook's message, the warnings a script prints right before its result) — because on Linux and macOS a pipe's writes are queued and `process.exit` does not wait for them, so a large result reached its reader cut short (`tests/result-whole-before-exit.test.js`, `tests/printers-whole-before-exit.test.js`: each process records the order in which it makes its streams blocking and writes to them — the check that fails on every runtime for a printer without the call — and the text a reader receives; nothing else about the stream changes, the guard included). `tests/exit-writes-inventory.test.js` is a syntactic tripwire, not a proof: it fails on a new exit with no such call before it in its block (or that is not listed with the bound that makes it safe: it writes nothing, or a constant), and on a call that comes after a write of its block or leaves out a stream written before the exit; it does not follow calls or control flow, and does not see writes made in an enclosing block, before an `await`, or through a helper. Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`), where it also cleans `pcf-push.js`'s receipt and guards the SDK workspace `makePcfSdk` makes+ output-redaction.js ← keeps every access token the process obtained out of everything it WRITES, and out of nothing the service or the SDK made: `noteToken(token)` (called where a token is read from the Azure CLI — `dataverse-auth.js`, both reads — and where `dataverseRequest` and the SDK's HTTP client send one) is the registry, and the first token noted guards the process: `guardStream` wraps `process.stdout.write` and `process.stderr.write` (every `console.*` call, every script's result and warning printer, a library's own output end there; a text cleaned as a string, bytes — a Buffer, a Uint8Array, a string in `base64` or `hex` — masked byte for byte with as many `*` in a copy, the very bytes when they hold none), and `guardFatalErrors` prints — cleaned — what Node itself prints when an error ends the process, which never passes through `process.stderr.write` (only when nothing else handles the error: a test runner's own listener is left alone). `redactFileData(data, opts)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`: a text cleaned as `redactOutput(text)` cleans it; bytes — every ArrayBuffer view: a Buffer, any typed array, a DataView — and a string given with a `hex`, `base64` or `base64url` encoding read as the bytes the file gets, a hit masked with as many `*` in a copy; data it cannot read with a token noted is refused before anything is written) and `guardWorkspaceStorage` wraps the SDK's `writeTextAtomic` (`maker-sdk.js`). `redactTokens(text, tokens)` is the matcher: it reads the text as it SPELLS a token, one character at a time — the character itself or an escape of it (`\uXXXX` in either case, `\xXX`, `\/`), with a fold between any two of them (white space, `\r\n` `\t` `\b` and the like as JSON writes them, a run of backslashes before an escape: JSON inside JSON, a stray backslash, a terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not) and an escape that can also be a literal backslash and letters (`\n` before a signature that starts with `n`) read both ways — every needle (the token and each part of 24 characters or more: `needlesOf`, and the base64 of each of those, percent-encoded and HTML spellings: `spellingsOf`) in ONE linear pass with a bounded set of readings beside it (a text that would need more is refused: the writer fails closed), the whole span from the token's first character to its last becoming `<token>`, so that JSON that was written is JSON still. It never touches an error, a warning or an answer: the SDK's errors keep every word the SDK gave them, and the strict `$batch` readers see the bytes the service sent. The beginning of a needle, 24 characters or more, goes too where a text says it was cut (`util.inspect`'s `... N more characters`, an ellipsis) and at the end of a whole text the process writes, and the end of a needle at its start (`redactOutput`; `redactTokens(text, tokens, { edges: true })`); `maskTokenBytes(bytes, tokens)` is the same for bytes. Each write is read on its own and nothing is held back for the next one. Not read: a token another process obtained; a piece of a token shorter than 24 characters (the shorter piece of a token written in two); a piece from the middle of one (a token written in three pieces or more); the piece an escape cut between two writes leaves on its far side when it is shorter than 24 characters; base64 of a piece that is not a whole part; and a token split between two appends to a file (the module's header lists them all). `makeWritesBlocking(...streams)` makes a stream's writes blocking for the last writes of a process — `emitResult`, `guardFatalErrors`, and every printer of a script's own that ends the process after writing (a result, a usage error, a last-resort handler, a hook's message, the warnings a script prints right before its result) — because on Linux and macOS a pipe's writes are queued and `process.exit` does not wait for them, so a large result reached its reader cut short (`tests/result-whole-before-exit.test.js`, `tests/printers-whole-before-exit.test.js`: each process records the order in which it makes its streams blocking and writes to them — the check that fails on every runtime for a printer without the call — and the text a reader receives; nothing else about the stream changes, the guard included). `tests/exit-writes-inventory.test.js` is a syntactic tripwire, not a proof: it fails on a new exit with no such call before it in its block (or that is not listed with the bound that makes it safe: it writes nothing, or a constant), and on a call that comes after a write of its block or leaves out a stream written before the exit; it does not follow calls or control flow, and does not see writes made in an enclosing block, before an `await`, or through a helper. Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`), where it also cleans `pcf-push.js`'s receipt and guards the SDK workspace `makePcfSdk` makesapp-header-text.js ← an app's header texts (`name`, `description`) held to plain text at the HTTP client every SDK is made with (wired in `maker-sdk.js`): a PATCH of an app module row that carries one that is not a string is refused before any byte is sent — `APP_HEADER_NOT_PLAIN_TEXT`, an `SdkError` marked `transient: false` — whether it is the SDK's `patch`, a `patchRaw`, or a PATCH inside a raw change set (`postRaw` / `post` to `$batch`), because the SDK writes every text its workspace copy holds whenever its own comparison read of the header cannot be made (503, 403, a thrown error, an empty 200). The build takes such a text off the copy before its push, so this is the last line of defence, for a push of a copy it did not clean. A batch that names the app module table and cannot be read is refused too. A delegating Proxy: every member it does not judge runs on the client itself. Also how such a text reads in a message (`describeHeldAppText`), which the guard's refusals sharebatch-request.js ← a multipart `$batch` REQUEST read the way the service reads it — `readBatchRequest(text, contentType)`: the parts of the boundary the Content-Type declares, a change set one level down, one HTTP request in each part, answered as `{ operations: [{ method, target, contentId, body }] }`, or `{ problem }` for text it cannot read with confidence (cut short, another boundary, a part that is not a request). A body is only ever text: a line in it that looks like a request is not an operation. `app-header-text.js` reads a raw change set with itthrowaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote outcollection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not editedtemp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries- process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the pages lock, the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)+ process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the build lock and the pages lock (`app-operation-lease.js`), the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged; whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the userpower-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)sdk-first.js ← the rule `list-connections.js`, `connector.js` and `solution-settings.js` share: read through the SDK, and through `pac` for the SDK's typed refusals (`sdkFirst`, `CONNECTIVITY_REFUSALS`) — an error counts only when it IS the bundle's `SdkError` (an HTTP body that carries a refusal's code does not); any other failure is thrown with the SDK's own code. An environment outside the Public cloud is judged from its host first (`connectivityCloudOf`, pinned to the bundle by a table of hosts) and answered by `pac` at once, with the code the SDK would give. What the SDK could not clean up before it refused (`readCleanupWarnings`: a staged copy of the package it could not delete, with its upload id) is carried across the fallback — as `warnings` on the answer, or attached to the error `pac` throws when it fails — so `solution-settings.js` shows it for `template` and `import` alike (an import's, sanitized once)@@ -2700,7 +2780,7 @@ scripts/genpage-subarea.js ← `genPageSubArea(base, genPageId)`, `genPageSubAreaId(pageId)` and `GENPAGE_DEFAULT_VECTOR_ICON` (the icon the platform gives a page entry that names none, so a rebuild does not take it for a designer edit): the one shape a generative page has as a sub-area of an app's navigation (`{ ...base, type: 'GenPage', genPageId }`). The build's `appDef` and `placeInApp` — and a script that creates an app around a first page — all build it hereapp-component-scope.js ← what an edit of an app that is not about its components may ADD to them, held at the SDK's transport (`makeAppComponentScope()`: `wrap(httpClient)`, `limit(appId, { views }, work)`). Every `pushArtifact('app', …)` of an existing app (the bundle's `appApi.update`) PATCHes the sitemap and then posts ONE AddAppComponents whose list it DERIVES: for each Entity sub-area the table, EVERY active Main form, EVERY active public view and EVERY chart, for each DashBoard sub-area the dashboard — whether or not the app has them, and `components.mainFormsByTable` narrows the Main forms alone. AddAppComponents only adds, so a page edit that went through it put back what the app's maker had taken out, and its publish made it live. The bundle is never patched and cannot be told to skip the derivation, so the page backend (`placeInApp`, `removeFromApp`) keeps the SDK's sitemap write and has the post limited where it leaves the process: to the views the edit pins, and — when none is left — not sent at all (the SDK is answered with the service's 204). The action is found by the PATH of the address, percent-decoded as a whole before its trailing slashes are dropped and its last segment is read (a query string or fragment that mentions the name is not it; `AddAppComponents%2F` and `%41ddAppComponents` are it, in another spelling), and every POST is read ONCE while an edit is open — its address as text, its body as the plugin's transport takes it (text as it is, bytes copied, an object serialized as the transport serializes it and read back as plain data) — decided on in that CANONICAL form and sent in that form in every branch (the action it cuts, another app's request, a request to another address, a batch), never the object, bytes or address the caller holds, which the transport would read again: a `toJSON`, a getter or an address that answers differently the second time cannot undo the limit, and JSON text and the UTF-8 bytes of it are parsed for the action. While an edit is open, a request that IS the action in a shape the limit does not read — another spelling of the name, an address or path that cannot be decoded, a body that is JSON text (for a `post`), is not JSON or cannot be serialized, or has no list — or that does not carry every view the edit pins (a view named as a reference, or left out), or a `$batch` that may carry the action, through `post` and `postRaw` alike (a part of a batch cannot be limited: one classifier reads a multipart batch request line by line and a JSON batch entry by entry, each address as any address is read, and a JSON batch after its JSON is), is REFUSED with the bundle's `SdkError` `APP_COMPONENTS_NOT_LIMITED`: not sent whole and not answered as done. A raw POST (`postRaw`: a real POST whose body the transport does not touch, which the bundle uses for `$batch` only) is told by its address exactly as a `post` is, so the action cannot escape the limit by the method that carries it: one to the action's address is limited as the object form is when its body is JSON text of the same object, the UTF-8 bytes of it or an object, and what goes on is a form the transport sends as it is — JSON text for text and for bytes (the transport would send a Buffer as `{"type":"Buffer",…}`), the plain object for an object — with any `Content-Length` the caller declared, in whatever spelling, rewritten to one header with the exact length of what is written; it is refused when its body cannot be read that way. The SDK reports that as a warning of the push ("one or more components were not pinned"), so the sitemap the edit saved stays saved and nothing unlimited reaches the app. A page is a GenPage sub-area, which needs nothing from the app's components, and everything the SDK derives belongs to a sub-area that was there before the edit. The build owns the whole app and never opens an edit; an SDK lent to the backend keeps its owner's transport, and is not limited. Pinned against the real bundle by `genpage-app-edit-real-bundle.test.js` — the re-vendor tripwire for the request's shape, which also pushes the app through the limit — over the plugin's own transport, under a fake service that reads the wire (the body as JSON, a `Content-Length` that must be its length) — with that request changed, or sent through the raw method, to see the limit and the refusal as the user doesgenpage-base.js ← base-marker hash, compare, and read/write (sibling dotfile of the code file; no environment URL; `appId` is optional — a page created before any app held it is recorded with the page alone, and the first update that names the app it was then placed in goes ahead on that marker and records the app; `unfinished` (`publish` or `place`) is set only by an upload that CREATED the page and did not finish it, and is what lets `genpage-upload.js --page-id` finish exactly that page — it is cleared when the page is finished, and `genpage-base.js record` never writes it)- safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Every text it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactOutput`; bytes are written as they are): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callers+ safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Everything it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactFileData`: a text as a text; bytes — any ArrayBuffer view, or a string given with a `hex`, `base64` or `base64url` encoding — masked with as many `*`, and data it cannot read refused before anything is written): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callershydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)verify-spec.js ← spec-vs-deployed reconciliation core (checks are ordered tasks on a pool of 4)status-reasons-keys.js ← a table's status reasons (with their states) and alternate keys (with their columns), one narrow read each (`readStatusReasons`, `readAlternateKeys`: `{ state: 'ok' | 'absent' | 'error' }`, never a throw), and the checks of the declared ones against them (`statusReasonChecks`, held to the build's own `statusReasonTargets`; `alternateKeyChecks`) — verify's `status-reason` and `alternate-key` checks@@ -2728,7 +2808,7 @@ scripts/content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only); `recordedContentSha` reads a page's recorded hash back (the build's pages phase compares it with the page's source to tell an unchanged page from a changed one)classify-changes.js ← changed-only: classify a spec diff → fast (page-content) | full | noop + sticky debtapply-snapshot.js ← changed-only: pure eligibility state machine (identity bind, debt, tombstone, generation CAS)- apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's and the page ownership and publish records', with the access tokens the process obtained taken out of its text, `lib/output-redaction.js`) + workspace lease + invalidate/claim/tombstone/delete + distrust marker. `acquireLease` is the one exclusive-create-and-reclaim protocol for a lock file in a workspace: the snapshot lease (`apply-snapshot.lock`) and the build's pages lock (`pages-<app>.lock`, `sdk-build.js` `acquireAppPagesLease`) both use it, the pages lock with the owner record of `process-owner.js` and a stricter rule for "stale" — a lock left by a build that was killed is released by the next build, which says so (`released the pages lock for '<app>': the build that held it (pid …) is no longer running`), but only when that build is provably gone; a lock whose pid runs, another machine's, one with no readable record, is refused in the words it always had, and none is ever taken by age+ apply-snapshot-store.js ← changed-only: atomic snapshot write (writeFileAtomic, also the baseline's and the page ownership and publish records', with the access tokens the process obtained taken out of what it writes — a text, or bytes masked with as many `*` — `lib/output-redaction.js` `redactFileData`) + workspace lease + invalidate/claim/tombstone/delete + distrust marker. `acquireLease` is the one exclusive-create-and-reclaim protocol for a lock file in a workspace: the snapshot lease (`apply-snapshot.lock`) and the build's pages lock (`pages-<app>.lock`, `sdk-build.js` `acquireAppPagesLease`) both use it, the pages lock with the owner record of `process-owner.js` and a stricter rule for "stale" — a lock left by a build that was killed is released by the next build, which says so (`released the pages lock for '<app>': the build that held it (pid …) is no longer running`), but only when that build is provably gone; a lock whose pid runs, another machine's, one with no readable record, is refused in the words it always had, and none is ever taken by ageapply-snapshot-index.js ← changed-only: build result.created → snapshot artifact mapworkspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanupworkspace-binding.js ← a persistent `.maker-workspace` belongs to the environment it was first opened for (only `--apply` opens it; a dry run uses a temporary workspace): turns the SDK's `WORKSPACE_ORG_MISMATCH`, and a manifest the JSON parser rejects, into the build's halt (both environments as origins, the safe remedies — the teardown one only for another environment that was built in, with the folder printed on its own line; a folder that was only opened gets no build-there/teardown advice; a folder with no usable environment is moved aside, not deleted; never clears or re-binds) and into the dry run's warning@@ -2994,7 +3074,42 @@ expression, a loop that stops at the first `>` or `}`) has to skip comments anditself to be complete (a function or class reaches its body; a bare name is one the moduledeclares or imports, not a token that merely appears — the `as` of `import * as React` is not abinding), because a write cut inside its export line balances; any complete `export default` will-do, for overloads. And `endsMidStatement` catches the cuts that leave every bracket balanced: the+do, for overloads. A **generic arrow** is a default export too (`export default <T,>(props: P<T>) => …`,+and after `async`): the `<` is read by the same TypeScript rule as any `<` where an expression starts — type+parameters for `<T,>`, `<T = X>` and `<T extends X>`, after an optional `const` — and any other head is an+element (`<div/>`, `<T>(x) => x`), which is no component and stays refused; the type parameters must close, a+parameter list must follow, then the arrow — at once, or right after a return type that `returnTypeEnd` reads to+its end as TypeScript 5.8's parser reads a type — and a body: a block or what begins an expression, not `;` or a+statement's word (`genericArrowIsComplete`). The return type has to be read, not scanned: it may hold an `=>` of+its own (`(p): (x: T) => T => …`, `new () => T`), so the first `=>` after the colon is not always the arrow's, and+a write cut right after such a type has neither the arrow nor a body; and any word may name a type (`module<T>`,+`namespace`, `declare` — TypeScript reads a type's name as an identifier name), so no word marks the end of one.+Where TypeScript reads `(…)` as a function type is its own rule (`isUnambiguouslyStartOfFunctionType`: `(A) => T`+is one, `(A | B)` is not, and nor is a parenthesised object type whose key is an index signature's or a mapped+type's — `({ [key: string]: T })`, `({ [K in keyof T]: boolean })` — since that key holds no expression and so+makes no binding pattern, where `({ [key]: v })` and `({ [K in T]: v })` do), and a return type nested deeper than+any page (200 levels) is refused rather than read. **Known limit:** a default value in a binding pattern of a+function type's parameter is passed over to the next `,` or closing bracket at its own level, and the comma between+a generic call's type arguments is taken for one (`({ a = f<T, U>() }) => R`): the pattern then reads as none, the+parentheses as a parenthesised type and the function type's `=>` as the arrow, so a write cut right after such a+return type (`export default <T,>(p: T): ({ a = f<T,T>() }) => T`) is accepted — the page compile refuses it+(TypeScript: `'=>' expected`), and `source-literals.test.js` pins it. With the call in parentheses the cut is refused.+**Known limits, refused although TypeScript parses them** (both rare; 2.18.0 refused every synchronous generic-arrow+default export, so neither is a regression there; it did admit the `async` forms of both — it took any `async` arrow+text with an `=>` and something after it — and those are now refused too), pinned in `source-literals.test.js`:+- a mapped type whose key type is in parentheses, inside a parenthesised return type — `(p): ({ [K in (keyof T)]: boolean }) => …`,+ and so `((keyof T))`, `(keyof T) as K` and a parenthesised conditional key type. The key's reading takes any group in+ parentheses for an operand, so `K in (keyof T)` reads as an expression, the braces as a binding pattern, the parentheses+ as a function type's parameters and the arrow as that function type's, and the page as cut off. Write `[K in keyof T]`,+ drop the parentheses around the return type (`(p): { [K in (keyof T)]: boolean } => …`), or name the type with a type+ alias (`type Flags<T> = { [K in (keyof T)]: boolean }`, then `(p): Flags<T> => …`);+- a return type that is a function type whose parameter has a computed key the reading does not know — one that starts with+ a regular expression, `({ [/key/.source]: value }: Record<string, T>) => …` — and whose own return type starts with a+ leading `|` (`=> | typeof value | null`). The key is taken for no expression, the parentheses for a parenthesised type,+ the function type's `=>` for the arrow, and the `|` after it begins no body. Drop the leading `|`, write the key as a name+ or a string, or name the function type with a type alias.+The export pattern once took no `<` after `default`, and every such page was refused as having no default export.+And `endsMidStatement` catches the cuts that leave every bracket balanced: thelexer reports when a file stops inside a string, template, comment or JSX element, and a filemay not end on a token that needs more (`a +`, `React.`, `=>`). Both gates run all three checks.A backslash continues a string over one line terminator, and CR LF is **one** terminator@@ -3920,22 +4035,24 @@ client sends it) out of everything the process writes, and changes nothing else|---|---|| stdout and stderr — every `console.*` call, every script's result printer and warning printer, the progress lines, a library's own output, the SDK bundle's | `process.stdout.write` and `process.stderr.write` are wrapped when the first token is noted (a process that has none is untouched); a text is cleaned as a string, bytes are masked byte for byte in a copy (as many `*`, so a frame keeps its length). `emitResult` cleans its own text too, so a result is clean where a caller has replaced `write` || what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection) — it never passes through `write` | a handler prints it, cleaned, with the same exit status, when nothing else handles the error (a test runner has its own listener and is left alone) |-| the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, a plan, the settings template | `writeFileSafe` and `appendFileSafe` (`lib/safe-fs.js`) clean the text they write |-| the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records | `writeFileAtomic` (`lib/apply-snapshot-store.js`) cleans the text it writes |+| the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, a plan, the settings template | `writeFileSafe` and `appendFileSafe` (`lib/safe-fs.js`) clean the text they write and mask every ArrayBuffer view they are given (a Buffer, any typed array, a DataView: the bytes it covers, with as many `*`, in a copy); a string written as `hex`, `base64` or `base64url` is masked as the bytes that encoding produces (`redactFileData`). An append is read on its own |+| the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records | `writeFileAtomic` (`lib/apply-snapshot-store.js`) cleans the text it writes, and masks a view it is given the same way || every file of the SDK's workspace — artifacts, their metadata, the manifest | the SDK writes them through `writeTextAtomic` and through nothing else; `lib/maker-sdk.js`, the one factory, wraps the storage it is given |`output-token-writers.test.js` lists every other write of file content in the plugin and says why none of them can carry a token (each writes what the plugin made itself or a person gave it, or runs in a process that obtainsno token), so a new writer fails there until it is classified; it also pins that the one raw write to a descriptor is `solution-settings.js`'s own, and that no script pipes a child's output to a stream. A token is looked for asthe text SPELLS it: one character at a time, each the character itself or an escape of it, with a fold between any two (white space, `\r\n` as JSON writes it, a run of backslashes for JSON inside JSON, a stray backslash, aterminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not), and an escape that can also be a literal backslash and its letters (`\n` before a part that starts-with `n`) read both ways — in one linear pass over the text, every needle (the token, each of its parts of 24 characters or more, and its other spellings: base64 at each of the three byte alignments, standard and URL-safe, and the-percent-encoded and HTML spellings where they differ from it) at once, with a bounded set of the second readings beside it (a text that would need more is refused, and the writer fails closed: a stream writes a notice, a+with `n`) read both ways — in one linear pass over the text, every needle (the token, each of its parts of 24 characters or more, and its other spellings: the base64 of the token and of each of those parts at each of the three byte+alignments, standard and URL-safe — the characters made of its own bits, not a neighbour's or the padding — and the percent-encoded and HTML spellings where they differ from it) at once, with a bounded set of the second readings beside it (a text that would need more is refused, and the writer fails closed: a stream writes a notice, afile is not written), the whole span becoming `<token>` so that JSON that was written is JSON still. Where a text says it was cut (`util.inspect` prints at most 10,000 characters of a string and then `... N morecharacters`; an ellipsis, `...` or `…`), the run before it that begins a needle — 24 characters or more — goes too; and a whole text the process writes loses such a run at its end, and the end of a needle at its start(a token written in two pieces: nothing is held back for the next write; an escape cut between the two writes — `\` and `/`, `\u00` and `73` — is kept whole,because a guarded stream remembers the few characters of it, so JSON written in two pieces is JSON together). Bytes a stream is given (a Buffer, a Uint8Array, a string in `base64` or `hex`) are read byte for byte and each hit is masked with as many `*` in-a copy, so a test runner's frames keep their lengths; bytes that hold none are the very object. Not read: a token another process obtained, a piece of a token shorter than 24 characters (the shorter piece of a token written-in two), a piece from the middle of one, other spellings, a cut inside bytes, and bytes given to a file writer (the module's header lists them). Observe the boundary at the process's descriptors and files — `output-token-boundary.test.js` runs real processes (`tests/helpers/token-boundary-child.js`), in colours too — and not by replacing `process.stderr.write` in a+a copy, so a test runner's frames keep their lengths; bytes that hold none are the very object. Not read: a token another process obtained; a piece of a token shorter than 24 characters (the shorter piece of a token written+in two); a piece from the middle of one (a token written in three pieces or more — each write is read on its own); the piece an escape cut between two writes leaves on its far side when it is shorter than 24 characters;+other spellings — base64 of a piece that is not a whole part, hex, a numeric entity for each character, a partial percent-encoding, a token spelled backwards; a cut inside bytes; what a child process writes, the files listed+as handed on as they are, and a file the SDK writes other than through `writeTextAtomic`; a token split between two appends to a file (the module's header lists them). Observe the boundary at the process's descriptors and files — `output-token-boundary.test.js` runs real processes (`tests/helpers/token-boundary-child.js`), in colours too — and not by replacing `process.stderr.write` in aprocess of your own, which replaces the guard itself. `output-redaction.test.js` holds the matcher (against an exact reference that follows every reading over random spellings, JSON validity, cost on a large text and on texts made of nothing but escapes), the registry and the guards,`output-token-real-bundle.test.js` the real bundle and the production client (the SDK's error is the SDK's own; the answer reaches the SDK byte for byte as the service sent it; a page write whose refusal proof and sends arethose of a client that takes nothing out). `solution-settings.js` keeps its own guard on what it writes (below), which stacks with this one. The pcf plugin carries the copy of the module and notes the tokens it reads; its@@ -5131,7 +5248,7 @@ real bundle, because a stub stays green through a change in the SDK's own rule.with the kept steps, not the deleted ones, as its own step line does (`teardown-row-summary-removal.test.js` holds allof it over the real bundle). The table delete that follows reports the dependency if the skill row is still there, anda model left behind blocks only a later row summary for the same table, by name.-- **A web resource whose publication the SDK cannot confirm is recorded, put in the solution, and written again by the+- **A web resource whose publication the SDK cannot confirm is recorded, put in the solution, and recovered by thenext run** (`scripts/tests/web-resource-unconfirmed.test.js`). The SDK reads a web resource's PUBLISHED content backafter every create and every content write it publishes — one GET per write (the lifecycle matrix's first build readsfour more) — and throws `WEB_RESOURCE_UNVERIFIED` when the publish failed or the read-back could not confirm the@@ -5142,9 +5259,10 @@ real bundle, because a stub stays green through a change in the SDK's own rule.and records it in `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace(`lib/web-resource-records.js`), adds it to the solution as the success path does, and stops with the SDK's words(the row, its id, why it is unconfirmed) and the build's: UNCONFIRMED, not lost — run the build again. The run that- follows — the build's own re-run of the halt, and a new invocation on the same workspace — writes the content again- by id (`updateWebResource`, which publishes and reads it back again) and clears the entry once that verified and the- row is in the solution — only the entry that run knows, its id and the revision of the note that made it, so a later+ follows — the build's own re-run of the halt, and a new invocation on the same workspace — writes a spec web+ resource's or the icon's content again by id (`updateWebResource`, which publishes and reads it back again), and+ the page manifest's only where its published copy is not what the run wants (below), and clears the entry once the+ row is confirmed and in the solution — only the entry that run knows, its id and the revision of the note that made it, so a laterunconfirmed write of the same row that another build sharing the workspace recorded meanwhile stays for the next run;a row that is gone by then is created again only if no conflicting replacement was found.A receipt whose id and a live row's name disagree, or whose name now belongs to another id, stops recovery without@@ -5152,9 +5270,13 @@ real bundle, because a stub stays green through a change in the SDK's own rule.A web resource of that name the record does nothold — another maker's, or one whose write was confirmed — is reused untouched, as before. The page manifest's owndedup compares with its PUBLISHED copy (what `readPageManifest` reads), so an update whose publication was not- confirmed is written again whenever that copy is still old; the record supplies the id of a manifest created and never- published, which no plain read finds (assumed, not measured). The pages a halted run created are bound by their- creation receipts, so none is created twice. The build's retry reads the error as a wrapper of its cause+ confirmed is written again whenever that copy is still old; the record supplies the id of a manifest that no plain read+ finds — assumed of one created and never published, though live, a manifest created and never published (each of its+ publishes refused) was read back with that content by the run that followed, the build's own retry. Where that copy+ already holds what the run would write, the manifest is kept as it is and its record cleared (as it was there), so the+ manifest's stop says that the next run reads the published copy and keeps it, or else writes the content again by id;+ the stop for a spec web resource or the icon, which are written again whatever was published, promises the write. The+ pages a halted run created are bound by their creation receipts, so none is created twice. The build's retry reads the error as a wrapper of its cause(`CAUSE_WRAPPER_CODES`, `lib/retry-policy.js`): a lock refusal, a 503 or a reset is run again, a 400, 401, 403, 404,412 or a typed refusal is not, and no cause (the read-back differed or carried no content) is run again. An unchangedrebuild reads one local file and sends nothing more. Recovery of a recorded spec resource or icon checks its publisheddiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 01906a39d..97792fcb1 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,99 @@ 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.+## [2.19.0]++The bundled SDK is unchanged (power-platform-ux a3443479, as in 2.18.0). A `--changed-only` apply no longer stops over the bindings of+a deployed page it leaves alone, a regression of 2.18.0. Two applies of one app no longer run at once in one workspace, the pages lock+no longer depends on how the app's name is spelled, and a new table's column or status reason that Dataverse refuses moments after the+table's create is sent again once a read proves it missing. A name such as `__proto__` or `constructor` works like any other name, a+key over another key's columns stops the build instead of being skipped when the platform answers in English, and a generated page whose+default export is a generic arrow function is accepted. The token guard also takes out the base64 of each part of a token and reads+the bytes the plugin's file writers are given, and the genpage evals grade 17 more of their expectations.++### Changed++- **The genpage evals now grade 17 of the 23 expectations their coverage baseline recorded as ungraded** (#688). A wizard's review+ step and its field labels, components kept at the top level, a search box beside a filter toolbar, shown text through the translate+ helper, choice values named after their RuntimeTypes.ts members, the columns a page's data calls name (against the RuntimeTypes.ts+ the run kept, for evals 1 and 7), an edit that keeps what its plan's Preservation Constraints quote and one that stops when the app+ lists no pages, realistic sample data, and for eval 10 the exact search for its table, its signed-out and WhoAmI 403 blockers shown+ verbatim, and an identity warning shown before the run goes on to the entity-builder, are now checked against the stored evidence.+ Six synthetic fixtures were added for them, and the Layer-1 smoke tier replays eight fixtures, none failing (#630). The six still+ ungraded each have their reason in the baseline: eval 4's Next/Back navigation (proving that a button moves the step needs data-flow+ analysis), three that a correct check would fail on drift the captured fixtures really show (evals 2 and 13, and the batched-state+ rule), eval 15's (it names an input shape `provision-entities.js` refuses) and eval 6's (a person judges it). Two limits of the+ label check are kept: it counts a label whose empty value holds a comment (`{/* hidden */ null}`), and it does not count one written+ only in character references (`Ti…`).++### Fixed++- **A `--changed-only` apply no longer stops over the bindings of a deployed page it leaves alone — a regression of 2.18.0.** It+ checked the connector and Custom API bindings of every page another page navigates to, as if it might create each one, so a conflict+ on a page it leaves alone (`pages-binding-reference-conflict`) stopped the edit of another page. It creates such a page only when+ the page is missing, so it now leaves out a navigation target its last apply recorded as deployed, and checks the changed pages and+ every other target; a recorded target that was deleted since is checked in the pages step, before it is created again. Each binding+ name is read once per attempt: such a target adds no read of a name a changed page shares, and the names only it states are read in+ a query of their own. A full build checks every page, as before.+- **Two applies of one app no longer run at the same time in one workspace.** Two overlapping builds of one app each looked for what+ was missing and created it — measured, two generated app icons in the solution. A second `--apply` of the app in that workspace — a+ full build, its data stage or a `--changed-only` run — is now refused at once, before it sends a request: `build-locked`, on stderr+ (`another build may be applying '<app>' in this workspace`), exit 1 and no JSON on stdout. Run it again once the first has finished.+ A lock is taken over only from a build proven no longer running, never for its age. Not covered: builds in two workspaces or on two+ machines, a build of an earlier release (finish those first), and a teardown, download, `/genpage` or `apps.js` command run beside+ an apply.+- **The pages lock no longer depends on how the app's name is spelled.** On a case-sensitive file system `Contoso_App` and+ `contoso_app` took two locks, so two builds of one app could deploy its pages at once. The lock now ignores case, and the lock file+ earlier releases take is still taken too, so a build of an earlier release that spells the app the same way is still kept out of the+ pages step; one that spells it differently is not.+- **A column or status reason that Dataverse refuses moments after its new table's create no longer stops the first build.** On a+ Spanish environment such a create was refused with HTTP 400 `0x80040216` ("An unexpected error occurred.") or `0x80090457` ("… does+ not exist"), and the next run succeeded. For a table the run has just created, the build now reads whether the column or status+ reason is there and adopts it when it is, and sends it again only once a usable read proves it missing, within about a minute per+ table; a status reason refused this way is added at the end of the data-model step. Any other refusal, and a refusal for a table+ that already existed, is handled as before; a check that runs out stops the build with the original refusal and says to run the+ build again.+- **An alternate key over the columns of another key stops the build whatever language the platform answers in** (`0x80060894`).+ Dataverse allows one key per set of columns. When the platform's message was in English, the build skipped such a key as if it already+ existed — it was never created, and verification then reported it missing — and when the message was in another language it stopped+ with the platform's raw error. That is the language of the platform's message, not of the build or the environment: an environment+ whose only language is Spanish answered in English. The build now reads the table's keys after that refusal: it skips the key only+ when the key over those columns is the declared one, and otherwise stops, naming the existing key and its columns and what to do —+ declare that key's name or delete it if it is a leftover, keep one of two keys the spec declares over the same columns, or first+ reconcile a key whose columns are not those the spec declares for it. When the read cannot tell, the build stops with the platform's+ error.+- **A name that is also a built-in JavaScript property name works like any other name.** `__proto__`, `constructor`, `toString`,+ `hasOwnProperty` and the like can name a dashboard, a persona, a business process flow or a status reason, and `constructor` a page+ key. A dashboard called `__proto__` in the navigation stopped the app step; a new app whose navigation held a page keyed `constructor`+ stopped at the pages step, after the app was created; a persona called `__proto__` named by a flow's or a form's security roles+ stopped the security phase; a sample record could be created with the default status when such a status reason's value had not been+ captured; and such names were left out of the build result and the changed-only snapshot. The App Spec check and the provisioning+ input check refuse a column type such as `constructor` or `toString` as unknown, and the App Spec check reports a form whose table is+ called `constructor` or `__proto__` instead of stopping with a TypeError.+- **A generated page whose default export is a generic arrow function is accepted.** `export default <T,>(props: Props<T>) => …` —+ with a constraint, a `const` type parameter, a default or a return type — compiles, but `/genpage`'s worker-output check and+ `/app-builder`'s page promotion refused it as having "no complete default export". A default export that TypeScript reads as a JSX+ element (`export default <div/>`, or `<T>(x) => x` in a `.tsx` file) is still refused, and so is a generic arrow cut off before its+ body — now an `async` one too, which was let through when cut inside its type parameters, right after a return type that is itself a+ function type, or with no body after its arrow. Two rare return types that TypeScript parses are refused, and so are their `async`+ forms, which 2.18.0 let through: a mapped type whose key type is in parentheses inside a parenthesised return type+ (`(p): ({ [K in (keyof T)]: boolean }) => …`), and a function type whose parameter has a computed key starting with a regular+ expression and whose own return type starts with `|`. Write the key type without its parentheses or drop the leading `|`, or name+ the type with a type alias. A page cut off right after a function-type return type whose parameter's default value holds a generic+ call (`({ a = f<T, U>() }) => R`) passes this check; the deploy compile refuses it.+- **The stop for a page manifest whose publication could not be confirmed says what the next build does.** It said that build writes+ the manifest again by its id; that build keeps the published copy when the copy already holds the content, and otherwise writes it+ again by id. The message for a spec web resource and for the generated app icon is unchanged.+- **An access token is also kept out of the base64 of each of its parts, and out of the bytes the plugin's file writers are given**+ (#757). The base64 of each part of 24 characters or more is taken out like the token — standard and URL-safe, at each of the three+ byte alignments — and what `writeFileSafe`, `appendFileSafe` and `writeFileAtomic` are given as bytes (a Buffer, a typed array or a+ DataView, or a string written as hex, base64 or base64url) is read too, a hit masked with `*` so the file keeps its length. After a+ nested write and the write around it are both refused, the next write keeps the escape context of the last accepted output, so JSON+ written in pieces stays JSON. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more+ writes, a short piece on the far side of an escape split between two writes, base64 of a piece that is not a whole part, a token+ split between two appends to a file, a token another process obtained, and a file written other than through the plugin's writers.+ pcf's copy of the module takes out the same spellings and keeps the same escape context.+## [2.18.0]The bundled SDK is updated to power-platform-ux a3443479. An app whose sitemap's unique name is not the app's — first-party appsdiff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.mdindex 2a43b55bd..8cdd15b1c 100644--- a/plugins/model-apps/docs/app-builder-design.md+++ b/plugins/model-apps/docs/app-builder-design.md@@ -139,6 +139,16 @@ full build (engine, run 2) build --apply (FULL, idempotent) → ui + app +data-model *discovery* (a few metadata reads, no writes) — acceptable and DRY.- **LLM code-gen stays in the main loop, between the two engine runs** (invariant §4). The enginenever awaits an agent.+- **One apply of an app at a time per workspace.** Each engine run that applies — run 1, run 2, or a+ `--changed-only` apply — holds the app's build lease (`<workspace>/app-build.<hash>.lock`,+ `lib/app-operation-lease.js`) for all of its work, from before its auth check to its result, so a+ second run of the same app cannot interleave its discovery and creates with this one's: the generated+ app icon, the app, a web resource or a page would otherwise be found missing by both and created twice.+ The second run stops at once (`build-locked`) and is re-run after the first finishes. The lease is+ released between run 1 and run 2 (page generation holds none); run 2 rediscovers state, as above. It+ is a local courtesy between cooperating runs of this version — not a server transaction, not across+ workspaces or machines, and a build of an earlier release takes none (the legacy pages lock still keeps+ such a build out of the pages phase when it spells the app the same way).Stages are therefore a **vocabulary and orchestration layer**, not independent writeinvocations. `data` executes in run 1; `generate-pages` in the main loop; `ui`/`app`/`publish`/@@ -685,6 +695,15 @@ of the touched artifacts only. A pre-mutation live-projection equality check refMaker-drifted artifact (a page write is checked against the page's version only between its own read and its write — the residual concurrent-edit race is documented asunsupported).+The pages-only fast apply checks the bindings of the pages it WRITES before it writes anything: its changed+keys, and a navigation target only when the target is absent (the pages phase creates it from its spec entry,+bindings and all, and leaves an existing one as it is). Whether a target exists the pages phase learns only+after that check, so the flow passes the page keys the snapshot records as deployed (`changedOnly.deployedKeys`):+a listed target is not read, an unlisted one is checked (fail closed), and a listed one the pages phase finds+absent (deleted in Maker since the last apply) is checked there before it is created — still before any write,+because the fast apply runs the pages phase alone. The two checks share what the attempt has read, so a name is+read once per attempt and a later read can never undo what an earlier one proved.+**CONFIRMED landmine (validated against `sdk-build.js`) — the pages-only fast path MUST skip the sitemapfinalize.** The pages phase's finalize (`sdk-build.js:1428-1437`) rebuilds the WHOLE sitemap via`appDef(spec, result.created)` and writes `/siteMap` + `components`. In a pages-only run `result.created`diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.mdindex e38c06f4d..6b5feb7de 100644--- a/plugins/model-apps/docs/architecture.md+++ b/plugins/model-apps/docs/architecture.md@@ -225,6 +225,15 @@ deterministic, idempotent, narrated SDK build. Create and **edit share one path*`--non-interactive`/autopilot mode suppresses prompts only — it never bypasses safety gates.The durable `<app>_pagemanifest` web resource carries page semantics across download and rebuild.+**One apply at a time (build lease):** each `--apply` run — the data pre-build (run 1), the full build+(run 2) and a `--changed-only` apply — holds the app's build lease in its workspace+(`<workspace>/app-build.<hash>.lock`, `lib/app-operation-lease.js`) from before its auth check to its+result: a second apply of the same app in that workspace stops at once with `build-locked`, before it+reads or writes anything. Page generation between run 1 and run 2 holds no lease; run 2 takes a new one+and rediscovers state. Inside run 2 the pages phase also holds the two pages locks+(`app-pages.<hash>.lock` and the legacy `pages-<spelling>.lock`). Teardown, download, `/genpage` and+`apps.js` take no build lease, and builds in different workspaces are not excluded.+**Three-authority page identity (pages phase):** generative-page management consults threeauthorities — all matching by id, never by display name:(1) **IDENTITY** — the `<app>_pagemanifest` (`key → pageId`); a downloaded spec's owndiff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 2d3d80f4c..9f824676f 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -50,6 +50,8 @@ const { makeGenpageSdk } = require('./lib/genpage-sdk.js');const { leftOnDiskWarning } = require('./lib/left-on-disk.js');const { makeTempWorkspace } = require('./lib/temp-workspace.js');const { makeWritesBlocking } = require('./lib/output-redaction.js');+// The lease one apply of an app holds for the whole of its work in the workspace (lib/app-operation-lease.js).+const { withAppBuildLease, applyWorkspaceOf } = require('./lib/app-operation-lease.js');// The folder an app's workspace lives in, checked before anything is built on it. An APPLY makes the folder if it is// missing and re-checks it (mkdir on an existing junction succeeds, so the re-check is what refuses one). A DRY RUN@@ -197,7 +199,12 @@ function cliEmit(log, opts = {}) {log(` [${e.n}/${e.total}] ${mark} ${e.label}${why}`);return;}- if (counts) counts[e.status] = (counts[e.status] || 0) + 1;+ if (counts) {+ // A step taken up again later in its phase keeps its number and names the outcome it replaces (`replaces`: a status reason its table's+ // lag deferred, then retried — makeRunner, entity-provision.js), so the summary counts each step once, by the outcome it ended with.+ if (e.replaces && counts[e.replaces] > 0) counts[e.replaces] -= 1;+ counts[e.status] = (counts[e.status] || 0) + 1;+ }const glyph = e.status === 'ok' ? '✓' : e.status === 'skip' ? '⊘' : '✗';const tail = e.status === 'error' ? ` — ${e.detail || ''}` : '';log(` [${e.n}/${e.total}] ${glyph} ${e.label}${tail}`);@@ -411,6 +418,17 @@ async function buildModelApp(spec, opts, deps) {}const fileErrors = appSourceFileErrors(spec, opts.appDir);if (fileErrors.length) return { ok: false, errors: fileErrors };+ if (!opts.apply) return buildModelAppHeld(spec, opts, deps, v, undefined);+ // An APPLY runs under the app's build lease (lib/app-operation-lease.js), from the approval record it reads at its start, through every attempt+ // of the retry loop below and its waits, the settlement of what a halted run owes, the inline verify and the journal's close: a second apply of+ // the same app in the same workspace is refused before any of that. The CLI hands its own lease in (`opts.buildLease`), and it is borrowed; a+ // caller that holds none gets one taken here, and let go when this returns or throws.+ return withAppBuildLease({ workspaceDir: applyWorkspaceOf(opts), appUniqueName: appUniqueName(spec), buildLease: opts.buildLease, warn: deps.warn },+ (buildLease) => buildModelAppHeld(spec, opts, deps, v, buildLease));+}++// The body of buildModelApp, run once the spec has been validated — under the build lease `buildLease` for an apply, which every attempt below borrows.+async function buildModelAppHeld(spec, opts, deps, v, buildLease) {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@@ -682,6 +700,8 @@ async function buildModelApp(spec, opts, deps) {warn: deps.warn,genpage: deps.genpage, // injectable seam for tests (lib/genpage-sdk.js's shape); else made from envworkspaceDir: opts.workspaceDir, // lease/staging live under the real workspace dir+ // The build lease this apply holds (or borrowed from its caller): every attempt borrows it, so none of them takes a second one.+ buildLease,authorizedFormRemovals,authorizedSitemapRemovals,allowDestructive: opts.allowDestructive, // pages phase gates destructive page removals@@ -1132,6 +1152,25 @@ async function main() {env,workspaceDir,};+ // An APPLY runs under the app's build lease from here to its result (lib/app-operation-lease.js): taken after the arguments, the spec and the+ // paths have been checked, and BEFORE the auth check, the language read, the SDK's workspace, the journal, the baseline and the snapshot — so a+ // second apply of the same app in this workspace is refused (`build-locked`: on stderr, exit 1, no stdout JSON) before it sends a request or+ // touches a file another build is using. The lease covers the build's automatic re-runs and their waits, the settlement of a halt, the inline+ // verify, the SDK's cleanup and the baseline written last, and it is let go — in the `finally` of withAppBuildLease — before the result is+ // printed: emitResult ends the process, and a `finally` around it would never run. So the command's body ANSWERS its result, and it is printed+ // here, after the release; an error it throws goes on to main().catch the same way. A dry run reads only, and takes no lease.+ const command = { env, spec, languageCode, changedOnly, workspaceDir };+ const outcome = opts.apply+ ? await withAppBuildLease({ workspaceDir, appUniqueName: appUniqueName(spec), warn: (m) => process.stderr.write(`⚠ ${m}\n`) },+ (buildLease) => runBuildCommand({ ...command, opts: { ...opts, buildLease } }))+ : await runBuildCommand({ ...command, opts });+ emitResult(outcome.ok, outcome.payload);+}++// Everything main() does once the command line has been checked: auth, the authoring language, the SDK, the journal, the build and the baseline.+// Answers { ok, payload } for main() to print: a refusal of the identity as the `{ ok: false, error }` it has always printed, and otherwise the+// build's result, `ok` only when the build and its verify succeeded.+async function runBuildCommand({ env, spec, languageCode, changedOnly, workspaceDir, opts }) {// #455: the App, Form and Dashboard adapters bake the authoring LCID in at CONSTRUCTION, so it// has to be resolved before the SDK exists — which is why this reads over the transport hatch// rather than through `provision.queryRecords`. Resolving here also means the provisioned-language@@ -1158,7 +1197,7 @@ async function main() {// error(s); see stdout JSON") — which would replace a message written specifically to tell the// operator which identity to sign in as. `download-model-app.js` uses `error` for the identical// failure, so the array here also made two sibling CLIs report the same problem differently.- if (!auth.ok && !auth.inconclusive) { emitResult(false, { ok: false, error: auth.error }); return; }+ if (!auth.ok && !auth.inconclusive) return { ok: false, payload: { ok: false, error: auth.error } };if (auth.inconclusive) process.stderr.write(`⚠ ${auth.error}\n`);}const authoringLanguageCode = opts.apply@@ -1291,12 +1330,12 @@ async function main() {} finally {cleanup();}+ // Still under the build lease: the baseline is this build's to write, and no other build of the app may write it meanwhile.persistAppliedBaseline(r, { spec, opts, workspaceDir, appDirAbs, baselineIdentity });- // emitResult() calls process.exit(), so emit AFTER cleanup() has run. A build that applied cleanly- // but whose auto-verify found missing artifacts exits NON-ZERO (the silent-partial signal auto-verify exists- // to raise), while r still carries the full build + verify detail.+ // main() prints this once the lease is let go (emitResult calls process.exit). A build that applied cleanly but whose auto-verify found missing+ // artifacts exits NON-ZERO (the silent-partial signal auto-verify exists to raise), while r still carries the full build + verify detail.const ok = r.ok && (!r.verify || r.verify.ok);- emitResult(ok, r);+ return { ok, payload: r };}if (require.main === module) {diff --git a/plugins/model-apps/scripts/lib/app-operation-lease.js b/plugins/model-apps/scripts/lib/app-operation-lease.jsnew file mode 100644index 000000000..69d84658b--- /dev/null+++ b/plugins/model-apps/scripts/lib/app-operation-lease.js@@ -0,0 +1,280 @@+'use strict';+// The local leases that keep two builds of ONE app in ONE workspace from writing at the same time.+//+// WHY. A build discovers what an environment has and then creates what is missing: the app's generated icon is looked up by name and created+// when the lookup finds nothing, and so are the app, the authored web resources, the views, the forms and the pages. Two builds of the same app+// that overlap both see "missing" and both create — measured over the real bundle: two lookups, two icon creates, two icons added to the+// solution. Only a lock held around the whole read-then-create stops that; the platform's own uniqueness answers are not a lock.+//+// WHAT IS LOCKED, AND BY WHICH FILE. Every lock is a file in the workspace folder, taken through the snapshot lease's protocol+// (lib/apply-snapshot-store.js acquireLease: an exclusive create picks one holder, a `.reclaim` claim lets exactly one of several reclaimers win,+// a release removes only a file that still holds its own token) and stamped and judged by lib/process-owner.js: a lock is taken over ONLY from a+// process that is PROVEN gone, never because it is old — a live build can be paused for as long as a laptop sleeps.+//+// app-build.<sha256 of the lower-cased app unique name>.lock one whole apply of the app (withAppBuildLease)+// app-pages.<sha256 of the lower-cased app unique name>.lock the pages phase, keyed without regard to case+// pages-<the app unique name, unsafe characters as _>.lock the pages phase, as every earlier release spells it+//+// The build lock is held for one complete apply: from before the CLI's auth check, through every phase, the automatic re-runs of a transient+// halt and their waits, the settlement of what a halted run owes, the inline verify, the journal and the SDK's cleanup, to the baseline and the+// snapshot the run persists — and let go only when all of that has settled. A second apply of the same app in the same workspace is refused at+// once (`build-locked`), before it opens the SDK's workspace, the journal or the snapshot, or sends any request. The pages files are taken inside+// it, by the pages phase, as before: a build of an earlier release takes no build lock, so the legacy pages file is the only thing that still keeps+// it and a build of this one apart.+//+// The page-publish record already compares app names without regard to case (lib/page-publish-records.js), so `Contoso_App` and `contoso_app`+// share one record; the pages lock did not, and on a case-sensitive file system the two spellings took two locks. The hashed name fixes that. It+// is a different name from the legacy one on every file system: a lower-cased `pages-contoso_app.lock` would be the SAME file as+// `pages-Contoso_App.lock` on Windows and on a default macOS volume, and a build would then refuse its own lock. The legacy name is still taken,+// byte for byte, because a build of an earlier release takes only that one: holding it keeps the two releases out of each other's pages phase when+// they spell the app the same way. A different spelling across releases on a case-sensitive file system is not covered (the earlier release cannot+// see the hashed file), and no scan of other spellings can cover it: an old build can start under an unseen spelling right after the scan.+//+// Nothing here talks to Dataverse, stores a token, an environment, a spec or a name in a lock, or waits: a held lock is refused at once.+const fs = require('node:fs');+const path = require('node:path');+const { sha256 } = require('./hash.js');+const { assertSafeOutputDir, assertPlainFileTarget } = require('./safe-fs.js');+const { acquireLease } = require('./apply-snapshot-store.js');+const { ownerStamp, ownerState, describeOwner } = require('./process-owner.js');+const { BuildHalt } = require('./entity-provision.js');+const { RETRY } = require('./retry-policy.js');++// The one lower-casing the page-publish record uses for an app's name (page-publish-records.js: `String(name || '').toLowerCase()`), nothing more+// — no trimming, no Unicode normalization — so the lock and the record agree on which spellings are one app. Hashed so that any name, whatever its+// characters, makes a file name that is safe and of one length.+const canonicalAppOf = (rawApp) => String(rawApp || '').toLowerCase();+const appHashOf = (rawApp) => sha256(canonicalAppOf(rawApp));++// The file names, all inside the workspace folder. The legacy one is the earlier releases' exactly (`String(appUnique).replace(...)`): a build+// of one of them and a build of this one must name the same file when they spell the app the same way.+const buildLockName = (rawApp) => `app-build.${appHashOf(rawApp)}.lock`;+const canonicalPagesLockName = (rawApp) => `app-pages.${appHashOf(rawApp)}.lock`;+const legacyPagesLockName = (rawApp) => `pages-${String(rawApp).replace(/[^A-Za-z0-9_-]/g, '_')}.lock`;++// What a refused take-over adds to a refusal: the lock's owner is gone, but the lock could not be taken (another build was taking it over at the+// same moment, or died doing so).+const unreleasedNote = (lease) => (lease.stale ? ` The build that held it is no longer running, but its lock could not be released: ${lease.reason}.` : '');++// Takes ONE lock file `file` in the folder `dir`. Answers acquireLease's result: { ok: true, path, token, reclaimed?, previous? }, or+// { ok: false, reason, stale?, error? }.+//+// The lock and its claim file are looked at first, with the plugin's one check for a planted link (lib/safe-fs.js): a symbolic link, a junction,+// a hard link or a folder at either name is refused, not followed — a reclaim writes the lock and a release deletes it, and either would then land+// on whatever the link points at. A missing name is what a free lock is. These checks are of names, between operations; they are no defense+// against a hostile process that swaps a name for a link in between.+function takeLockFile(dir, file, { owner = {}, now = Date.now, stamp }) {+ const lockPath = path.join(dir, file);+ assertPlainFileTarget(lockPath);+ assertPlainFileTarget(`${lockPath}.reclaim`);+ return acquireLease(dir, {+ file,+ now,+ stamp: stamp || ownerStamp({ ...owner, now }),+ // Stale only when the process that took the lock is PROVEN gone (process-owner.js): a lock whose owner runs, or cannot be judged — another+ // machine, another pid namespace, a record that is missing or damaged, a lock of a release that recorded only { pid, at } — is never stale,+ // however old it is.+ isStale: (held) => ownerState(held, owner).state === 'gone',+ });+}++// Releases a lock this process holds, and says so when it cannot confirm that it did. Owner-checked: the file is removed only while it still holds+// this holder's exact token, and a lock that holds another token now — a build that took it over after this one was judged gone — is that build's,+// and is left without a word. A removal that cannot be confirmed (the file still holds the token when read back, or cannot be read at all: an+// unreadable lock is not a removed one) is a warning, never an error: the work the lock guarded has already finished, so this must not turn a+// finished build into a failure. A later build takes the lock over once this process is gone. Never throws (sayAfterRelease).+function releaseLockFile(handle, { warn, kind, appUnique }) {+ if (!handle || !handle.path || !handle.token) return;+ let confirmed = false;+ try {+ const held = fs.readFileSync(handle.path, 'utf8');+ if (held !== handle.token) return;+ fs.rmSync(handle.path, { force: true });+ try {+ confirmed = fs.readFileSync(handle.path, 'utf8') !== handle.token;+ } catch (e) {+ confirmed = !!e && e.code === 'ENOENT';+ }+ } catch (e) {+ confirmed = !!e && e.code === 'ENOENT';+ }+ if (!confirmed) {+ sayAfterRelease(warn, `could not confirm removal of the ${kind} lock for '${appUnique}': ${handle.path}. This run has finished; keep the workspace and its recovery records. If a later run still stops here, confirm no build is running before removing only this lock.`);+ }+}++// A warning given while locks are let go, through the caller's `warn`. The release is done by then, and by the rule above it must not change what+// the build answers — so a callback that throws (a logger that is gone, a pipe that closed) is not let out of here either: it would replace the+// build's own result or error, and stop the release of the files still held after this one. The warning is lost; no lock is.+function sayAfterRelease(warn, message) {+ if (typeof warn !== 'function') return;+ try {+ warn(message);+ } catch {+ // Deliberately nothing: see above.+ }+}++// Whose lock a take-over replaced, as one key: the process (pid, machine, kind of system, pid namespace, start), not the moment or the random part+// of its token. The two pages files of one build carry one owner, and a take-over of both is said once.+const ownerKeyOf = (held) => JSON.stringify([held && held.pid, held && held.host, held && held.platform, held && held.ns, held && held.start]);++// The pages refusal, in the words it has always had (a person and the skills read them). `blocking` is the file that refused: the hashed one for two+// builds of this release, the legacy one for a build of an earlier release that spells the app the same way. "Stale" in the sentence means what the+// take-over means by it — the owner is proven gone — and never that the lock is old.+function pagesLocked(appUnique, blocking, lease) {+ // `retry: NEVER`: the lock belongs to a build that is still running, or to one that is gone but whose lock could not be released — running the+ // earlier phases again releases neither — and the message quotes the lock's path, which holds the maker's folder.+ return new BuildHalt(`another build is deploying pages for '${appUnique}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${blocking} if it is stale.${unreleasedNote(lease)}`, { phase: 'pages', code: 'pages-locked', recoverable: true, retry: RETRY.NEVER });+}++// SINGLE-MACHINE advisory lock over the pages phase (design §9: a courtesy, not a cross-machine guarantee): it stops two LOCAL builds of the same app+// racing to CREATE duplicate pages, while correctness rests on the convergence spine (fail-closed enumeration, create-absent-first, persist after+// each create) that makes any re-run idempotent. Takes, in this order, the hashed pages lock and then the legacy one, and answers { release() },+// which lets go of the legacy one and then the hashed one.+//+// A lock that is held refuses at once (`pages-locked`, the file that refused named), and so does one whose owner is gone but that could not be+// taken over. Nothing is waited for, so taking the two files in a fixed order cannot deadlock a build of this release against an earlier one,+// which takes only the second. When the second file refuses, the first is let go again before the refusal is thrown: a phase never runs on half+// of its locks, and no lock is kept while waiting for another. A create that failed for another reason than the lock being there (a workspace+// that cannot be written) is that error, as it always was.+//+// A build killed outright (SIGKILL, "End task", an agent's timeout, a power cut) cannot release its locks, and used to leave every later build+// stopped on them until a person deleted the file. A later build now takes such a lock over itself when the process that took it is PROVABLY gone+// (lib/process-owner.js), and every doubt keeps it: a pid that still runs, a lock made on another machine, platform or pid namespace, one with no+// readable record — none is ever taken by age. The take-over is said through `deps.warn` — once for each build the locks belonged to (one build's+// two files are one owner), and also when the second file then refuses and the first is let go again: the take-over did happen. A `warn` that throws+// while it says so rolls the acquire back like a refusal and its error is thrown; one that throws while the files are let go is not let out+// (sayAfterRelease). Cross-machine or cross-worktree concurrency for the SAME app is UNSUPPORTED. `deps` = seams: now, warn, and owner (the+// process-owner.js seams).+function acquireAppPagesLease(wsDir, appUnique, deps = {}) {+ const now = deps.now || (() => Date.now());+ const owner = deps.owner || {};+ // The folder itself is checked as every place the plugin writes into a folder it was named: a link or a file at its name is refused, a missing+ // one is made. A linked ANCESTOR is the maker's own choice and is followed (lib/safe-fs.js).+ assertSafeOutputDir(wsDir, { create: true });+ const stamp = ownerStamp({ ...owner, now });+ const held = [];+ const said = new Set();+ const sayTakenOver = (lease) => {+ if (!lease.reclaimed || typeof deps.warn !== 'function') return;+ const key = ownerKeyOf(lease.previous);+ if (said.has(key)) return;+ said.add(key);+ deps.warn(`released the pages lock for '${appUnique}': the build that held it (${describeOwner(lease.previous)}) is no longer running`);+ };+ const letGo = () => {+ for (const lease of held.splice(0).reverse()) releaseLockFile(lease, { warn: deps.warn, kind: 'pages', appUnique });+ };+ for (const file of [canonicalPagesLockName(appUnique), legacyPagesLockName(appUnique)]) {+ let lease;+ try {+ lease = takeLockFile(wsDir, file, { owner, now, stamp });+ } catch (e) {+ letGo();+ throw e;+ }+ if (!lease.ok) {+ letGo();+ if (lease.error) throw lease.error;+ throw pagesLocked(appUnique, path.join(wsDir, file), lease);+ }+ held.push(lease);+ // The caller's `warn` runs only once the file is in `held`, inside the same rollback as a refusal: a callback that throws lets go of every file+ // this call took — rather than leave them stamped with this process, which is alive, so no later build could take them over — and its error is+ // what the caller gets, as for any acquire that failed.+ try {+ sayTakenOver(lease);+ } catch (e) {+ letGo();+ throw e;+ }+ }+ return { release: letGo };+}++// ---------------------------------------------------------------------------------------------------------------------+// The build lease: one whole apply of one app in one workspace+// ---------------------------------------------------------------------------------------------------------------------++// The workspace an apply leases when its caller named none: the app folder's `.maker-workspace`, as the CLI makes it beside app-spec.json and as+// the pages phase has always found it. Every applying entry resolves it through this one function, so the lease a caller holds and the lease its+// callee looks for name the same folder.+const applyWorkspaceOf = (opts = {}) => opts.workspaceDir || path.join(path.resolve(opts.appDir || '.'), '.maker-workspace');++// The capabilities this process has handed out, each the proof that a lease is held: an empty frozen object that only withAppBuildLease makes,+// recognised by identity here. Not JSON, not a flag, not an environment variable, not a pid — a callee borrows a lease only when its caller hands it+// the very object, so two independent applies in one process still compete like two processes do (sharing a pid is not owning a lease).+const capabilities = new WeakMap();++// `retry: NEVER` for both refusals below: running the build's phases again cannot release another build's lease or make a capability valid, and a+// refusal quotes the lock's path, which holds the maker's folder — the retry rule must never read its words. `recoverable` is the operator's: a+// later run of the same command can proceed once the other build has finished. It never authorizes the build's own automatic re-run.+function buildLocked(appUnique, lockPath, lease) {+ return new BuildHalt(`another build may be applying '${appUnique}' in this workspace — refusing a second concurrent apply (would risk duplicate creation). Re-run the same command after it finishes. If no build using this workspace is running, inspect ${lockPath} and remove it only if it is abandoned; keep the workspace and its recovery records.${unreleasedNote(lease)}`, { phase: 'preflight', code: 'build-locked', recoverable: true, retry: RETRY.NEVER });+}+function buildLeaseInvalid() {+ return new BuildHalt('the supplied build lease is not active for this app and workspace — refusing to apply without its own lease', { phase: 'preflight', code: 'build-lease-invalid', recoverable: false, retry: RETRY.NEVER });+}++// Runs `operation(buildLease)` while this process holds the build lease of the app `appUniqueName` (the raw name sdk-build.js appUniqueName gives)+// in the workspace `workspaceDir`, and answers what it answered, or throws what it threw — after the lease is let go.+//+// `buildLease` is how a nested apply BORROWS its caller's lease instead of taking one of its own (the CLI hands it to buildModelApp, which hands it to+// every attempt of runSdkBuild; the changed-only flow hands it to its builds): it must be a capability this function made, still active, for the same+// workspace folder (compared as the real path safe-fs resolves it, so two spellings of one folder are one) and the same app (without regard to case). A+// borrower runs the operation and releases nothing. Anything else — a string, a capability already released, one for another app or folder — is+// refused (`build-lease-invalid`): an apply never runs without a lease of its own or a valid borrowed one.+//+// Without a `buildLease` the lease is TAKEN: a held lock refuses at once (`build-locked`); there is no wait, no age limit and no flag that skips it.+// A lock whose owner is PROVEN gone is taken over, and `warn` says so; one whose owner is gone but that could not be taken over adds why. A create+// that failed for another reason than the lock being there (a folder that cannot be written) is that error. The lease is let go only when+// `operation` has settled — every request it awaited has answered — never by a timer, a signal handler or an exit hook that could fire while a+// write is still in flight; a release that cannot confirm the lock is gone says so through `warn` and does not change the result. The release is+// guarded from the moment the lock is ours: a `warn` that throws while it says the take-over lets the lock go, and its error is thrown (the+// operation does not run); one that throws while the lock is let go is not let out (sayAfterRelease).+// `owner` and `now` are the process-owner.js seams, for tests.+async function withAppBuildLease({ workspaceDir, appUniqueName, buildLease, warn, owner, now }, operation) {+ // A link or a file at the workspace's name is refused, a missing one is made (lib/safe-fs.js), and the answer is the folder's real path: what a+ // borrower's folder is compared with.+ const root = assertSafeOutputDir(workspaceDir, { create: true });+ const app = canonicalAppOf(appUniqueName);+ if (buildLease !== undefined && buildLease !== null) {+ const held = typeof buildLease === 'object' ? capabilities.get(buildLease) : undefined;+ if (!held || !held.active || held.root !== root || held.app !== app) throw buildLeaseInvalid();+ return operation(buildLease);+ }+ const file = buildLockName(appUniqueName);+ const lease = takeLockFile(workspaceDir, file, { owner, now: now || Date.now });+ if (!lease.ok) {+ if (lease.error) throw lease.error;+ throw buildLocked(appUniqueName, path.join(workspaceDir, file), lease);+ }+ const capability = Object.freeze({});+ const record = { root, app, active: true };+ capabilities.set(capability, record);+ try {+ // Inside the guard: the caller's `warn` is the first thing outside this module that runs once the lock is ours, and a callback that throws must+ // not leave the lock stamped with this process, which is alive — no later build could take it over.+ if (lease.reclaimed && typeof warn === 'function') {+ warn(`released the build lock for '${appUniqueName}': the build that held it (${describeOwner(lease.previous)}) is no longer running`);+ }+ return await operation(capability);+ } finally {+ record.active = false;+ releaseLockFile(lease, { warn, kind: 'build', appUnique: appUniqueName });+ }+}++module.exports = {+ withAppBuildLease,+ applyWorkspaceOf,+ acquireAppPagesLease,+ buildLockName,+ canonicalPagesLockName,+ legacyPagesLockName,+ // For tests.+ canonicalAppOf,+ takeLockFile,+ releaseLockFile,+};diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex a3ec465d5..f5d88f181 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -2706,7 +2706,9 @@ function validateAppSpec(spec, opts = {}) {if (c.type === 'Customer' && c.description) {warnings.push(`entity ${e.schemaName}: column ${c.schemaName} is a Customer column — the SDK's createCustomerColumn accepts no description, so this one will NOT be written to Dataverse`);}- if (c.type && !TYPE_MAP[c.type]) {+ // An own key of TYPE_MAP: `constructor`, `toString` and the other members of Object.prototype are no column type, and a plain+ // `TYPE_MAP[c.type]` read answered them with the inherited member, so a column of such a type passed this check.+ if (c.type && !Object.hasOwn(TYPE_MAP, c.type)) {errors.push(`entity ${e.schemaName}: column ${c.schemaName} has unknown type '${c.type}'`);}// An AutoNumber column needs a format, and `required` is true, false or "recommended" (see checksColumnValues).@@ -2813,7 +2815,10 @@ function validateAppSpec(spec, opts = {}) {// (first Main form in spec order), and both are order-independent — which is the property the old// behaviour lacked, when every Main form promoted itself from inside a concurrent loop and the last// to finish won.- const defaultByEntity = {};+ // Null-prototype maps here and in the Main-form counts below: the key is the table a form names, as the spec writes it, and this loop+ // runs before that name is checked — `(map[key] = map[key] || []).push(…)` on a plain object threw for `constructor` and `__proto__`+ // (it read the inherited member), and the counts below turned into text. A table the spec does not declare is reported further down.+ const defaultByEntity = Object.create(null);for (const f of spec.forms || []) {if (!f) continue;if (f.isDefault !== undefined && typeof f.isDefault !== 'boolean') {@@ -2912,8 +2917,8 @@ function validateAppSpec(spec, opts = {}) {// ground: deactivating every other Main form is a DESTRUCTIVE, entity-wide act, and a spec that// declares a sibling Main form alongside a flagged one is asking for that sibling to be built and// then immediately deactivated — almost certainly not what the author meant.- const mainFormsByEntity = {};- const flaggedByEntity = {};+ const mainFormsByEntity = Object.create(null);+ const flaggedByEntity = Object.create(null);for (const f of spec.forms || []) {if (!f || (f.formType !== undefined && f.formType !== 'Main')) continue;const key = String(f.entity || '').toLowerCase();diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-index.js b/plugins/model-apps/scripts/lib/apply-snapshot-index.jsindex 5bc7b9bef..c4635754f 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-index.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-index.js@@ -14,15 +14,21 @@// path re-resolves live and treats a missing entry as "must full-build that artifact").const { identityOf } = require('./classify-changes.js');+const { ownValue } = require('./own-keys.js');function low(s) { return String(s == null ? '' : s).toLowerCase(); }// Build artifacts = { pages, forms, views, app, webResources, entities, charts, commands, dashboards }.// created = result.created from sdk-build; opts carries the build-time hashes the fast path verifies with.+//+// A page's key and a dashboard's name can be a member of Object.prototype (`constructor`, `__proto__`, …): the two maps keyed by them are+// null-prototype objects, so every such name is recorded as an entry, and they are READ with ownValue, so a page or dashboard the build did+// not report reads as absent instead of as an inherited member (lib/own-keys.js). The snapshot is written with JSON.stringify, which writes+// them exactly as a plain object with the same entries.function indexArtifacts(spec, created, opts = {}) {const s = spec || {};const c = created || {};- const out = { pages: {}, forms: {}, views: {}, app: {}, webResources: {}, entities: {}, charts: {}, commands: {}, dashboards: {} };+ const out = { pages: Object.create(null), forms: {}, views: {}, app: {}, webResources: {}, entities: {}, charts: {}, commands: {}, dashboards: Object.create(null) };const pageDeployedShas = opts.pageDeployedShas || {};const formProjections = opts.formProjections || {};const viewProjections = opts.viewProjections || {};@@ -33,12 +39,13 @@ function indexArtifacts(spec, created, opts = {}) {for (const p of Array.isArray(s.pages) ? s.pages : []) {if (!p || typeof p !== 'object') continue;const key = identityOf.page(p);- const pageId = c.pages && c.pages[key];+ const pageId = ownValue(c.pages, key);if (!pageId) continue; // an intent page or one that wasn't deployed — nothing to record+ const deployedSha = ownValue(pageDeployedShas, key);out.pages[key] = {pageId,sourceSha: p.__contentSha != null ? p.__contentSha : null,- deployedSha: pageDeployedShas[key] != null ? pageDeployedShas[key] : (p.__contentSha != null ? p.__contentSha : null),+ deployedSha: deployedSha != null ? deployedSha : (p.__contentSha != null ? p.__contentSha : null),};}@@ -99,7 +106,7 @@ function indexArtifacts(spec, created, opts = {}) {}for (const d of Array.isArray(s.dashboards) ? s.dashboards : []) {if (!d || typeof d !== 'object') continue;- const id = c.dashboards && c.dashboards[d.name];+ const id = ownValue(c.dashboards, d.name);if (id) out.dashboards[identityOf.dashboard(d)] = { id };}diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.jsindex f15c71a17..e8156a01b 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js@@ -26,8 +26,9 @@ const {// The one liveness check, shared with the pages lock and the temporary workspaces (lib/process-owner.js); re-exported below as it always was.const { processAlive } = require('./process-owner.js');// The one writer of the snapshot, the baseline (`last-applied.json`) and the page ownership and publish records is `writeFileAtomic`, and the text it writes has the access tokens the process obtained taken out first-// (lib/output-redaction.js). The leases, claims and markers this module writes hold process ids, times and random ids, and a reason built from a file system's own words.-const { redactOutput } = require('./output-redaction.js');+// (lib/output-redaction.js: a text cleaned as a text, bytes masked as the bytes the file gets). The leases, claims and markers this module writes hold process ids, times and random ids, and a reason built from a file+// system's own words.+const { redactFileData } = require('./output-redaction.js');const SNAPSHOT_FILE = 'apply-snapshot.json';const LEASE_FILE = 'apply-snapshot.lock';@@ -69,7 +70,7 @@ function writeFileAtomic(target, text) {try {const fd = fs.openSync(tmp, 'w');try {- fs.writeFileSync(fd, redactOutput(text));+ fs.writeFileSync(fd, redactFileData(text));fs.fsyncSync(fd);} finally {fs.closeSync(fd);diff --git a/plugins/model-apps/scripts/lib/changed-only-flow.js b/plugins/model-apps/scripts/lib/changed-only-flow.jsindex d14bddd3c..68a8dc5ed 100644--- a/plugins/model-apps/scripts/lib/changed-only-flow.js+++ b/plugins/model-apps/scripts/lib/changed-only-flow.js@@ -26,7 +26,11 @@ const { classifyChanges } = require('./classify-changes.js');const snap = require('./apply-snapshot.js');const store = require('./apply-snapshot-store.js');const { indexArtifacts } = require('./apply-snapshot-index.js');+const { ownValue } = require('./own-keys.js');const { odataLit } = require('./odata.js');+// The app's build lease (lib/app-operation-lease.js), and the one derivation of the app's unique name it is keyed by.+const { withAppBuildLease, applyWorkspaceOf } = require('./app-operation-lease.js');+const { appUniqueName } = require('./sdk-build.js');// ---- PURE decision ------------------------------------------------------------------------------------@@ -164,14 +168,19 @@ function assembleFastSnapshot({ snapshot, annotatedSpec, created, pageKeys, geneif (!env.artifacts) env.artifacts = {};if (!env.artifacts.pages) env.artifacts.pages = {};const selected = new Set(pageKeys || []);+ // Each map is read by the page's key as an OWN entry (lib/own-keys.js): a key can be `constructor`, which a plain object — the+ // snapshot's parsed JSON, or the `{}` of a build that measured no deployed hash — answers with the Object function, and that+ // function would be recorded as the page's id or deployed hash (and then dropped from the JSON written to disk).const deployedShas = (created && created.pageDeployedShas) || {};for (const p of annotatedSpec.pages || []) {if (!p || typeof p !== 'object') continue;const key = p.key || p.name;if (!selected.has(key)) continue; // only refresh the pages we actually re-uploadedconst sourceSha = p.__contentSha != null ? p.__contentSha : null;- const deployedSha = deployedShas[key] != null ? deployedShas[key] : sourceSha;- const pageId = (created && created.pages && created.pages[key]) || (env.artifacts.pages[key] && env.artifacts.pages[key].pageId) || null;+ const measured = ownValue(deployedShas, key);+ const deployedSha = measured != null ? measured : sourceSha;+ const recorded = ownValue(env.artifacts.pages, key);+ const pageId = ownValue(created && created.pages, key) || (recorded && recorded.pageId) || null;env.artifacts.pages[key] = { pageId, sourceSha, deployedSha };}snap.bumpGeneration(env, generation);@@ -181,13 +190,33 @@ function assembleFastSnapshot({ snapshot, annotatedSpec, created, pageKeys, genereturn env;}+// The pages a snapshot records as deployed by the last verified apply: the keys whose record holds a page id (apply-snapshot-index.js `indexArtifacts`, assembleFastSnapshot). A record without one proves+// no page, and a snapshot that records none (an older one) names none — so the build checks every navigation target, as it always did.+function deployedPageKeys(snapshot) {+ const pages = (snapshot && snapshot.artifacts && snapshot.artifacts.pages) || {};+ return Object.keys(pages).filter((key) => pages[key] && pages[key].pageId);+}+// ---- orchestration ------------------------------------------------------------------------------------// Run the `--apply --changed-only` flow. `deps.buildModelApp` is injected (no require cycle) so this// module orchestrates without importing the CLI wrapper; `deps.buildDeps` is the deps object passed// through to buildModelApp (sdk/provisionSdk/journal/verify/log). Returns the buildModelApp result// augmented with `.changedOnly` (the decision), or a noop/abort result.+//+// The FIRST thing it does is take the app's build lease, or borrow the one its caller holds (`opts.buildLease`, the CLI's): before the spec's+// content is read, before the snapshot and the distrust markers are read, and before the live identity is resolved (a WhoAmI). A second apply of+// the same app in this workspace is refused there (`build-locked`), and reads nothing — it would otherwise decide fast/full/noop from a snapshot+// the running build is about to change. Everything below runs under the lease, and the builds it starts borrow it: one lease for the whole flow,+// let go when it returns or throws. The workspace is resolved once (lib/app-operation-lease.js applyWorkspaceOf), so the lease and the flow name+// the same folder.async function runChangedOnlyApply({ spec, opts, deps }) {+ const ws = applyWorkspaceOf(opts);+ return withAppBuildLease({ workspaceDir: ws, appUniqueName: appUniqueName(spec), buildLease: opts.buildLease, warn: deps.warn },+ (buildLease) => runChangedOnlyApplyHeld({ spec, opts: { ...opts, workspaceDir: ws, buildLease }, deps }));+}++async function runChangedOnlyApplyHeld({ spec, opts, deps }) {const log = deps.log || (() => {});const ws = opts.workspaceDir;const annotate = (s) => annotateContentHashes(s, deps.readContent);@@ -323,7 +352,10 @@ async function runChangedOnlyApply({ spec, opts, deps }) {return { ok: false, errors: [msg], changedOnly: decision };}// selectedKeys: upload ONLY the changed pages (never clobber an unchanged one).- const fastOpts = { ...fullApplyOpts(opts), phases: ['pages'], changedOnly: { fastApply: true, resolvedAppId: live.appId, skipSitemapFinalize: true, selectedKeys: decision.pageKeys } };+ // deployedKeys: the pages the snapshot records its last verified apply deployed. The build checks the bindings of the pages it writes before it writes anything, and it writes a navigation target only+ // when the target is absent — which it learns only later, in its pages phase. So it is told which pages are there, and leaves their bindings unread; one it was told of and finds absent after all+ // (deleted in Maker since) it checks before it makes it (sdk-build.js, pagesMadeUnchecked).+ const fastOpts = { ...fullApplyOpts(opts), phases: ['pages'], changedOnly: { fastApply: true, resolvedAppId: live.appId, skipSitemapFinalize: true, selectedKeys: decision.pageKeys, deployedKeys: deployedPageKeys(snapshot) } };const { r, moved } = await buildHolding(ws, inv.generation, log, () => deps.buildModelApp(spec, fastOpts, deps.buildDeps));// Re-bless ONLY on a fully successful apply whose mandatory page verify PASSED (a fast apply always// applies the pages phase, so verify is mandatory and r.verify is always set — a missing/failed verifydiff --git a/plugins/model-apps/scripts/lib/deployed-baseline.js b/plugins/model-apps/scripts/lib/deployed-baseline.jsindex f76f0ea93..3db9196db 100644--- a/plugins/model-apps/scripts/lib/deployed-baseline.js+++ b/plugins/model-apps/scripts/lib/deployed-baseline.js@@ -27,6 +27,7 @@ const { annotateContentHashes, recordedContentSha } = require('./content-hash.jsconst { migrateAppSpec } = require('./app-spec.js');const { writeFileAtomic } = require('./apply-snapshot-store.js');const { resolveAppSource } = require('./app-source-path.js');+const { ownValue } = require('./own-keys.js');const FILE = 'last-applied.json';// Stored beside the spec's own top-level keys. phase-diff.js compares only its per-phase slices, so@@ -68,18 +69,18 @@ function confinedReader(appDir) {* An entry no source has is left out, so the next build resolves it itself.*/function deployedIdsFor(spec, { created, previous, fromSpec = false } = {}) {- const own = (map, name) => (map && typeof map === 'object' && Object.prototype.hasOwnProperty.call(map, name) ? map[name] : undefined);const prior = (previous && previous[IDS_KEY]) || {};const list = (v) => (Array.isArray(v) ? v : []);// Object.fromEntries defines each name as an own data property — a dashboard named `__proto__` is- // recorded, not turned into the object's prototype.+ // recorded, not turned into the object's prototype. Every source is read as its OWN entry (ownValue,+ // lib/own-keys.js), so a dashboard named `constructor` never resolves to Object.prototype's.const dashboards = Object.fromEntries(list(spec && spec.dashboards).filter((d) => d && typeof d.name === 'string' && d.name)- .map((d) => [d.name, (fromSpec && d.dashboardId) || own(created && created.dashboards, d.name) || own(prior.dashboards, d.name)])+ .map((d) => [d.name, (fromSpec && d.dashboardId) || ownValue(created && created.dashboards, d.name) || ownValue(prior.dashboards, d.name)]).filter(([, id]) => typeof id === 'string' && id));const pages = Object.fromEntries(list(spec && spec.pages).filter((p) => p && typeof p.key === 'string' && p.key)- .map((p) => [p.key, (fromSpec && p.pageId) || own(created && created.pages, p.key) || own(prior.pages, p.key)])+ .map((p) => [p.key, (fromSpec && p.pageId) || ownValue(created && created.pages, p.key) || ownValue(prior.pages, p.key)]).filter(([, id]) => typeof id === 'string' && id));return { dashboards, pages };}diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex ab4276fb0..1d7a91922 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -34,6 +34,7 @@ const {} = require('./app-spec.js');const { readColumnLabels, makeTableLabelReader, lookupKey, labelsByLcid } = require('./lookup-labels.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');+const { ownValue } = require('./own-keys.js');// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution// uniquename / publisher prefix with a `'` would otherwise break the query or inject a clause).const { odataLit } = require('./odata.js');@@ -49,7 +50,7 @@ const { readOrgLanguageCode, readProvisionedLanguages } = require('./dataverse-aconst { RETRY, retryPolicyFor, refusal, serviceFailure, serviceCodeOf } = require('./retry-policy.js');// What the run's throttle budget says when it refuses a wait (the words of the build's own halt for it), for the step guard in makeRunner.const { waitDoesNotFit } = require('./throttle-budget.js');-const { readStatusOptions, alternateKeyMatches } = require('./table-schema-metadata.js');+const { readStatusOptions, alternateKeyMatches, alternateKeyOverColumns, sameKeyColumnSet } = require('./table-schema-metadata.js');// App Spec column type -> SDK ColumnType. Lookup is omitted (side effect of a OneToMany// relationship); Customer is handled specially (createCustomerColumn).@@ -917,32 +918,342 @@ function outcomeUnknown(err) {// and tells the budget; the service has asked the run to hold back, so the columns are NOT then created one by one — each would be one more request to a service that said to wait — and the phase stops// with the budget's halt. `stop`, when there is a budget, is the check that says so (the runner's `stopIfRefused`): it throws when the budget has refused, and does nothing otherwise, so a change// set that was refused by anything else, or whose sends ran out while the budget still had room, falls back exactly as it always did.-async function createColumnsInOneRequest({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep, stop }) {+//+// And one refusal is the lag of the table itself (`lagTable`, a table this attempt has just created — see "The lag of a table this attempt just+// created" below): the change set refused with HTTP 400 and `0x80040216` or `0x80090457` in its first part is not taken for an ordinary refusal.+// The table's columns are read, and what follows depends on what that read PROVES (recoverRefusedBatch): every column there is adopted; every+// missing one proved absent sends the change set once more, or creates the missing ones one by one; a column the read cannot place is read again,+// within the table's budget; and a budget spent with a column still missing stops the build — `terminal` — before any further column is sent.+//+// Answers { map, terminal?, fallback? }: `map` holds the columns confirmed, keyed by the column object, each with the id createColumn would have+// answered; `terminal`, when there is one, is the failure the column loop stops with at the first column the map does not hold (it sends nothing+// more); `fallback`, when there is one, is the lag's own one-by-one fallback (recoverRefusedBatch), whose creates the table's budget gates.+async function createColumnsInOneRequest({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep, stop, lagTable }) {try {// The options are built inside the try: a column the options cannot be built for fails the way it always did, in its own step// on the per-column path, instead of failing the phase from here.await sdk.createColumns(table.logicalName, columns.map(optionsFor));} catch (err) {if (typeof stop === 'function') stop();- if (outcomeUnknown(err)) {- // ONE read, and only an answer that shows EVERY column counts: the change set is atomic, so a table that has only some of them- // did not get them from it (a column the platform makes itself under the name of one the spec asks for is there either way).- const found = await confirmInlineColumns(provision, table, columns, { sleep, attempts: 1 });- if (found.size === columns.length) {- if (typeof warn === 'function') warn(`the answer to the request that creates the ${columns.length} ordinary column(s) of table ${tableSchemaName} was lost or could not be read (${briefReason(err)}), but the table has every one of them`);- return found;- }+ const code = lagTable ? batchLagCodeOf(err) : null;+ if (code) return recoverRefusedBatch({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep, stop, lagTable, original: err, code });+ return { map: await afterRefusedBatch(err, { provision, table, tableSchemaName, columns, warn, sleep }) };+ }+ return { map: await confirmInlineColumns(provision, table, columns, { warn, sleep }) };+}++// What follows a change set that was not created as sent, for every refusal but the lag of the table (above): the columns found when its answer was+// lost and the table proves it committed, and otherwise none — the columns are then created one by one, with `warn` saying why.+async function afterRefusedBatch(err, { provision, table, tableSchemaName, columns, warn, sleep }) {+ if (outcomeUnknown(err)) {+ // ONE read, and only an answer that shows EVERY column counts: the change set is atomic, so a table that has only some of them+ // did not get them from it (a column the platform makes itself under the name of one the spec asks for is there either way).+ const found = await confirmInlineColumns(provision, table, columns, { sleep, attempts: 1 });+ if (found.size === columns.length) {+ if (typeof warn === 'function') warn(`the answer to the request that creates the ${columns.length} ordinary column(s) of table ${tableSchemaName} was lost or could not be read (${briefReason(err)}), but the table has every one of them`);+ return found;}- if (typeof warn === 'function') {- // A ConnectionError carries `.statusCode`; any other error may wrap one as its `cause`.- const status = err && (err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status)));- warn(status === 429- ? `table ${tableSchemaName} was throttled (${briefReason(err)}), so its ${columns.length} ordinary column(s) are created one by one instead of in one request`- : `could not create the ${columns.length} ordinary column(s) of table ${tableSchemaName} in one request (${briefReason(err)}) — creating them one by one`);+ }+ if (typeof warn === 'function') {+ // A ConnectionError carries `.statusCode`; any other error may wrap one as its `cause`.+ const status = err && (err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status)));+ warn(status === 429+ ? `table ${tableSchemaName} was throttled (${briefReason(err)}), so its ${columns.length} ordinary column(s) are created one by one instead of in one request`+ : `could not create the ${columns.length} ordinary column(s) of table ${tableSchemaName} in one request (${briefReason(err)}) — creating them one by one`);+ }+ return new Map();+}++// ---- The lag of a table this attempt just created ---------------------------------------------------------------------------------------------------+//+// Right after a table is created, a column create or a status-reason insert for it is intermittently refused, and the same create succeeds on a+// re-run. Measured live on an environment whose only language is Spanish, in three of four first builds, the same way in two releases:+// POST $batch (the columns of a new table) HTTP 400, first change-set part {"error":{"code":"0x80040216","message":"An unexpected error occurred."}}+// POST …/Attributes (one column) HTTP 400 {"error":{"code":"0x80040216","message":"An unexpected error occurred."}}+// POST /InsertStatusValue HTTP 400 {"error":{"code":"0x80090457","message":"Component of type Entity with name and id <id> does not exist."}}+// Nothing retried them: a 400 is final to the HTTP client and to the build's own retry (lib/retry-policy.js), and neither code means "already+// exists" (ALREADY_EXISTS_CODES). Both codes are generic, so neither is ever read as a success or as a condition to run the build again; a create+// refused with one of them is sent again ONLY when all of these hold:+// - THIS attempt created the table (not a table that existed, not one found after a create whose answer was lost, not a later attempt);+// - the create is the column change set, one column's create, or a status reason's insert, for that table;+// - the answer is HTTP 400 with one of the two codes, read from the OData error of the answer (the change set's from its first part);+// - a read made after the refusal PROVES the thing absent: a list that holds the table's own stock entry — its primary name column, or the+// stock status reason 1 or 2 — and not the thing, every entry of which can be told apart (a column named with its id, an option with its+// value). A 404, a 400 `0x80090457`, an answer that is no list, one without the stock entry, or one with an entry that cannot be told apart+// — the thing itself named without its id, say — proves nothing and is read again; any other failure of the read stops the build with that+// failure; a column or a reason the read shows is ADOPTED, never sent again;+// - the table's budget still has room: 60 seconds of the time spent waiting for those reads, the waits between them and the check's own sends+// — the resends, and the one-by-one creates of the change set's columns that a read proved absent (time spent elsewhere is not counted) —+// at most 8 reads, at most 4 resends of one create or insert and 1 of the change set. A budget that runs out with the create still missing —+// proved absent or not — stops the build with the original refusal, before any further POST, and says the build may be run again.+// Why 60: the sends are charged, and measured live on that environment one resend took 7.9–47.2 s for a change set and 20.7–26.5 s for a+// File column. With 20 s, the two recoveries a first build met on one new table (its change set's and a File column's) spent 36.7 s, and+// the status reason queued for the same table — which the platform had in fact committed — was never read: the build stopped, and only its+// re-run went on. A minute holds two such recoveries and the read of a third; a lag that outlasts it still stops the build, as before.+// The read of a status reason carries labels, and a label-bearing read ahead of a labelled create keeps only the base language of that create,+// so a refused insert is not read in the table loop: it is queued, and read and sent again after every other labelled create of the phase+// (drainLagStatuses). Nothing here deletes or updates anything, and no wait is a fire-and-forget: every read, wait and resend is awaited.+const LAG_CODES = Object.freeze(new Set(['0x80040216', '0x80090457']));+const LAG_VISIBILITY_CODE = '0x80090457';+const LAG_ADMISSION_MS = 60000;+const LAG_PROBES = 8;+const LAG_SINGLE_RESENDS = 4;+const LAG_DELAYS_MS = Object.freeze([1000, 2000, 4000, 8000]);+const LAG_JITTER = 0.25;+const LAG_SKIP = 'refused just after the table was created — retrying after the other schema creates';+const LAG_REMEDY = ' — the refusal persisted after the bounded check. The table was created. Run the build again to reconcile what is already there; a refusal that is not lag will persist';+// The refusals a budget ran out on: the halt the runner raises around one adds LAG_REMEDY (operatorRemedy). Kept here, beside the error and not in+// its words, so that the error the step reports while it runs, and every rule that reads an error, see the SDK's error exactly as it was.+const persistedLagRefusals = new WeakSet();+const persisted = (err) => { if (err && typeof err === 'object') persistedLagRefusals.add(err); return err; };++// The code of a single create's refusal when it is the lag of the table: HTTP 400 and one of LAG_CODES as the `error.code` of its answer+// (serviceCodeOf reads it from the SDK's ConnectionError, whose `cause` is the body; a code only the message names is not the code). Else null.+function lagCodeOf(err) {+ const status = err && (err.statusCode || err.status);+ if (status !== 400) return null;+ const code = serviceCodeOf(err);+ return code !== null && LAG_CODES.has(code) ? code : null;+}++// The same for a refused change set. The SDK's ConnectionError for a `$batch` carries the multipart answer as its `cause` (a string), e.g.+// --batchresponse_1\r\nContent-Type: multipart/mixed; boundary=changesetresponse_1\r\n\r\n--changesetresponse_1\r\nContent-Type: application/http\r\n+// Content-Transfer-Encoding: binary\r\nContent-ID: 1\r\n\r\nHTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n+// {"error":{"code":"0x80040216","message":"An unexpected error occurred."}}\r\n--changesetresponse_1--\r\n--batchresponse_1--+// The change set's boundary is the one its part declares; its FIRST part is split off at that boundary, its MIME headers and then the headers of+// the HTTP response inside it are skipped (each ends at a blank line), and the body left is parsed as JSON. Only the `error.code` of that JSON+// counts: an answer that is not in this shape, a part that is not a response, or a body that does not parse is no lag refusal — and neither is+// an error with no body at all (the SDK's word that a change set was rolled back). The message is never searched for a code.+function batchLagCodeOf(err) {+ if (!err || err.code !== 'CONNECTION_ERROR' || err.statusCode !== 400 || typeof err.cause !== 'string') return null;+ const code = firstChangeSetErrorCode(err.cause);+ return code !== null && LAG_CODES.has(code) ? code : null;+}+const afterBlankLine = (text) => {+ const blank = /\r?\n\r?\n/.exec(text);+ return blank ? text.slice(blank.index + blank[0].length) : null;+};+function firstChangeSetErrorCode(text) {+ const declared = /^Content-Type:\s*multipart\/mixed;\s*boundary=("?)([^"\s;]+)\1\s*$/im.exec(text);+ if (!declared) return null;+ const parts = text.split(`--${declared[2]}`);+ const first = parts.length > 2 ? parts[1] : null;+ if (first === null || first.startsWith('--')) return null;+ const response = afterBlankLine(first);+ if (response === null || !/^HTTP\/1\.[01] \d{3}\b/.test(response)) return null;+ const body = afterBlankLine(response);+ if (body === null) return null;+ try {+ const parsed = JSON.parse(body.trim());+ const code = parsed && parsed.error && parsed.error.code;+ return typeof code === 'string' && code ? code.toLowerCase() : null;+ } catch {+ return null;+ }+}++// The lag work of one provisionDataModel run: its clock, waits and jitter (seams for tests; the real ones otherwise), the budget of each table+// (created when lag work for the table starts, and shared by its change set, its single creates and its queued status reasons), and the queue+// of refused status reasons the phase's tail drains.+function lagContext({ now, sleep, random, warn }) {+ return {+ now: typeof now === 'function' ? now : Date.now,+ sleep: typeof sleep === 'function' ? sleep : (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+ random: typeof random === 'function' ? random : Math.random,+ warn: typeof warn === 'function' ? warn : () => undefined,+ budgets: new Map(),+ statuses: [],+ };+}++// The lag window of a table this attempt created: what a read of it needs — its MetadataId (a read by id answers for this table and no other+// that comes to hold its name), its schema name for the messages, and the logical name of the primary name column it was created with, the stock+// entry whose presence makes a read's list complete enough to prove a column absent. No id, or no raw client to read with: no window, and every+// create of the table is handled as it always was.+function lagWindow(lag, provision, entity, createdTable) {+ const tableId = createdTable && guidOf(createdTable.metadataId);+ if (!lag || !tableId || !provision || !provision.dataverse || typeof provision.dataverse.get !== 'function') return null;+ const logical = entity.schemaName.toLowerCase();+ if (!lag.budgets.has(logical)) lag.budgets.set(logical, { spentMs: 0, probes: 0, warned: false });+ return { lag, raw: provision.dataverse, logical, schemaName: entity.schemaName, tableId, primaryLogical: String(entity.primaryAttribute.schemaName).toLowerCase(), budget: lag.budgets.get(logical) };+}++const lagSpent = (budget) => budget.spentMs >= LAG_ADMISSION_MS || budget.probes >= LAG_PROBES;++// Runs `fn` and charges the table's budget with the time it took, sampled around it: only what the lag work itself awaits is counted.+async function charged(window, fn) {+ const started = window.lag.now();+ try {+ return await fn();+ } finally {+ window.budget.spentMs += Math.max(0, window.lag.now() - started);+ }+}++// Waits before the `index`-th read or resend of one create: 1 s, 2 s, 4 s, 8 s, 8 s …, plus up to a quarter more, and never past what is left of+// the table's budget — a wait that would run past it is not taken, and the answer is false (the budget is spent). True when the wait was taken+// and room is left after it.+async function lagWait(window, index) {+ const base = LAG_DELAYS_MS[Math.min(index, LAG_DELAYS_MS.length - 1)];+ const delay = Math.round(base * (1 + LAG_JITTER * window.lag.random()));+ if (delay >= LAG_ADMISSION_MS - window.budget.spentMs) return false;+ await charged(window, () => window.lag.sleep(delay));+ return !lagSpent(window.budget);+}++// Said once per table, when its lag work starts. It names what was refused and the code; no address and no id.+function sayLagOnce(window, what, code) {+ if (window.budget.warned) return;+ window.budget.warned = true;+ window.lag.warn(`creating ${what} was refused just after the table was created (HTTP 400 ${code}) — checking whether it exists before a bounded retry`);+}++// What a read made during lag work says, before it is asked about any one thing: { kind: 'list', items } for an answer that can prove something,+// { kind: 'unknown' } for one that proves nothing (the table is not visible to the read yet — a 404, or a 400 `0x80090457` — or a 2xx that is not+// the expected shape), or { kind: 'failed', error } for any other answer, which stops the build as that read's own failure, with its status and+// code (statusError). A read that throws — a failure of the transport — is thrown as it is. Every read counts against the table's 8.+async function lagRead(window, url, itemsOf, what) {+ window.budget.probes += 1;+ const res = await charged(window, () => window.raw.get(url));+ if (res && res.status >= 200 && res.status < 300) {+ const items = itemsOf(res.body);+ return Array.isArray(items) ? { kind: 'list', items } : { kind: 'unknown' };+ }+ const answered = res && res.body && res.body.error;+ if (res && (res.status === 404 || (res.status === 400 && answered && typeof answered.code === 'string' && answered.code.toLowerCase() === LAG_VISIBILITY_CODE))) return { kind: 'unknown' };+ return { kind: 'failed', error: statusError(`could not read ${what} of table ${window.schemaName} to check whether a refused create landed`, res) };+}++// The table's columns, by its id: ids and logical names only — no labels, so the read may come before the phase's labelled creates.+// GET /EntityDefinitions(<id>)/Attributes?$select=MetadataId,LogicalName → { "value": [{ "MetadataId": "…", "LogicalName": "new_name" }, …] }+// A `list` answer is turned into what it shows, row by row, and nothing in it is dropped unread: a row is USABLE when it names a column+// (`LogicalName`, a non-empty string) and carries that column's id (`MetadataId`, a GUID), and only a usable row shows a column present.+// - `ids`: logical name → MetadataId, from usable rows;+// - `named`: every logical name a row names, usable or not — a column named without a usable id, or named twice with two ids, is in the list+// and cannot be adopted (`unclear`), so it is neither present nor absent;+// - `complete`: the list can prove a column ABSENT — it holds the table's primary name column, and every row in it is usable. A row that names+// no column, or names one without its id, could be the very column asked about, and a list that holds one proves no column absent.+// Such a read is never permission to create: only `absent` is (columnState).+async function readLagColumns(window) {+ const read = await lagRead(window, `/EntityDefinitions(${window.tableId})/Attributes?$select=MetadataId,LogicalName`, (body) => body && body.value, 'the columns');+ if (read.kind !== 'list') return read;+ const ids = new Map();+ const named = new Set();+ const unclear = new Set();+ let usable = true;+ for (const a of read.items) {+ const logical = a && typeof a.LogicalName === 'string' && a.LogicalName ? a.LogicalName.toLowerCase() : null;+ const id = a && typeof a.MetadataId === 'string' && GUID_RE.test(a.MetadataId) ? a.MetadataId : null;+ if (!logical) { usable = false; continue; }+ named.add(logical);+ if (!id || (ids.has(logical) && ids.get(logical).toLowerCase() !== id.toLowerCase())) { usable = false; unclear.add(logical); continue; }+ ids.set(logical, id);+ }+ for (const logical of unclear) ids.delete(logical);+ return { kind: 'list', ids, named, complete: usable && ids.has(window.primaryLogical) };+}+// One column against such a read: 'present' (a usable row names it, with its id), 'absent' (a complete list that does not name it at all), or+// 'unknown' — which includes a column the list names without a usable id: it may well be there, and is read again rather than created again.+function columnState(read, logical) {+ if (read.kind !== 'list') return { state: 'unknown' };+ if (read.ids.has(logical)) return { state: 'present', id: read.ids.get(logical) };+ if (read.named.has(logical)) return { state: 'unknown' };+ return { state: read.complete ? 'absent' : 'unknown' };+}++const adoptColumnWarning = (window, column, code) => `column ${window.schemaName}.${column.schemaName} was refused (HTTP 400 ${code}) and then found on the table, so it is reused`;++// The change set of a table this attempt created, refused with the table's lag (createColumnsInOneRequest): read, and act on what the read proves.+// Answers { map, terminal?, fallback? } as createColumnsInOneRequest does:+// - every column found: adopted — nothing is sent;+// - every missing column proved absent, none found and the change set not yet sent again: it is sent once more (after a wait); a refusal of that+// with the lag is read again, any other refusal is handled as every refused change set is (afterRefusedBatch), and a change set that commits is+// confirmed as every one is;+// - every missing column proved absent otherwise (some found, or the change set already sent again), with the budget not spent: `fallback` — the+// found ones are adopted, and the column loop creates the missing ones one by one, each create gated on and charged to the table's budget+// (`fallback.columns` are those columns, `fallback.original` the refusal the loop stops with once the budget is spent);+// - a missing column the read cannot place: read again, after a wait;+// - the budget spent while a column is still missing — proved absent or not — or a read that failed: `terminal`, with the found ones in `map`.+async function recoverRefusedBatch({ sdk, provision, table, tableSchemaName, columns, optionsFor, warn, sleep, stop, lagTable: window, original, code }) {+ sayLagOnce(window, `the ${columns.length} ordinary column(s) of table ${tableSchemaName} in one request`, code);+ const confirmed = new Map();+ let resent = false;+ for (let waits = 0; ;) {+ if (lagSpent(window.budget)) return { map: confirmed, terminal: persisted(original) };+ let read;+ try {+ read = await readLagColumns(window);+ } catch (e) {+ return { map: confirmed, terminal: e };+ }+ if (read.kind === 'failed') return { map: confirmed, terminal: read.error };+ let unknown = 0;+ for (const c of columns) {+ if (confirmed.has(c)) continue;+ const logicalName = c.schemaName.toLowerCase();+ const found = columnState(read, logicalName);+ if (found.state === 'present') {+ confirmed.set(c, { logicalName, metadataId: found.id });+ if (typeof warn === 'function') warn(adoptColumnWarning(window, c, code));+ } else if (found.state === 'unknown') unknown += 1;+ }+ if (confirmed.size === columns.length) return { map: confirmed };+ if (lagSpent(window.budget)) return { map: confirmed, terminal: persisted(original) };+ if (unknown === 0 && (confirmed.size > 0 || resent)) return { map: confirmed, fallback: { original, columns: new Set(columns.filter((c) => !confirmed.has(c))) } };+ if (!(await lagWait(window, waits++))) return { map: confirmed, terminal: persisted(original) };+ if (unknown > 0) continue;+ // Every column proved absent and none found: the change set committed nothing (it is atomic), and is sent once more.+ if (typeof stop === 'function') stop();+ resent = true;+ try {+ await charged(window, () => sdk.createColumns(table.logicalName, columns.map(optionsFor)));+ } catch (err) {+ if (typeof stop === 'function') stop();+ if (batchLagCodeOf(err)) continue;+ return { map: await afterRefusedBatch(err, { provision, table, tableSchemaName, columns, warn, sleep }) };+ }+ return { map: await confirmInlineColumns(provision, table, columns, { warn, sleep }) };+ }+}++// One column's create for a table this attempt created (`create` sends it): sent as always, and when its refusal is the table's lag, read, and acted+// on as the read proves — a column found is adopted with the id the read gave it; one proved absent is sent again after a wait, up to 4 times; one+// the read cannot place is read again. A resend refused with the lag is read again; refused otherwise, that failure is thrown as it is, and the step+// handles it as any (an "already exists" answer is its skip). A budget that runs out with the column still missing throws the original refusal,+// which the step's halt then says may be run again (persistedLagRefusals); a read that failed throws that failure. `charge`: the first send is+// itself one of the check's sends — a column of the lag's own fallback (recoverRefusedBatch), which the caller sends only while the budget has+// room — and the time it takes is charged to the table's budget like every resend's.+async function createInLagWindow(create, { window, column, stop, warn, charge = false }) {+ try {+ return await (charge ? charged(window, create) : create());+ } catch (err) {+ const code = window ? lagCodeOf(err) : null;+ if (!code) throw err;+ sayLagOnce(window, `column ${window.schemaName}.${column.schemaName}`, code);+ const logicalName = column.schemaName.toLowerCase();+ let resends = 0;+ for (let waits = 0; ;) {+ if (lagSpent(window.budget)) throw persisted(err);+ const read = await readLagColumns(window);+ if (read.kind === 'failed') throw read.error;+ const found = columnState(read, logicalName);+ if (found.state === 'present') {+ if (typeof warn === 'function') warn(adoptColumnWarning(window, column, code));+ return { logicalName, metadataId: found.id };+ }+ if (lagSpent(window.budget)) throw persisted(err);+ if (found.state === 'absent' && resends >= LAG_SINGLE_RESENDS) throw persisted(err);+ if (!(await lagWait(window, waits++))) throw persisted(err);+ if (found.state !== 'absent') continue;+ if (typeof stop === 'function') stop();+ resends += 1;+ try {+ return await charged(window, create);+ } catch (again) {+ if (!lagCodeOf(again)) throw again;+ }}- return new Map();}- return confirmInlineColumns(provision, table, columns, { warn, sleep });}// Which of a new table's columns that went in the change set the table really has, with the MetadataId each createColumn answer@@ -992,10 +1303,12 @@ const STATE_CODE = { Active: 0, Inactive: 1 };// The state and the value the build gives each of a table's declared status reasons, in the spec's order: the declared state (Active// unless it says Inactive; any other word has always read as Active) and the declared `value`, else 100000000 + the reason's place in the// list. The data-model phase inserts each at these, and verify (lib/status-reasons-keys.js) holds a deployed reason to the same two.+// The state is the spec's own word, read as an own key of STATE_CODE: `constructor` or `toString` is another word, and reads as Active+// too — never as the inherited function, which no request can carry.function statusReasonTargets(entity) {return ((entity && entity.statusReasons) || []).map((statusReason, index) => ({statusReason,- stateCode: STATE_CODE[statusReason.state] !== undefined ? STATE_CODE[statusReason.state] : 0,+ stateCode: Object.hasOwn(STATE_CODE, statusReason.state) ? STATE_CODE[statusReason.state] : 0,value: typeof statusReason.value === 'number' ? statusReason.value : 100000000 + index,}));}@@ -1067,7 +1380,7 @@ function causeChain(err, maxDepth = 6) {// and the rebuild halted, because only the English words below were read. The code is the same in every language. A code is listed only// for the create that answers it, and only where the platform's reference gives it an "already exists" meaning for what that create// makes — never a generic code such as 0x80040216 ("An unexpected error occurred."), and never a neighbouring condition: a key over the-// same columns under another name (0x80060894, EntityKeyWithSelectedAttributesExists — the declared key is not there), a record that+// same columns under another name (0x80060894, EntityKeyWithSelectedAttributesExists — the declared key may not be there), a record that// already holds a key's values (0x80060892). Two codes are broader than the thing created — the name or the navigation property they speak// of can be held by something else — and each is listed for one create only, where a read that follows the refusal decides: 0x80044363// (SchemaNameisNotUnique) for the table create, 0x80072551 (NavigationPropertyAlreadyExists) for the 1:N relationship create. A listed@@ -1075,8 +1388,11 @@ function causeChain(err, maxDepth = 6) {// is skipped on it (a column's code can name a companion the platform makes beside the column, as its words can), and for a table or a// relationship it is only the cue to read what exists, which alone decides what is reused. The lists only ADD recognition:// isAlreadyExists keeps its 409 and English-word rules unchanged, and they still read an answer whatever code it carries, an unlisted one-// included — an English 0x80060894 answer ("An entity key with the selected attributes already exists on entity.") is still a skip, as it-// always was. Names and messages are the platform's reference:+// included. The one answer that never reaches them is a key create's 0x80060894: its English words ("An entity key with the selected+// attributes already exists on entity.") read as an already-exists answer, which made a build skip a key that was never created when the+// platform's message was in English, and stop when it was in another language, so the key step decides that code by the table's keys before+// anything reads its words (KEY_OVER_SAME_COLUMNS).+// Names and messages are the platform's reference:// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes// Lower case, because serviceCodeOf (lib/retry-policy.js) lower-cases what it reads: the platform writes a code in either case (the// reference spells 0x8004432B with a capital).@@ -1139,7 +1455,8 @@ const NO_CODES = Object.freeze(new Set());// column WAS made) carries a code that is not the create's. The code only ADDS recognition: the 409 and English-word rules are// the ones this function always had, and they apply whatever code the answer carries — a code of another create, a generic code or// a code the message only quotes does not count by itself, and does not stop the words from counting either. Kept deliberately-// narrow so a genuine failure (bad key attribute, etc.) still surfaces.+// narrow so a genuine failure (bad key attribute, etc.) still surfaces. A key create's 0x80060894 never reaches it: the key step+// decides that answer by the table's keys (KEY_OVER_SAME_COLUMNS), because its English words would read as an already-exists one.function isAlreadyExists(err, codes = NO_CODES) {if (!err) return false;const status = err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status));@@ -1436,13 +1753,19 @@ function makeRunner({ emit, total, throttle }) {const refusals = () => (budgeted ? throttle.declined().count : 0);const refusedBefore = refusals();const stopIfRefused = (phase) => { if (refusals() > refusedBefore) throw budgetStop(throttle, phase); };- const run = async (phase, label, fn, { recoverable = false, skipIf, settling = false } = {}) => {+ // `again`: { n, replaces } takes up, later in its phase, a step that already has a number — a status reason its table's lag deferred to the end+ // of the data-model phase (drainLagStatuses). Every step is one item of the plan whose length `total` is, so the step keeps the number it was+ // deferred under, and its outcome names the outcome it replaces (`replaces`): a printer counts the step once, by the outcome it ended with.+ // `skipIf` is handed the step's number, for a skip that defers the step.+ const run = async (phase, label, fn, { recoverable = false, skipIf, settling = false, again } = {}) => {if (!settling) stopIfRefused(phase);- const myN = (n += 1);+ const takenUp = !!again && Number.isInteger(again.n);+ const myN = takenUp ? again.n : (n += 1);+ const outcome = (event) => (takenUp ? { ...event, replaces: again.replaces } : event);emit({ phase, status: 'start', label, n: myN, total });try {const out = await fn();- emit({ phase, status: 'ok', label, n: myN, total });+ emit(outcome({ phase, status: 'ok', label, n: myN, total }));return out;} catch (err) {// Idempotency escape hatch: a create that fails only because the component already@@ -1453,12 +1776,12 @@ function makeRunner({ emit, total, throttle }) {// collision: an environment that does not declare a platform member cannot host the artifact// at all, and labelling that "(exists)" would tell the operator the exact opposite of what// happened. Boolean callers are unaffected.- const why = skipIf && skipIf(err);+ const why = skipIf && skipIf(err, myN);if (why) {- emit({ phase, status: 'skip', label: `${label} (${typeof why === 'string' ? why : 'exists'})`, n: myN, total });+ emit(outcome({ phase, status: 'skip', label: `${label} (${typeof why === 'string' ? why : 'exists'})`, n: myN, total }));return undefined;}- emit({ phase, status: 'error', label, n: myN, total, detail: String((err && err.message) || err) });+ emit(outcome({ phase, status: 'error', label, n: myN, total, detail: String((err && err.message) || err) }));throw new BuildHalt(`${phase} failed: ${(err && err.message) || err}${operatorRemedy(err)}`, { phase, code: (err && err.code) || 'sdk-error', recoverable, cause: err, retry: retryPolicyFor(err) });}};@@ -1525,6 +1848,10 @@ const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-works// message ends with "Do NOT re-run the create" and the SDK call that sets the level. Running this build again is the fix: it finds the table (it// is not created twice) and sets the level the way it does for any existing column with an explicit `required`.function operatorRemedy(err) {+ // A create refused with the lag of a table this attempt just created, still refused when the bounded check ran out (createInLagWindow,+ // recoverRefusedBatch, drainLagStatuses). Recognised by the error object itself, never by its words: the event the step reported while the+ // lease was held carries the SDK's message as it was, and only this halt — which the command prints after its lease is let go — says more.+ if (persistedLagRefusals.has(err)) return LAG_REMEDY;if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') {return ' — the table exists. Run the build again: it finds the table, does not create it again, and sets the required level of its primary name column (the call the message names is made for you).';}@@ -1692,6 +2019,19 @@ async function resolveAuthoringLanguage({ envUrl, languageCode, spec, warn, read});}+// The table probe's request (findExistingTable): one narrow read of a table by its logical name — and, with `includeKeys`, the identity of+// each of its alternate keys, its schema name and its columns, which are scalars, never a label:+// GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName&$expand=Keys($select=SchemaName,KeyAttributes)+// -> { "LogicalName": "contoso_project", "EntitySetName": "contoso_projects",+// "Keys": [ { "SchemaName": "contoso_CodeKey", "KeyAttributes": [ "contoso_code" ], "MetadataId": "<guid>" } ] }+// A quote in the name is doubled, as an OData string literal escapes it. Also the read of a table's keys after a key create the platform+// refused because another key is over the same columns (keyOverSameColumns).+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#retrieve-and-delete-alternate-keys+function tableProbeUrl(logical, { includeKeys = false } = {}) {+ const escaped = logical.replace(/'/g, "''");+ return `/EntityDefinitions(LogicalName='${escaped}')?$select=LogicalName,EntitySetName${includeKeys ? '&$expand=Keys($select=SchemaName,KeyAttributes)' : ''}`;+}+// Discover-then-create global choices, tables, columns, status reasons, alternate keys,// and relationships (idempotent). Returns captured maps used by sample data + later phases.// Does this table already exist? Returns { logicalName, entitySetName } or null.@@ -1724,10 +2064,9 @@ async function findExistingTable(provision, schemaName, { hasLocalizedLabels = fconst logical = String(schemaName).toLowerCase();const raw = provision && provision.dataverse;if (raw && typeof raw.get === 'function') {- const escaped = logical.replace(/'/g, "''");// Keys' identities are scalars, so they can ride this already-required probe// without a label-bearing read ahead of a localized create.- const url = `/EntityDefinitions(LogicalName='${escaped}')?$select=LogicalName,EntitySetName${includeKeys ? '&$expand=Keys($select=SchemaName,KeyAttributes)' : ''}`;+ const url = tableProbeUrl(logical, { includeKeys });// Retried only for a LOCALIZED entity, where the alternative to a conclusive answer is a halt.// For everything else one attempt then `findTables` is both cheaper and exactly the old// behaviour.@@ -1820,9 +2159,11 @@ async function provisionDataModel(args) {const carriedIn = new Set(owed.keys());const waitingKeys = [];const waitingStatuses = [];+ // The lag work of the tables this attempt creates ("The lag of a table this attempt just created", above). `now`, `sleep` and `random` are seams.+ const lag = lagContext(args);let result;try {- result = await provisionDataModelSteps(args, { owed, carriedIn, waitingKeys, waitingStatuses });+ result = await provisionDataModelSteps(args, { owed, carriedIn, waitingKeys, waitingStatuses, lag });} catch (err) {await payOwedLengths(args, owed, carriedIn, { halted: true, waitingKeys });throw err;@@ -1832,19 +2173,21 @@ async function provisionDataModel(args) {// Option labels must be read only AFTER every labelled schema create (including deferred keys).// Reading them inside the table loop can strip later creates' non-base-language labels.for (const status of waitingStatuses) await applyStatusReasons(args, status, result, true);+ // The status reasons a table this attempt created refused with its lag, read and sent again here for the same reason (drainLagStatuses).+ await drainLagStatuses(args, lag, result);return result;}-async function applyStatusReasons({ sdk, provision, runner, warn }, { entity, logical, languageCode }, result, checkExisting = false) {+async function applyStatusReasons({ sdk, provision, runner, warn }, { entity, logical, languageCode, window }, result, checkExisting = false) {const read = checkExisting ? await readStatusOptions(provision && provision.dataverse, logical) : {};if (read.failed && typeof warn === 'function') {warn(`could not read status reasons for ${logical} (${read.failed}); using the duplicate-protected insert instead`);}for (const { statusReason: sr, stateCode, value: pinned } of statusReasonTargets(entity)) {- (result.statusReasonValues[logical] = result.statusReasonValues[logical] || {})[sr.label] = { value: pinned, stateCode };- const same = (read.options || []).some((o) => o && o.Value === pinned && o.State === stateCode- && labelsByLcid(o.Label)[languageCode] === sr.label- && (sr.color === undefined || o.Color === sr.color));+ // The table's reasons by LABEL — the maker's text, which can be `__proto__` or `constructor` — in a null-prototype map, so each label is+ // an own entry (lib/own-keys.js). On a plain object the `__proto__` reason was never stored: its value object became the map's prototype.+ (result.statusReasonValues[logical] = result.statusReasonValues[logical] || Object.create(null))[sr.label] = { value: pinned, stateCode };+ const same = (read.options || []).some((o) => statusOptionIs(o, { pinned, stateCode, label: sr.label, color: sr.color, languageCode }));if (same) {runner.skip('data-model', `status reason ${entity.schemaName}: ${sr.label} (exists — reuse)`);continue;@@ -1852,7 +2195,83 @@ async function applyStatusReasons({ sdk, provision, runner, warn }, { entity, loawait runner.run('data-model', `status reason ${entity.schemaName}: ${sr.label}`, async () => {const value = await sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned, languageCode });result.statusReasonValues[logical][sr.label] = { value: typeof value === 'number' ? value : pinned, stateCode };- }, { recoverable: true, skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.statusReason) });+ }, {+ recoverable: true,+ skipIf: (err, step) => {+ if (isAlreadyExists(err, ALREADY_EXISTS_CODES.statusReason)) return true;+ // A table this attempt created (`window`): the insert refused with the table's lag is not sent again here, and its options are not read+ // here either — that read carries labels. It is queued for the end of the phase (drainLagStatuses), with the number of its step, which+ // the drain takes up again; the step is a skip that says so.+ const code = window ? lagCodeOf(err) : null;+ if (!code) return false;+ sayLagOnce(window, `status reason ${entity.schemaName}: ${sr.label}`, code);+ window.lag.statuses.push({ window, entity, logical, languageCode, sr, stateCode, pinned, original: err, code, step });+ return LAG_SKIP;+ },+ });+ }+}++// Whether a status option the environment holds is the status reason the spec declares: its pinned value, its state, its label in the authoring+// language — and its colour, when the spec declares one.+function statusOptionIs(o, { pinned, stateCode, label, color, languageCode }) {+ return !!o && o.Value === pinned && o.State === stateCode && labelsByLcid(o.Label)[languageCode] === label && (color === undefined || o.Color === color);+}++// The status reasons a table this attempt created refused with its lag (applyStatusReasons), after every labelled create of the phase: for each,+// the step its insert was deferred under, taken up again — it keeps that step's number, so the phase's steps stay within the plan's total — which+// reads the table's status options and acts on what the read proves —+// - the pinned value there, with the declared state, label and colour: adopted, nothing sent;+// - the pinned value there with another state, label or a declared colour it does not have: the original refusal, and nothing is sent, adopted+// or updated — that option is not this reason;+// - the pinned value absent from a list that holds the stock reason 1 or 2, every option of which carries an integer value: sent again, after a+// wait, up to 4 times; a resend refused with the lag is read again, refused otherwise is that failure (an "already exists" answer is the+// step's skip);+// - a read that proves nothing — the pinned value held twice, an option without a value, no stock reason: read again, after a wait.+// The table's budget is the one its column work used, if any; a budget spent with the reason still missing stops the build with the original+// refusal (persistedLagRefusals), a read that failed with that failure. A step that throws stops the phase there: the reasons after it are not tried.+// GET /EntityDefinitions(<id>)/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)+// → { "value": [{ "LogicalName": "statuscode", "OptionSet": { "Options": [{ "Value": 1, "State": 0, "Label": {…}, "Color": null }, …] } }] }+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/statusoptionmetadata+async function drainLagStatuses({ sdk, runner, warn }, lag, result) {+ for (const queued of lag.statuses.splice(0)) {+ const { window, entity, logical, languageCode, sr, stateCode, pinned, original, code, step } = queued;+ await runner.run('data-model', `status reason ${entity.schemaName}: ${sr.label} (retried after the other schema creates)`, async () => {+ let resends = 0;+ for (let waits = 0; ;) {+ if (lagSpent(window.budget)) throw persisted(original);+ const read = await lagRead(window, `/EntityDefinitions(${window.tableId})/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)`, (body) => {+ const status = body && Array.isArray(body.value) && body.value.find((a) => a && String(a.LogicalName).toLowerCase() === 'statuscode');+ return status && status.OptionSet ? status.OptionSet.Options : undefined;+ }, 'the status reasons');+ if (read.kind === 'failed') throw read.error;+ // An option is USABLE when it is an object with an integer `Value`; only a list of usable options proves the pinned value absent — an+ // option without a value could be this very reason. Two options at the pinned value cannot both be it: that proves nothing either way.+ const options = read.kind === 'list' ? read.items : null;+ const atPinned = options ? options.filter((o) => o && o.Value === pinned) : [];+ if (atPinned.length === 1) {+ if (!statusOptionIs(atPinned[0], { pinned, stateCode, label: sr.label, color: sr.color, languageCode })) throw original;+ if (typeof warn === 'function') warn(`status reason ${entity.schemaName}: ${sr.label} was refused (HTTP 400 ${code}) and then found, so it is reused`);+ return;+ }+ const usable = !!options && options.every((o) => o && typeof o === 'object' && Number.isInteger(o.Value));+ const absent = usable && atPinned.length === 0 && options.some((o) => o.Value === 1 || o.Value === 2);+ if (lagSpent(window.budget)) throw persisted(original);+ if (absent && resends >= LAG_SINGLE_RESENDS) throw persisted(original);+ if (!(await lagWait(window, waits++))) throw persisted(original);+ if (!absent) continue;+ if (typeof runner.stopIfRefused === 'function') runner.stopIfRefused('data-model');+ resends += 1;+ try {+ const value = await charged(window, () => sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned, languageCode }));+ result.statusReasonValues[logical][sr.label] = { value: typeof value === 'number' ? value : pinned, stateCode };+ return;+ } catch (again) {+ if (!lagCodeOf(again)) throw again;+ }+ }+ // The same step as the insert the lag deferred — not one more: it keeps that step's number, and its outcome replaces the deferral's skip.+ }, { recoverable: true, skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.statusReason), again: { n: step, replaces: 'skip' } });}}@@ -1890,13 +2309,87 @@ async function payOwedLengths({ runner, sdk, provision, spec, warn, sleep }, owereturn outcomes;}+// The code of a key create the platform refuses because ANOTHER key of the table is over the same columns — it allows one key per set of+// columns: EntityKeyWithSelectedAttributesExists, in the reference's words+// HTTP 400 {"error":{"code":"0x80060894","message":"An entity key with the selected attributes already exists on entity."}}+// That does not say the DECLARED key is there: the key over those columns may be another one. Its English words read as an already-exists+// answer all the same (isAlreadyExists), so when the platform's message was in English the build skipped the key — which was then never+// created, and the build's verification found it missing — while the same answer in another language stopped the build with the platform's+// words. Which of the two happened depends on the language of the MESSAGE, not of the build or the environment: measured live, an environment+// whose only language is Spanish answered this code in English. So the key step decides this code, whatever the language of the answer and+// before any word is read, from the keys the table holds (keyOverSameColumns).+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes+const KEY_OVER_SAME_COLUMNS = '0x80060894';++// What the table's keys say of a key create refused with KEY_OVER_SAME_COLUMNS, read once, by the table probe's request (tableProbeUrl):+// { state: 'declared' } a key of the declared schema name, in any case, over exactly the declared columns (alternateKeyMatches): the+// declared key is there, and the step is a skip — as for a key the probe found before the create;+// { state: 'other', holder } a key of another name over exactly those columns (alternateKeyOverColumns): the table's key,+// `{ SchemaName, KeyAttributes }`, beside which the declared key cannot be made;+// { state: 'unknown' } the read failed, or showed no key over exactly those columns: nothing says which key the platform means, so+// nothing is guessed, and the create's own error stops the build.+// The read carries no label — it is the narrow read the build makes of a table ahead of its labelled creates — so a create in several+// languages that follows it keeps its labels (findExistingTable). The client resolves a status that is not 2xx and throws only for a request+// that got no answer; neither throws here.+async function keyOverSameColumns(provision, logical, key) {+ const raw = provision && provision.dataverse;+ if (!raw || typeof raw.get !== 'function') return { state: 'unknown' };+ let res;+ try { res = await raw.get(tableProbeUrl(logical, { includeKeys: true })); } catch { return { state: 'unknown' }; }+ const keys = res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.Keys) ? res.body.Keys : null;+ if (!keys) return { state: 'unknown' };+ if (alternateKeyMatches(keys, key)) return { state: 'declared' };+ const holder = alternateKeyOverColumns(keys, key);+ return holder ? { state: 'other', holder } : { state: 'unknown' };+}++// The stop for a key the platform refused because the key `holder` of the table is over the same columns: the declared key, the key the+// table has (as the platform names it), the columns, and what to do. Which advice is right depends on what the spec says of the holder's name:+// - nothing: the holder is not the spec's — declare it under its own name, or delete it where nothing uses it;+// - another of the table's keys under that name over the SAME columns: the spec itself asks for two keys over one set of columns, so deleting+// the holder is no way out (the next build makes it again) — one of the two has to go, or change its columns;+// - another of the table's keys under that name over OTHER columns: the spec is valid, and the key in the environment drifted from it (the spec+// changed that key's columns, or the key was made otherwise). Its name exists, so the build skipped it (0x80060893) and does not change its+// columns; it has to be reconciled — deleted, where nothing relies on it as it is — before the declared key can be made. Asking to drop or+// change a declaration would be wrong here: keeping only that key leaves it skipped again, and verification still finds its columns wrong.+function keyOverSameColumnsStop(entity, logical, key, holder) {+ const lower = (list) => (list || []).map((c) => String(c).toLowerCase());+ const columns = lower(key.columns);+ const over = `the same column${columns.length === 1 ? '' : 's'} (${columns.join(', ')})`;+ const head = `alt key ${entity.schemaName}.${key.schemaName} was not created: the table ${logical} already has the key ${holder.SchemaName} over ${over}`;+ const named = (entity.alternateKeys || []).filter((k) => k && k !== key && String(k.schemaName).toLowerCase() === holder.SchemaName.toLowerCase());+ if (named.some((k) => sameKeyColumnSet(k.columns, key.columns))) {+ return `${head}, and the spec declares both — Dataverse allows one key per set of columns. Keep one of them in the table's alternateKeys, or give the other different columns.`;+ }+ if (named.length) {+ const declared = lower(named[0].columns);+ return `${head}, and Dataverse allows one key per set of columns. The spec declares ${holder.SchemaName} over other columns (${declared.join(', ')}): `+ + `the key in the environment is not the one the spec describes, and a build does not change the columns of a key that exists. `+ + `Reconcile ${holder.SchemaName} first: if nothing relies on it as it is (an integration that writes records by it, say), delete it in Power Apps (the table's Keys) and run the build again — it then creates both keys as the spec declares them.`;+ }+ return `${head}, and Dataverse allows one key per set of columns. To keep that key, declare it as it is — set this key's schemaName to '${holder.SchemaName}' — `+ + `or, if ${holder.SchemaName} is a leftover that nothing uses, delete it in Power Apps (the table's Keys) and run the build again.`;+}+// One alternate key: a narrated step. The SDK has no key lister, so a re-run that finds the key already there gets an-// already-exists answer, which is a skip and not a halt. The same step wherever the key is made — with its table, or after the-// length of the table's name column (createWaitingKeys).-function alternateKeyStep({ runner, sdk, entity, logical, key, languageCode }) {- return runner.run('data-model', `alt key ${entity.schemaName}.${key.schemaName}`,- () => sdk.createAlternateKey(logical, { schemaName: key.schemaName, displayName: key.displayName || key.schemaName, keyAttributes: (key.columns || []).map((x) => x.toLowerCase()), languageCode }),- { recoverable: true, skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.alternateKey) });+// already-exists answer, which is a skip and not a halt. The same step wherever the key is made — with its table, ahead of the+// length of the table's name column (alternateKeyAheadOfLength), or after it (createWaitingKeys). A refusal because another key is over+// the key's columns (KEY_OVER_SAME_COLUMNS) is decided by the table's keys instead: a skip where they show the declared key, a stop that+// says what to do where they show another (a refusal: a run again meets the same key), and the create's own error otherwise. Either stop+// goes the way a key the platform refuses always went: a failed step, which halts the phase.+function alternateKeyStep({ runner, sdk, provision, entity, logical, key, languageCode }) {+ // What the table's keys said of a KEY_OVER_SAME_COLUMNS refusal; unset for any other answer, which is read as it always was.+ let overSameColumns;+ return runner.run('data-model', `alt key ${entity.schemaName}.${key.schemaName}`, async () => {+ try {+ return await sdk.createAlternateKey(logical, { schemaName: key.schemaName, displayName: key.displayName || key.schemaName, keyAttributes: (key.columns || []).map((x) => x.toLowerCase()), languageCode });+ } catch (err) {+ if (serviceCodeOf(err) !== KEY_OVER_SAME_COLUMNS) throw err;+ overSameColumns = await keyOverSameColumns(provision, logical, key);+ if (overSameColumns.state === 'other') throw refusal(keyOverSameColumnsStop(entity, logical, key, overSameColumns.holder), { cause: err });+ throw err;+ }+ }, { recoverable: true, skipIf: (err) => (overSameColumns ? overSameColumns.state === 'declared' : isAlreadyExists(err, ALREADY_EXISTS_CODES.alternateKey)) });}// What the build can tell of an alternate key over a table's name column with that column at the length the spec asks — the one wording every@@ -1948,11 +2441,14 @@ function keyRoomAtAskedLength(entity, key) {// the key, if the length the spec asks leaves room for it, and where that run is refused the same way, the platform's error and the sizes of// the key's columns say why.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys-async function alternateKeyAheadOfLength({ runner, sdk, entity, logical, key, languageCode, warn }) {+async function alternateKeyAheadOfLength({ runner, sdk, provision, entity, logical, key, languageCode, warn }) {try {- await alternateKeyStep({ runner, sdk, entity, logical, key, languageCode });+ await alternateKeyStep({ runner, sdk, provision, entity, logical, key, languageCode });} catch (err) {- if (typeof warn === 'function') {+ // A key refused because another key of the table is over its columns (KEY_OVER_SAME_COLUMNS) was refused for its columns, not for its+ // size: the stop says what to do about that, and the advice below — about the length of the name column — does not apply to it.+ const refusedForItsColumns = causeChain(err).some((e) => serviceCodeOf(e) === KEY_OVER_SAME_COLUMNS);+ if (typeof warn === 'function' && !refusedForItsColumns) {const column = String(entity.primaryAttribute.schemaName).toLowerCase();const asked = askedPrimaryNameLength(entity);// Said from the languages the label goes out in, which is what keeps the key from waiting. A key that does not wait is a map that does not@@ -2017,7 +2513,7 @@ async function keyMustWaitForShorterNameColumn({ provision, entity, logical, key// failed with, which the halt declares), the code of the service's answer, a reset, an explicit "never retry" — and never the halt's own// words or code. The retry then finds the length still owed (`owedLengths`), sets it, and asks for the key.// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/define-alternate-keys-entity#create-alternate-keys-async function createWaitingKeys({ runner, sdk }, waitingKeys, outcomes) {+async function createWaitingKeys({ runner, sdk, provision }, waitingKeys, outcomes) {for (const { entity, logical, key, languageCode } of waitingKeys) {const outcome = outcomes.get(logical);if (outcome && !outcome.ok && !outcome.left) {@@ -2040,7 +2536,7 @@ async function createWaitingKeys({ runner, sdk }, waitingKeys, outcomes) {);await runner.run('data-model', `alt key ${entity.schemaName}.${key.schemaName}`, async () => { throw halt; }, { recoverable: true });}- await alternateKeyStep({ runner, sdk, entity, logical, key, languageCode });+ await alternateKeyStep({ runner, sdk, provision, entity, logical, key, languageCode });}}@@ -2067,7 +2563,7 @@ async function settleOwedLengths({ sdk, provision, spec, owed, warn, sleep } = {// `owed` is the Map provisionDataModel keeps (see there): this attempt's tables whose length is to be set, and those an earlier attempt// left unset. `carriedIn` is the set of the second kind as the phase found them; `waitingKeys` collects the alternate keys that wait for// a length step, for createWaitingKeys to make once the steps have run.-async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true }, { owed, carriedIn, waitingKeys, waitingStatuses }) {+async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true }, { owed, carriedIn, waitingKeys, waitingStatuses, lag }) {// `lookupLabels` records the label each spec lookup column carries once this phase is done// (`<referencing>|<lookup logical>` -> { label }), so a later phase that repairs something derived// from it — an existing form's cell label — repairs it to what the column now says.@@ -2239,10 +2735,21 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la}// A table THIS build created gets its ordinary columns in one change set (createColumnsInOneRequest). A table found after its// create is not given one: nothing shows what it already holds, and the per-column path below skips what exists.+ // The same table is in its lag window (lagWindow): its column creates and status reason inserts refused with the table's lag are read and+ // sent again within its budget. Every other table — one that existed, one found after its create — has none, and nothing changes for it.+ const window = createdTable ? lagWindow(lag, provision, e, createdTable) : null;+ // A change set whose bounded check ran out with a column still missing (`terminal`): the column loop sends no further column, and stops at+ // the first one the check did not confirm.+ let inlineTerminal = null;+ // A change set the table's lag refused, whose missing columns a read then proved absent (`fallback`): the column loop creates them one by one,+ // but each of those creates is one of the check's own sends — made only while the table's budget has room, and charged to it — and once the+ // budget is spent, by them or by the reads and waits between them, the loop stops at the next column it has not confirmed, as `terminal` does.+ let inlineFallback = null;+ const stopIfRefused = typeof runner.stopIfRefused === 'function' ? () => runner.stopIfRefused('data-model') : undefined;if (createdTable && inlineEnabled) {const inlineSet = inlineColumnsOf(buildable, { primaryName: e.primaryAttribute && e.primaryAttribute.schemaName, tableLogical: logical });if (inlineSet.length) {- inlineConfirmed = await createColumnsInOneRequest({+ const inline = await createColumnsInOneRequest({sdk,provision,table: { metadataId: createdTable.metadataId, logicalName: createdTable.logicalName || logical },@@ -2252,8 +2759,12 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, lawarn,sleep,// A runner without the check (a stand-in for one) never stops here.- stop: typeof runner.stopIfRefused === 'function' ? () => runner.stopIfRefused('data-model') : undefined,+ stop: stopIfRefused,+ lagTable: window,});+ inlineConfirmed = inline.map;+ inlineTerminal = inline.terminal || null;+ inlineFallback = inline.fallback || null;}}// columns: every buildable column (all scalar types + Customer; Lookup comes from a@@ -2273,9 +2784,18 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, lafor (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'})`,- () => inlineConfirmed.get(c) || (c.type === 'Customer'- ? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode })- : sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode))),+ () => {+ const confirmed = inlineConfirmed.get(c);+ if (confirmed) return confirmed;+ if (inlineTerminal) throw inlineTerminal;+ // Proved absent is not permission to create once the budget is spent: the change set's refusal, here, before any further POST.+ if (inlineFallback && lagSpent(window.budget)) throw persisted(inlineFallback.original);+ if (c.type === 'Customer') return sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode });+ // A Customer column is created by an action of its own, which the lag was not seen on: it is not in the window.+ return createInLagWindow(() => sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode)), {+ window, column: c, stop: stopIfRefused, warn, charge: !!inlineFallback && inlineFallback.columns.has(c),+ });+ },{ skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.column) }));if (existingTable) {const existingColMeta = new Map(existingColRows.map((c) => [String(c.logicalName || c.schemaName || '').toLowerCase(), c]));@@ -2450,7 +2970,8 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la// proof keeps that duplicate-protected path. A fresh insert records the server-returned value.// The same statusReasonTargets supply both the insert and verification state/value contract.if (e.statusReasons && e.statusReasons.length) {- const status = { entity: e, logical, languageCode: resolvedLanguageCode };+ // `window`: a table this attempt created, whose inserts refused with its lag are queued for the end of the phase (applyStatusReasons).+ const status = { entity: e, logical, languageCode: resolvedLanguageCode, window };if (existingTable && provision.dataverse && typeof provision.dataverse.get === 'function') waitingStatuses.push(status);else await applyStatusReasons({ sdk, provision, runner, warn }, status, result);}@@ -2477,10 +2998,10 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, lawaitingKeys.push({ entity: e, logical, key: k, languageCode: resolvedLanguageCode });continue;}- await alternateKeyAheadOfLength({ runner, sdk, entity: e, logical, key: k, languageCode: resolvedLanguageCode, warn });+ await alternateKeyAheadOfLength({ runner, sdk, provision, entity: e, logical, key: k, languageCode: resolvedLanguageCode, warn });continue;}- await alternateKeyStep({ runner, sdk, entity: e, logical, key: k, languageCode: resolvedLanguageCode });+ await alternateKeyStep({ runner, sdk, provision, entity: e, logical, key: k, languageCode: resolvedLanguageCode });}}@@ -2923,7 +3444,9 @@ function buildSeedGroup({ spec, e, records, statusReasonValues }) {// captured during the data-model phase (insertStatusValue); if that phase was skipped this run// the value is unknown — halt loudly instead of silently inserting a default status.if (raw && raw.statusReason) {- const sv = (statusReasonValues[e.schemaName.toLowerCase()] || {})[raw.statusReason];+ // An OWN entry of the captured values (lib/own-keys.js): a label such as `constructor` that was not captured — the data-model phase+ // did not run — must halt here like any other, not read the inherited member as a captured value.+ const sv = ownValue(statusReasonValues[e.schemaName.toLowerCase()], raw.statusReason);if (!sv) throw refusal(`record sets statusReason '${raw.statusReason}' on ${e.schemaName}, but its status value wasn't captured — include the data-model phase (don't --skip data-model) so the custom status reason is created and its option value captured`);body.statuscode = sv.value; body.statecode = sv.stateCode;}diff --git a/plugins/model-apps/scripts/lib/output-redaction.js b/plugins/model-apps/scripts/lib/output-redaction.jsindex cc0572b4b..b8bb93fef 100644--- a/plugins/model-apps/scripts/lib/output-redaction.js+++ b/plugins/model-apps/scripts/lib/output-redaction.js@@ -30,17 +30,22 @@// (guardFatalErrors).// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),// `writeFileAtomic` (lib/apply-snapshot-store.js: the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records) and the SDK's workspace storage — every file the bundle writes goes through its-// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.+// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). The three writers clean what they are given as the file gets it (redactFileData): a text as a text; BYTES — every view of an ArrayBuffer: a+// Buffer, any typed array, a DataView — and a string given with a `hex`, `base64` or `base64url` encoding as the bytes written, a hit masked with as many `*` in a copy. Each call is read on its own: an append is+// not read together with the file it extends. tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.// - not covered, by design: a token another process obtained (`pac` has its own); a piece of a token SHORTER than MIN_TOKEN_PART_LENGTH at the edge of a write or before a cut (it would be taken out of ordinary words — a// token written in two pieces leaves the shorter piece when it is under 24 characters; the first one is written before the second exists); a piece from the MIDDLE of a token that neither begins nor ends a needle (a// token written in three pieces or more, or cut at both ends); the start of a write read through an escape's letters (it is read on the first reading only: a literal backslash before its first letter leaves that letter);// the piece of a token that an escape cut between two writes leaves on its far side when that piece is shorter than 24 characters (the escape stays whole, so its characters count for neither piece);-// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a part alone, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);-// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); bytes given to a FILE writer (the-// writers below clean text); the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than white space-// and ESC between two of its characters.+// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a substring that is not a whole part — or of a part shorter than 24 characters, or of a base64+// spelling —, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);+// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); a token split between two+// appends to a file, and the part of a chunk an append that failed part way left in the file (it is of the cleaned chunk, and is not taken back); what a child process writes, a write of the file system the+// plugin does not list (tests/output-token-writers.test.js), the files listed there as data handed on as it is (the settings a person gave, the package pac is given), and a file the SDK writes other than+// through `writeTextAtomic`; the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than+// white space and ESC between two of its characters.//// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as@@ -50,8 +55,9 @@// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).//-// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64, standard and URL-safe, at each of the three byte alignments it can have inside a longer value (a-// whole `Authorization` header, a body encoded once more), and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.+// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64 and that of each of its parts of 24 characters or more, standard and URL-safe, at each of the three+// byte alignments it can have inside a longer value (a whole `Authorization` header, a body encoded once more, the one part a diagnostic complains about) — the characters made of its own bits, not the ones beside them that+// also hold bits of their neighbours, nor the padding — and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.//// A TOKEN CUT SHORT. A formatter that cuts a long text keeps its beginning, and the end of what it kept can be the beginning of a token: util.inspect prints at most 10,000 characters of a string and then says how many it// left out (`'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters`), and a text cut to a length by hand ends with an ellipsis (`...`, `…`). Where a text says it was cut, the run before it that BEGINS a needle — 24@@ -69,7 +75,7 @@// a dot, an ellipsis, while a needle is being read), and its pieces are the alignments the pass already follows; the start of a text is read for at most the longest needle's length; bytes are read in one pass of the// same kind, needle by needle in lockstep. A text that would need more is not guessed at: the search fails, and every caller fails closed (tests/output-redaction.test.js and tests/output-token-forms.test.js measure// all of it). A text that holds no token comes back as the very string, and bytes as the very bytes.-const { inspect, types: { isUint8Array } } = require('node:util');+const { inspect, types: { isUint8Array, isArrayBufferView } } = require('node:util');// What takes the place of a token, or of a part of one, in a text.const TOKEN_MARKER = '<token>';@@ -106,12 +112,15 @@ const HTML_ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "/*** The other spellings of `token` that are taken out of what the process writes, each an exact needle read as any needle is (with folds and escapes in it):- * - its base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), as it is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so the token's- * first byte can stand at any of three places in a group and each place spells it differently. Of each, only the characters made of the token's own bits — a character that also holds bits of the byte before or- * after it changes with that byte, so it is left out at either end;+ * - the base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), of the token AND of each of its parts of 24 characters or more (needlesOf) — a diagnostic can encode the one+ * part it complains about as well as the whole header — as each is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so a needle's first byte can stand at any of three+ * places in a group and each place spells it differently. Of each, only the characters made of the needle's own bits — a character that also holds bits of the byte before or after it changes with that byte,+ * so it is left out at either end: a complete encoding of a part keeps that character and its padding (`<token>Q==`), and so does one of the token;* - its percent-encoded spelling (upper- and lower-case hex) and its HTML spelling, and those of each of its parts of 24 characters or more — only where they differ from it: a JWT is base64url and dots, which* neither changes, so a JWT has base64 spellings only.- * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more, as a part is; a spelling that is already a needle of the token is not repeated. The longest first.+ * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more — the length of the SPELLING, so that a token of 18 characters keeps the 24 characters of its first alignment; a part shorter than 24 characters+ * is no needle and so has no spelling — and a spelling that is already a needle of the token, or another needle's spelling, is not repeated. The longest first. needlesOf is not changed by any of it: the Dataverse+ * client scrubs the answers it fails with by that list alone (lib/sdk-http-client.js).* @param {string} token* @returns {string[]}*/@@ -122,13 +131,15 @@ function spellingsOf(token) {const keep = (spelled) => {if (spelled.length >= MIN_TOKEN_PART_LENGTH && !plain.includes(spelled)) spellings.add(spelled);};- const bytes = Buffer.from(token, 'utf8');- for (let offset = 0; offset < 3; offset += 1) {- // With `offset` bytes before the token, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)- // hold the token's bits and nothing else.- const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));- keep(standard);- keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));+ for (const needle of plain) {+ const bytes = Buffer.from(needle, 'utf8');+ for (let offset = 0; offset < 3; offset += 1) {+ // With `offset` bytes before the needle, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)+ // hold the needle's bits and nothing else.+ const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));+ keep(standard);+ keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));+ }}for (const needle of plain) {keep(percentSpelling(needle, true));@@ -822,6 +833,56 @@ function redactOutput(text) {return redactWith(preparedNow(), text, true);}+// What a file writer is told when the data it was given could not be checked: a fixed sentence, never the data, which may hold the token.+const UNCHECKED_FILE_DATA = 'output-redaction: the data given to a file writer could not be checked for an access token, so it was not written';++/**+ * `data` as a file writer of the plugin writes it (lib/safe-fs.js `writeFileSafe` and `appendFileSafe`, lib/apply-snapshot-store.js `writeFileAtomic`), with every token this process has obtained taken out — whatever+ * `fs.writeFileSync` and `fs.appendFileSync` take, read as what they write:+ * - a text, as redactOutput reads it (a whole text: a needle's start at its end and its end at its start go too);+ * - BYTES — any view of an ArrayBuffer: a Buffer, a Uint8Array, a Uint16Array or any typed array, a DataView, from this realm or another (`util.types.isArrayBufferView`) — read byte for byte, only the bytes the view+ * covers (`[byteOffset, byteOffset + byteLength)`), and a hit masked with as many `*` in a COPY: the file keeps its length and the caller's memory is not written into. Node writes every such view as its raw bytes+ * (measured on Node 20 and 22: `writeFileSync` writes a Uint16Array and a DataView byte for byte), so a view is read as those bytes and never through `Buffer.from(view)`, which turns a Uint16Array into one byte+ * an element;+ * - a string given with `encoding` `hex`, `base64` or `base64url`, which the writer decodes into the bytes it writes: those bytes are read and, on a hit, masked and returned as a Buffer — the writer must then+ * write it WITHOUT that encoding (it would decode it again).+ * The very `data` when it holds no token, and — before anything is looked at — when no token has been obtained: a process that has none writes what it always wrote, and gets the same errors (a detached view, which+ * Node writes as nothing, included). A view whose bytes cannot be read (detached) or a string that cannot be decoded, when a token has been obtained, is not written: this throws, with a message that does not+ * hold the data, before the writer writes anything — never the data unchecked, and never another text in its place. A raw ArrayBuffer is no view: it is passed on, and Node refuses it (ERR_INVALID_ARG_TYPE).+ * Nothing is carried from one call to the next — two appends of a token's two halves are two writes, read each alone — and nothing is read from the file.+ * @template T+ * @param {T} data+ * @param {{ encoding?: string } | string | null} [opts]+ * @returns {T | Buffer}+ */+function redactFileData(data, opts) {+ if (obtained.size === 0) return data;+ const encoding = opts && typeof opts.encoding === 'string' ? opts.encoding : '';+ if (typeof data === 'string' && BINARY_ENCODINGS.test(encoding)) {+ let decoded;+ try {+ decoded = Buffer.from(data, encoding);+ } catch {+ throw new TypeError(UNCHECKED_FILE_DATA);+ }+ if (decoded.length === 0) return data;+ const masked = maskWith(preparedNow(), decoded, true, 0);+ return masked === decoded ? data : masked;+ }+ if (isArrayBufferView(data)) {+ let raw;+ try {+ raw = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);+ } catch {+ throw new TypeError(UNCHECKED_FILE_DATA);+ }+ if (raw.length === 0) return data;+ const masked = maskWith(preparedNow(), raw, true, 0);+ return masked === raw ? data : masked;+ }+ return redactOutput(data);+}+/*** What a guarded stream writes in place of `chunk`: a text as `redactOutput` makes it, and bytes with every token this process has obtained masked (maskTokenBytes, with the edges of the write) — the very bytes when they* hold none. `from`: where an escape the stream's last write ended inside is finished (guardStream). Anything else is returned as it is.@@ -906,13 +967,17 @@ function guardStream(stream, redact = redactWritten) {}// The memory is this write's before the stream takes it, so that a callback the stream calls at once, and writes from, reads on from it. A write the stream REFUSES — it throws (an encoding it does not know, a// chunk that is no text and no bytes, a stream already ended) — wrote nothing, so the memory goes back to what the last written one left, unless a write made inside it has moved it on; the error is the- // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands.+ // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands. A refused write also takes back its own count: a write made inside another one that the+ // stream refuses as well wrote nothing either, and its count left behind would read, to the outer write, as a write the stream took — the outer one would then keep a memory nothing was written with.writes += 1;const mine = writes;try {return write.call(this, given, ...rest);} catch (error) {- if (writes === mine) open = before;+ if (writes === mine) {+ open = before;+ writes = mine - 1;+ }throw error;}};@@ -1044,6 +1109,7 @@ module.exports = {redactTokens,maskTokenBytes,redactOutput,+ redactFileData,guardStream,makeWritesBlocking,guardFatalErrors,diff --git a/plugins/model-apps/scripts/lib/own-keys.js b/plugins/model-apps/scripts/lib/own-keys.jsnew file mode 100644index 000000000..69a60fdd0--- /dev/null+++ b/plugins/model-apps/scripts/lib/own-keys.js@@ -0,0 +1,25 @@+'use strict';+// Reading a map keyed by NAMES — a dashboard's, a persona's, a status reason's label, a page's key — that a maker writes freely or a service+// returns. Any of those can be exactly a member of Object.prototype (`__proto__`, `constructor`, `toString`, `hasOwnProperty`, …), and each is a+// legal name. A plain object `{}` answers every one of them whether or not it was ever stored: `map.constructor` is the Object function,+// `map.toString` a function, `map.__proto__` the prototype itself — all truthy, so a "was it built?" lookup answers yes and hands the member on+// as the id. Writing `map.__proto__ = value` calls the inherited setter instead of storing an entry: JSON.stringify then leaves it out, and an+// object value becomes the map's prototype.+//+// The rule the plugin follows:+// - a map it BUILDS from such names is a null-prototype object (`Object.create(null)`): every name is an own key, `__proto__` included, and a+// name it does not hold reads as undefined. JSON.stringify writes its own keys in the same order whatever the prototype, so the bytes of a+// result or record of ordinary names do not change;+// - a map it READS by such a name, which can come from elsewhere — parsed JSON, a caller, a `|| {}` fallback — is read with `ownValue`, which+// answers an entry only when the map holds it as its own.+// JSON.parse makes every key of its text an own data property, `__proto__` included (it never calls the setter), so an own read of parsed JSON+// finds what the text holds.+// See: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects++// The value `map` holds under `key` as its OWN property, or undefined: for a key it does not hold, for an inherited member, and for anything+// that is not an object (undefined, null, a string).+function ownValue(map, key) {+ return map !== null && typeof map === 'object' && Object.hasOwn(map, key) ? map[key] : undefined;+}++module.exports = { ownValue };diff --git a/plugins/model-apps/scripts/lib/page-binding-targets.js b/plugins/model-apps/scripts/lib/page-binding-targets.jsindex 3f4fe1080..e8a3f8cc6 100644--- a/plugins/model-apps/scripts/lib/page-binding-targets.js+++ b/plugins/model-apps/scripts/lib/page-binding-targets.js@@ -53,18 +53,22 @@ const referenceConnectorKey = (id) => (typeof id === 'string' && CONNECTOR_API_Iconst bindingConnectorKey = (id) => (typeof id === 'string' && (CONNECTOR_API_ID.test(id) || CONNECTOR_NAME.test(id)) ? connectorKey(id) : null);// The pages a build writes that state a binding: [{ key, name, connectorBindings?, actionBindings? }], with the lists as the spec states them, in the spec's order. A page with no source the build can deploy is not-// written, and a page that states no entry has nothing to check. A changed-only run writes the pages it selected and any page another one navigates to (the build makes an absent target first, from its own-// spec entry, so it may have to write it), and no other.+// written, and a page that states no entry has nothing to check.+// A changed-only run (`changedOnly.selectedKeys`) writes the pages it selected, and a page another one navigates to only when that page is ABSENT: the pages phase makes an absent target first, from its own spec+// entry, bindings and all, and leaves one that exists as it is (sdk-build.js, `uploadedThisRun`). Which targets exist is settled by the pages phase, after this check has run, so the run may be told which of its+// pages are deployed (`changedOnly.deployedKeys`: the changed-only flow passes the pages its last verified apply recorded). A target it is told of is left out; one it is not told of may be absent, so it is checked —+// what is not known is never read as "it exists". A target it was told of and that the pages phase finds absent after all (deleted in Maker since) is checked there, before it is made (pagesMadeUnchecked).function pagesStatingBindings(spec, { changedOnly } = {}) {const pages = Array.isArray(spec && spec.pages) ? spec.pages : [];const selected = changedOnly && Array.isArray(changedOnly.selectedKeys) ? new Set(changedOnly.selectedKeys) : null;+ const deployed = new Set(selected && Array.isArray(changedOnly.deployedKeys) ? changedOnly.deployedKeys : []);const navigatedTo = new Set(pages.flatMap((page) => ((page && page.navigatesTo) || []).map((target) => target && target.targetKey)));const out = [];for (const page of pages) {const source = normalizePageSource(page);if (!(source && source.kind === 'tsx' && source.codeFile)) continue;const key = page.key || page.name;- if (selected && !selected.has(key) && !navigatedTo.has(key)) continue;+ if (selected && !selected.has(key) && !(navigatedTo.has(key) && !deployed.has(key))) continue;const lists = statedPageBindings(page);if (!Object.values(lists).some((list) => list.length)) continue;out.push({ key, name: page.name, ...lists });@@ -72,6 +76,22 @@ function pagesStatingBindings(spec, { changedOnly } = {}) {return out;}+// The pages the pages phase is about to MAKE (`made`: the keys of the absent navigation targets it creates) that state a binding the check before writing did not judge, because the run was told the page+// is deployed (pagesStatingBindings): each is checked before the first is made, as that check would have checked it, and by what the attempt has already read (bindingReads). Every other page the run+// writes was checked before it wrote anything, so this is [] for a run that was told nothing, and for a full build.+function pagesMadeUnchecked(spec, { changedOnly, made }) {+ const checked = new Set(pagesStatingBindings(spec, { changedOnly }).map((page) => page.key));+ return pagesStatingBindings(spec).filter((page) => made.has(page.key) && !checked.has(page.key));+}++// The pages that state a binding and that the check before writing leaves out only because the run was told they are deployed (pagesStatingBindings): what a dry run, which has no pages phase to+// find one absent, asks the environment about before it leaves them out (sdk-build.js, confirmDeployedTargets). [] for a run told nothing, and for a full build.+function pagesLeftOutAsDeployed(spec, changedOnly) {+ if (!changedOnly || !Array.isArray(changedOnly.deployedKeys)) return [];+ const checked = new Set(pagesStatingBindings(spec, { changedOnly }).map((page) => page.key));+ return pagesStatingBindings(spec, { changedOnly: { ...changedOnly, deployedKeys: undefined } }).filter((page) => !checked.has(page.key));+}+// The names the pages state for one kind of binding: each once, as the first page spells it (the service compares them without regard to case, and the match here is made in lower case).function namesOf(pages, kind) {const identity = PAGE_BINDINGS[kind];@@ -157,6 +177,14 @@ async function readDefinitions(reader, ids) {return definitions;}+// What one attempt of a build has read of what the pages' bindings name, for readBindingTargets: per kind, Map<lower-cased name, { row } | { none: true } | { problem }>, and the custom connectors'+// definitions by id. The check before writing and the pages phase's check of a navigation target it finds it has to make (sdk-build.js) share one, so a name is read ONCE per attempt, and what+// that read answered — a row, no row, a failure — stands for every check of the attempt. A later check never asks again: it adds no request, and a second read that fails can never turn what+// the first one proved (a reference for another connector) into "not checked". A new attempt (the build's re-run of a halt) starts a new one, and reads again.+function bindingReads() {+ return { references: new Map(), apis: new Map(), definitions: new Map() };+}+// What the environment has for the names `pages` state: { references, apis, definitions, problems }.// references Map<lower-cased logical name, { connectorId, connected?, customConnectorId? }> of the connection references (`connectionreference` rows) — or null when no page states a connector binding, or// the read failed. Each piece is kept only as the row PROVES it, and anything else is left out — which judgeBindingTargets reads as "not known", never as "fine":@@ -169,30 +197,56 @@ async function readDefinitions(reader, ids) {// apis Map<lower-cased unique name, { isFunction, boundEntity? }> of the Custom APIs (`customapi` rows) — or null likewise// definitions Map<custom connector id, Set<operation id> | { problem }> (readDefinitions) of the custom connectors a binding that calls operations goes through — or null when there is none// problems { references?, apis? }: why a read failed, as the service said it. A failed read does not stop the other, and is never an empty answer.+// unread { references?, apis? }: Map<lower-cased name, why> — present only beside answered names, which only an attempt's LATER check meets (below): the names an earlier read of the attempt could not+// read. They are not checked and are said so, by name, while the names that were read are judged.// Only the rows of the names asked for are kept, whatever the service answered.+// `seen` (bindingReads) is what the attempt has read so far: a name it holds is not asked for again, and its answer — a row, no row, a failure — is the one this check is given. One check alone (a+// fresh `seen`) reads every name once and answers exactly as a single read always did: the rows found, or null and why the read failed.// A connection reference row as the Web API answers it (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/connectionreference); `connectionid` is null while it has no// connection, and `_customconnectorid_value` null when no custom connector is recorded for it:// { "connectionreferencelogicalname": "contoso_msnweather", "connectorid": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "connectionid": "shared-msnweather-…", "_customconnectorid_value": null }// and a Custom API row (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapi), `bindingtype` 0 Global, 1 Entity, 2 EntityCollection:// { "uniquename": "contoso_ApproveOrder", "isfunction": false, "bindingtype": 1, "boundentitylogicalname": "contoso_item" }-async function readBindingTargets(provision, pages) {+async function readBindingTargets(provision, pages, seen = bindingReads()) {const targets = { references: null, apis: null, definitions: null, problems: {} };const reader = provision && typeof provision.queryRecords === 'function' ? provision : null;const read = async (kind, entity, select, column, keyOf, valueOf, target) => {const names = namesOf(pages, kind);if (!names.length) return;- try {- if (!reader) throw new Error('the rows cannot be read here');- const wanted = new Set(names.map((name) => name.toLowerCase()));- const found = new Map();- for (const row of await readNamed(reader, entity, select, column, names)) {- const key = row && typeof keyOf(row) === 'string' ? keyOf(row).trim().toLowerCase() : '';- if (key && wanted.has(key) && !found.has(key)) found.set(key, valueOf(row));+ const known = seen[target];+ const fresh = names.filter((name) => !known.has(name.toLowerCase()));+ if (fresh.length) {+ try {+ if (!reader) throw new Error('the rows cannot be read here');+ const wanted = new Set(fresh.map((name) => name.toLowerCase()));+ const found = new Map();+ for (const row of await readNamed(reader, entity, select, column, fresh)) {+ const key = row && typeof keyOf(row) === 'string' ? keyOf(row).trim().toLowerCase() : '';+ if (key && wanted.has(key) && !found.has(key)) found.set(key, valueOf(row));+ }+ for (const name of wanted) known.set(name, found.has(name) ? { row: found.get(name) } : { none: true });+ } catch (error) {+ const problem = String((error && error.message) || error);+ for (const name of fresh) known.set(name.toLowerCase(), { problem });+ }+ }+ const answers = names.map((name) => [name.toLowerCase(), known.get(name.toLowerCase())]);+ const why = [...new Set(answers.map(([, answer]) => answer.problem))];+ // Every name unread for one reason — the one read failed, as a single read's failure always read: null, and why.+ if (why.length === 1 && why[0] !== undefined) {+ targets.problems[target] = why[0];+ return;+ }+ const rows = new Map();+ for (const [name, answer] of answers) {+ if (answer.row) rows.set(name, answer.row);+ else if (answer.problem !== undefined) {+ if (!targets.unread) targets.unread = {};+ if (!targets.unread[target]) targets.unread[target] = new Map();+ targets.unread[target].set(name, answer.problem);}- targets[target] = found;- } catch (error) {- targets.problems[target] = String((error && error.message) || error);}+ targets[target] = rows;};await read('connectorBindings', 'connectionreference', ['connectionreferencelogicalname', 'connectorid', 'connectionid', '_customconnectorid_value'], 'connectionreferencelogicalname',(row) => row.connectionreferencelogicalname,@@ -214,7 +268,11 @@ async function readBindingTargets(provision, pages) {if (reference && reference.customConnectorId && operationsOf(entry).length && !ids.includes(reference.customConnectorId)) ids.push(reference.customConnectorId);}}- if (ids.length) targets.definitions = await readDefinitions(reader, ids);+ if (ids.length) {+ const fresh = ids.filter((id) => !seen.definitions.has(id));+ if (fresh.length) for (const [id, definition] of await readDefinitions(reader, fresh)) seen.definitions.set(id, definition);+ targets.definitions = new Map(ids.map((id) => [id, seen.definitions.get(id)]));+ }}await read('actionBindings', 'customapi', ['uniquename', 'isfunction', 'bindingtype', 'boundentitylogicalname'], 'uniquename',(row) => row.uniquename,@@ -231,12 +289,20 @@ const pagesWords = (pages) => `${plural(pages, 'page', 'pages')} ${pages.map((pa// has with no connection, the operations a custom connector there does not define, the Custom APIs it has none of, the Custom APIs that are not as the binding says. `refuse` is a connector conflict// and nothing else: a binding that is refused is not judged further.// unchecked [{ what, text }] for what could not be checked, and why: a page at a time, what its references' rows did not say (their connector, whether they have a connection, which custom connector they-// are for), then the operations of a binding whose custom connector's definition could not be read; then each read that failed. Missing evidence is never a finding and never "compatible".+// are for), then the operations of a binding whose custom connector's definition could not be read, and the names of its bindings an earlier read of the attempt could not read (`unread`);+// then each read that failed. Missing evidence is never a finding and never "compatible".function judgeBindingTargets(pages, targets) {const findings = [];const unchecked = [];const nameOf = (entry, identity) => (entry && typeof entry[identity] === 'string' && entry[identity].trim() ? entry[identity].trim() : undefined);const sameName = (names, name) => names.some((seen) => seen.toLowerCase() === name.toLowerCase());+ // Why a name was not read, when an earlier read of the attempt could not read it while other names were read (readBindingTargets `unread`) — undefined for a name that was read.+ const unreadWhy = (target, name) => (targets.unread && targets.unread[target] ? targets.unread[target].get(name.toLowerCase()) : undefined);+ const noteUnread = (byWhy, why, name) => {+ const names = byWhy.get(why) || [];+ if (!sameName(names, name)) names.push(name);+ byWhy.set(why, names);+ };for (const page of pages) {const at = { key: page.key, name: page.name };const connectors = (page.connectorBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.connectorBindings));@@ -248,11 +314,19 @@ function judgeBindingTargets(pages, targets) {const connectorUnknown = [];const connectionUnknown = [];const customUnknown = [];+ // The names that were not read at all, by why: not checked, and said so by name — never "not there".+ const referencesUnread = new Map();+ const apisUnread = new Map();const missingApis = [];const mismatches = [];if (targets.references instanceof Map) {for (const entry of connectors) {const name = nameOf(entry, PAGE_BINDINGS.connectorBindings);+ const notRead = unreadWhy('references', name);+ if (notRead !== undefined) {+ noteUnread(referencesUnread, notRead, name);+ continue;+ }const reference = targets.references.get(name.toLowerCase());if (!reference) {if (!sameName(missingReferences, name)) missingReferences.push(name);@@ -313,9 +387,15 @@ function judgeBindingTargets(pages, targets) {if (connectorUnknown.length) unchecked.push({ what: 'reference connectors', text: `this environment's ${plural(connectorUnknown, 'row', 'rows')} for connection ${plural(connectorUnknown, 'reference', 'references')} ${joined(connectorUnknown)} did not give a connector id this build can read (absent, or not of the form /providers/Microsoft.PowerApps/apis/shared_<name>), so whether ${bindingsWords(connectorUnknown)} ${plural(connectorUnknown, 'goes', 'go')} through the connector ${plural(connectorUnknown, 'it was', 'they were')} made for was not checked` });if (connectionUnknown.length) unchecked.push({ what: 'reference connections', text: `this environment's ${plural(connectionUnknown, 'row', 'rows')} for connection ${plural(connectionUnknown, 'reference', 'references')} ${joined(connectionUnknown)} did not say, in a form this build can read, whether ${plural(connectionUnknown, 'it has', 'they have')} a connection, so that was not checked for page ${quoted(page.name)}` });if (customUnknown.length) unchecked.push({ what: 'custom connector definitions', text: `the operations that ${bindingsWords(customUnknown)} call were not checked: this environment does not name a custom connector for ${plural(customUnknown, 'its connection reference', 'their connection references')}, and only a custom connector's definition is read here (a connector the platform publishes defines the same operations in every environment of its cloud)` });+ for (const [why, names] of referencesUnread) unchecked.push({ what: 'connection references', text: `could not read this environment's connection references (${shown(why)}), so ${bindingsWords(names)} ${plural(names, 'was', 'were')} not checked against them` });if (targets.apis instanceof Map) {for (const entry of actions) {const name = nameOf(entry, PAGE_BINDINGS.actionBindings);+ const notRead = unreadWhy('apis', name);+ if (notRead !== undefined) {+ noteUnread(apisUnread, notRead, name);+ continue;+ }const api = targets.apis.get(name.toLowerCase());if (!api) {if (!sameName(missingApis, name)) missingApis.push(name);@@ -344,6 +424,7 @@ function judgeBindingTargets(pages, targets) {});}for (const mismatch of mismatches) findings.push({ severity: 'warn', kind: 'api-mismatch', page: at, binding: mismatch.binding, text: mismatch.text });+ for (const [why, names] of apisUnread) unchecked.push({ what: 'Custom APIs', text: `could not read this environment's Custom APIs (${shown(why)}), so ${plural(names, 'Custom API binding', 'Custom API bindings')} ${names.map(quoted).join(', ')} of page ${quoted(page.name)} ${plural(names, 'was', 'were')} not checked against them` });}const unread = (what, kind, problem, listed) => {if (!problem) return;@@ -355,4 +436,9 @@ function judgeBindingTargets(pages, targets) {return { findings, unchecked };}-module.exports = { connectorKey, pagesStatingBindings, readBindingTargets, judgeBindingTargets, definedOperations };+// What a dry run says of the pages it was told are deployed when it cannot find out whether they still are (sdk-build.js, confirmDeployedTargets): it checks them, as if the build will make them.+function unconfirmedDeployedText(pages, why) {+ return `could not tell whether ${pagesWords(pages)}, recorded as deployed, ${plural(pages, 'is', 'are')} still in this environment (${shown(why)}), so ${plural(pages, 'its', 'their')} bindings are checked as if the build will make ${plural(pages, 'it', 'them')}`;+}++module.exports = { connectorKey, pagesStatingBindings, pagesMadeUnchecked, pagesLeftOutAsDeployed, bindingReads, readBindingTargets, judgeBindingTargets, unconfirmedDeployedText, definedOperations };diff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.jsindex 583865540..374b23b0f 100644--- a/plugins/model-apps/scripts/lib/provision-input.js+++ b/plugins/model-apps/scripts/lib/provision-input.js@@ -156,7 +156,8 @@ function validateProvisionInput(input) {errors.push(`entity '${e.schemaName}': column.schemaName is required and must be a string`);}- if (c.type && !TYPE_MAP[c.type]) {+ // An own key of TYPE_MAP, as in validateAppSpec: a member of Object.prototype (`constructor`, `toString`, …) is no column type.+ if (c.type && !Object.hasOwn(TYPE_MAP, c.type)) {errors.push(`entity '${e.schemaName}': column '${c.schemaName || ''}' has unknown type '${c.type}'`);}diff --git a/plugins/model-apps/scripts/lib/retry-policy.js b/plugins/model-apps/scripts/lib/retry-policy.jsindex 542f15953..1705c57d5 100644--- a/plugins/model-apps/scripts/lib/retry-policy.js+++ b/plugins/model-apps/scripts/lib/retry-policy.js@@ -89,7 +89,8 @@ const EMBEDDED_ANSWER = /^(?:HTTP (\d{3}) from|Transport failure reaching) (\S+)// The errors that are typed and WRAP a failure they carry as their `cause` — attached NOT enumerably (the SDK's attachCause, a native Error's `cause`), which// causeChain reads all the same — so what decides is that failure, never the wrapper's code or its words (which name what the maker named). One today:// WEB_RESOURCE_UNVERIFIED, the SDK's error for a web resource it wrote whose PUBLISHED content it could not confirm, and the build's own error around it-// (lib/sdk-build.js, unconfirmedWebResource). The row exists; a run again writes its content again by id. So:+// (lib/sdk-build.js, unconfirmedWebResource). The row exists; a run again writes its content again by id (the page manifest: unless its published copy+// already holds that content, which it keeps). So:// - it carries a failure — its publish's, or that of the read-back of what was published: that failure is judged by the rule above, a lock refusal (429// `0x80071151`), a 503 or a reset is run again, a 400, 401, 403, 404, a 412 (the SDK's typed VERSION_CONFLICT) or another typed refusal is not;// - it carries none: the read-back answered content that is not what was written, or no content — the write did not apply, or whether it did isdiff --git a/plugins/model-apps/scripts/lib/safe-fs.js b/plugins/model-apps/scripts/lib/safe-fs.jsindex 152450cfa..a0b847140 100644--- a/plugins/model-apps/scripts/lib/safe-fs.js+++ b/plugins/model-apps/scripts/lib/safe-fs.js@@ -27,8 +27,9 @@ const fs = require('node:fs');const path = require('node:path');const crypto = require('node:crypto');// Everything this module writes has the access tokens the process obtained taken out first: it is the one writer of the build's journal and status file, of what a download writes, of a page's file and its deployed copy-// (tests/output-token-writers.test.js lists every other write in the plugin and why none of them can carry a token). Text only: bytes a caller gives are written as they are.-const { redactOutput } = require('./output-redaction.js');+// (tests/output-token-writers.test.js lists every other write in the plugin and why none of them can carry a token). A text is cleaned as a text; bytes — any view of an ArrayBuffer, or a string given with a `hex`,+// `base64` or `base64url` encoding — are read as the bytes the file gets, and a hit is masked with as many `*` (redactFileData).+const { redactFileData } = require('./output-redaction.js');const UNSAFE = 'UNSAFE_OUTPUT';@@ -51,6 +52,17 @@ function sleepSync(ms) {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);}+// `data` with the access tokens the process obtained taken out (redactFileData), and the options to write it with. A string given with a `hex`, `base64` or `base64url` encoding that held a token comes back as the+// masked bytes it stands for, and those are written WITHOUT that encoding: `writeFileSync` and `appendFileSync` would otherwise decode them a second time. Every other option, and the encoding of anything else, is+// the caller's. Throws, before anything is created or written, for data that cannot be checked — never writes it unchecked.+function checkedForTokens(data, opts) {+ const checked = redactFileData(data, opts);+ if (checked === data || typeof data !== 'string' || typeof checked === 'string') return { data: checked, opts };+ const decoded = { ...opts };+ delete decoded.encoding;+ return { data: checked, opts: decoded };+}+function renameWithRetry(fsImpl, from, to) {for (let i = 0; ; i += 1) {try {@@ -234,7 +246,7 @@ function assertPlainFileTarget(filePath, opts) {function writeFileSafe(filePath, data, opts) {if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to write: no path was given', 'uninspectable');- data = redactOutput(data);+ ({ data, opts } = checkedForTokens(data, opts));const fsImpl = (opts && opts.fs) || fs;const resolved = path.resolve(filePath);const realDir = assertSafeOutputDir(path.dirname(resolved), { fs: fsImpl });@@ -444,7 +456,8 @@ function removeTreeWithRetry(dir, opts) {function appendFileSafe(filePath, data, opts) {if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to append: no path was given', 'uninspectable');- data = redactOutput(data);+ // The chunk is checked on its own, before anything is opened: the file is not read, and a token split between two appends is two chunks. A failed check writes nothing.+ ({ data, opts } = checkedForTokens(data, opts));const fsImpl = (opts && opts.fs) || fs;const resolved = path.resolve(filePath);const realDir = assertSafeOutputDir(path.dirname(resolved), { fs: fsImpl });diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 529edba9f..0d83683c0 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -19,9 +19,10 @@ const { resolveAppSource } = require('./app-source-path.js');const { readPageOwnership, recordPageCreation, recordPagePending, readPendingCreations, completePendingCreations, creationIds } = require('./page-ownership-records.js');const { readPublishedPages, writePublishedPages, sameFileVersions } = require('./page-publish-records.js');const { leftOnDiskWarning } = require('./left-on-disk.js');-// The pages lock is taken through the snapshot lease's exclusive create-and-reclaim, and reclaimed only from a build that is provably gone.-const { acquireLease, releaseLease } = require('./apply-snapshot-store.js');-const { ownerStamp, ownerState, describeOwner } = require('./process-owner.js');+// The pages lock: two files (one keyed without regard to case, one spelled as every earlier release spells it), each taken through the snapshot+// lease's exclusive create-and-reclaim and reclaimed only from a build that is provably gone; and the build lease an apply holds outside it+// (lib/app-operation-lease.js).+const { acquireAppPagesLease, withAppBuildLease, applyWorkspaceOf } = require('./app-operation-lease.js');const { unreadableAnswer } = require('./collection-answers.js');// normalizePageSource: read the page source from the discriminated `source` field (v2) or the// legacy top-level `codeFile` (pre-migration). PHASES: canonical ordered phase list — imported@@ -58,7 +59,7 @@ const {statedPageBindings,} = require('./app-spec.js');const { PHASES } = require('./stages.js');-const { pagesStatingBindings, readBindingTargets, judgeBindingTargets } = require('./page-binding-targets.js');+const { pagesStatingBindings, pagesMadeUnchecked, pagesLeftOutAsDeployed, bindingReads, readBindingTargets, judgeBindingTargets, unconfirmedDeployedText } = require('./page-binding-targets.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');const {isMainForm,@@ -138,12 +139,13 @@ const { DASHBOARD_LAUNCHER_URL, adoptLiveSitemap, chromeByTargetKey, describeSitconst { buildPromptSpec } = require('./ai-prompt.js');const { odataLit } = require('./odata.js');const { isRestrictedSolution } = require('./system-solutions.js');-const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComponentsFor, applyAppMainForms, explainAppPushWarnings } = require('./app-components.js');+const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComponentsFor, applyAppMainForms, explainAppPushWarnings, savedPageRows } = require('./app-components.js');const { appWriteTables, appPushTables, preAppTables, publishTablesXml, readSavedNotPublished, describeSavedNotPublished, readAppFormChartTables, describePreAppRefusal, describeUnreadAppComponents } = require('./table-publish.js');const { hasUnsyncedEdits } = require('./unsynced-edits.js');const { createSolutionMembership, ensureSolutionComponent } = require('./solution-membership.js');const { openUnconfirmedWebResources } = require('./web-resource-records.js');const { openDashboardCreations } = require('./dashboard-creation-records.js');+const { ownValue } = require('./own-keys.js');const { navigationEntryKind, navigationHolds, navigationIsPagesOnly, navigationVerdict } = require('./app-navigation.js');const { isAppTextMap, appTextKind, localizedAppText } = require('./app-header-text.js');// The build's retry policy (retry-policy.js): every halt below is raised with what a run again may do — RETRY.NEVER, or a policy decided from the failure it wraps — and every failure the engine@@ -531,9 +533,10 @@ function commandDef(entityLogical, cmds, webResources) {return { entityLogicalName: entityLogical, commandBars };}-// Group an entity's commands (keyed by lowercased entity logical name).+// Group an entity's commands (keyed by lowercased entity logical name). A null-prototype map: the name is the spec's text, and+// `(map[k] = map[k] || []).push(…)` on a plain object throws for `constructor` or `__proto__` (it reads the inherited member).function commandsByEntity(spec) {- const byEntity = {};+ const byEntity = Object.create(null);for (const c of spec.commands || []) {const k = String(c.entity).toLowerCase();(byEntity[k] = byEntity[k] || []).push(c);@@ -1163,7 +1166,8 @@ function defaultAppIconSvg(appName) {// The row is therefore never created again (a second create of the name is refused), and its content may be what was written, the old content, or// none. What the build does about it is the same at every site that writes one (the spec's web resources, the generated app icon, the page manifest):// it records the row — in the run's result, and in the workspace (lib/web-resource-records.js), so that the run that follows writes its content again-// by id instead of reusing it untouched — adds it to the solution as the success path does, and stops with what a run again does.+// by id instead of reusing it untouched (the page manifest: unless its published copy already holds what that run would write, which it keeps) — adds it+// to the solution as the success path does, and stops with what a run again does.const isUnconfirmedWrite = (e) => Boolean(e) && e.code === 'WEB_RESOURCE_UNVERIFIED' && typeof e.id === 'string' && e.id.length > 0;// The SDK's answer to a write by an id whose row is gone: HTTP 404 (`ensureSuccess` throws it as a ConnectionError).const isGoneRow = (e) => Boolean(e) && e.code === 'CONNECTION_ERROR' && e.statusCode === 404;@@ -1173,10 +1177,17 @@ const contentOf = (options) => (options.contentBase64 !== undefined ? { contentB// that recovers it), then the plugin's — what this build did with the row and what a run again does, which makes that call. Its code is the SDK's, so the// runner's halt carries it, and the SDK's error is its cause: the build's retry reads that as the wrapper it is (lib/retry-policy.js, CAUSE_WRAPPER_CODES),// judged by the failure the SDK's error carries, and run again when it carries none.-function unconfirmedWebResource(error, { name, recorded, inSolution }) {+// What a run again does is not the same at every site. The spec's web resources and the generated icon are written again by id whatever was published+// (writeOwnedWebResource). The page manifest is first compared with its PUBLISHED copy, and written again only where that copy is not the content the run+// would write (persistPageManifest, `comparesPublished`): live, a manifest created and never published — each of its publishes refused — was read back+// with that content by the run that followed (the build's own retry), and kept, its record cleared. So its stop says so, and does not promise a write.+function unconfirmedWebResource(error, { name, recorded, inSolution, comparesPublished = false }) {const solution = inSolution === true ? 'added it to the solution' : `could not add it to the solution (${(inSolution && inSolution.message) || inSolution}; a run again adds it)`;+ const nextRun = comparesPublished+ ? 'it reads the published copy and keeps it if it already holds the content that build would write; otherwise it writes the content again by that id, publishes it and reads it back (the call the message names is made for you)'+ : 'it writes the content again by that id, publishes it and reads it back (the call the message names is made for you)';const remedy = recorded- ? `this build recorded the row as its own and ${solution}. Its publication is UNCONFIRMED, not lost: run the build again — it writes the content again by that id, publishes it and reads it back (the call the message names is made for you).`+ ? `this build recorded the row as its own and ${solution}. Its publication is UNCONFIRMED, not lost: run the build again — ${nextRun}.`: `this build ${solution}, but could not save its local recovery record. Its publication is UNCONFIRMED, not lost: this build will not automatically retry it without that record. Write its content again by the id above in Power Apps once the cause is resolved; keep the same writable build workspace for automatic recovery.`;// SDK updates report only the id; the build also knows the authored name, which is what a maker needs to find the resource.const detail = error.webResourceName ? error.message : `Web resource '${name}' (${error.id}): ${error.message}`;@@ -1188,12 +1199,13 @@ function unconfirmedWebResource(error, { name, recorded, inSolution }) {}// Records a row the SDK wrote and could not confirm, puts it in the solution, and answers the error to stop the step with (unconfirmedWebResource).-// The record is written FIRST: it is local, and it is what the next run needs whatever happens to the add.-async function keepUnconfirmedWebResource(error, { name, unconfirmed, addToSolution }) {+// The record is written FIRST: it is local, and it is what the next run needs whatever happens to the add. `comparesPublished` is the page manifest's:+// the next run compares it with its published copy before it writes it again (see unconfirmedWebResource).+async function keepUnconfirmedWebResource(error, { name, unconfirmed, addToSolution, comparesPublished = false }) {const recorded = unconfirmed.note(name, error.id);let inSolution = true;try { await addToSolution(error.id); } catch (e) { inSolution = e; }- return unconfirmedWebResource(error, { name, recorded, inSolution });+ return unconfirmedWebResource(error, { name, recorded, inSolution, comparesPublished });}// A receipt authorizes only its original id, never a different row that came to hold the same name after it. This check costs nothing@@ -1350,7 +1362,7 @@ async function persistPageManifest(provision, spec, keyToId, sol, appUnique, exi}return (await provision.createWebResource({ name, displayName: `${spec.app.name} Page Manifest`, type: 'js', content })).id;} catch (e) {- if (isUnconfirmedWrite(e)) throw await keepUnconfirmedWebResource(e, { name, unconfirmed, addToSolution });+ if (isUnconfirmedWrite(e)) throw await keepUnconfirmedWebResource(e, { name, unconfirmed, addToSolution, comparesPublished: true });throw e;}};@@ -1500,16 +1512,31 @@ async function checkNavigationBeforeWriting(spec, { provision, phases, changedOn// - a reference or a Custom API that is not there, a reference that has no connection, an operation a binding calls that the custom connector there does not define, a Custom API of the other kind or bound// to another table, and a read that failed are SAID, by name, and the build goes on: the page is written with its binding (a reference made, or given its connection, later makes the page work without a// rebuild), and an ordinary read failure says only that the bindings were not checked. A refused throttle wait is still the attempt's budget stop, checked by its runner before any mutation.-// Only a run that has the pages phase writes a binding, and a changed-only run writes the pages it selected (pagesStatingBindings). A spec that states none reads nothing.-async function readPageBindingVerdict(spec, { provision, phases, changedOnly }) {+// Only a run that has the pages phase writes a binding, and a changed-only run writes the pages it selected and the navigation targets it has to make (pagesStatingBindings). A spec that states none reads nothing.+// `seen` is what the attempt has read of what bindings name (bindingReads); the pages phase's check of a target it makes is given the same one.+async function readPageBindingVerdict(spec, { provision, phases, changedOnly, seen }) {if (!phases.includes('pages')) return null;- const pages = pagesStatingBindings(spec, { changedOnly });+ return judgePageBindings(provision, pagesStatingBindings(spec, { changedOnly: bindingCheckScope(phases, changedOnly) }), seen);+}++// What a run is told of the pages that are deployed (`changedOnly.deployedKeys`, pagesStatingBindings) is heeded only by a run whose pages phase is its FIRST writer — the changed-only fast apply runs that+// phase alone (lib/changed-only-flow.js). A target the run was told of and that the pages phase finds absent is checked there, before it is made (pagesMadeUnchecked); in such a run that is still before+// anything is written, so the refusal says so truly. A run with an earlier phase (the solution, the tables, the app) would have written them by then, so it is not told: it checks every navigation target+// before it writes anything, as every run did before it could be told. A phase this build does not know is taken to come first.+function bindingCheckScope(phases, changedOnly) {+ if (!changedOnly || changedOnly.deployedKeys === undefined) return changedOnly;+ const pagesWriteFirst = phases.every((phase) => PHASES.indexOf(phase) >= PHASES.indexOf('pages'));+ return pagesWriteFirst ? changedOnly : { ...changedOnly, deployedKeys: undefined };+}++// What the environment has for the names `pages` state, judged (lib/page-binding-targets.js): null when no page states one, which reads nothing. A name `seen` already holds is not read again.+async function judgePageBindings(provision, pages, seen) {if (!pages.length) return null;- return judgeBindingTargets(pages, await readBindingTargets(provision, pages));+ return judgeBindingTargets(pages, await readBindingTargets(provision, pages, seen));}-async function checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly, warn }) {- const verdict = await readPageBindingVerdict(spec, { provision, phases, changedOnly });+// The apply's answer to a verdict: a conflict stops the build, and all else is said.+function haltOnPageBindingConflicts(verdict, warn) {if (!verdict) return;const refused = verdict.findings.filter((finding) => finding.severity === 'refuse');if (refused.length) {@@ -1524,10 +1551,50 @@ async function checkPageBindingsBeforeWriting(spec, { provision, phases, changedif (typeof warn === 'function') for (const text of [...verdict.unchecked.map((u) => u.text), ...verdict.findings.map((finding) => finding.text)]) warn(text);}+async function checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly, warn, seen }) {+ haltOnPageBindingConflicts(await readPageBindingVerdict(spec, { provision, phases, changedOnly, seen }), warn);+}++// A dry run has no pages phase, which is what finds a navigation target absent (reconcilePageIds: the spec's page id, or the manifest's, that the environment still lists). So for each target a+// changed-only run was told is deployed (`changedOnly.deployedKeys`) and would leave unread (pagesLeftOutAsDeployed), the dry run asks the environment, read only, whether the page is still there —+// never taking the record of an earlier apply as proof. Two reads, made only when there is such a target:+// GET <webresource set>?$select=webresourceid,content&$filter=name eq '<app>_pagemanifest'&$top=1 the manifest (readPageManifest): each page's key and id+// GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid,name,componentstate&$filter=uxagentprojectid eq <id> or …+// the pages in the SAVED layer, a never-published one included (savedPageRows)+// A target whose page answers to the id the spec or the manifest gives it is there: its binding is left unread, as the apply leaves it. One whose ids answer to no page is absent — the apply+// makes it — and one these reads cannot settle (no id, a read that fails) is not known to be there: both are checked, as if the build will make them, and a read that failed is said. Answers the+// run's `changedOnly` with `deployedKeys` keeping only the targets found.+async function confirmDeployedTargets(spec, { provision, phases, changedOnly, warn }) {+ const scoped = bindingCheckScope(phases, changedOnly);+ const leftOut = pagesLeftOutAsDeployed(spec, scoped);+ if (!leftOut.length) return scoped;+ const found = new Set();+ let unsettled;+ try {+ const { manifest } = await readPageManifest(provision, appUniqueName(spec));+ const manifestIds = new Map(((manifest && manifest.pages) || []).map((entry) => [entry.key, entry.pageId]));+ const specIds = new Map((spec.pages || []).map((page) => [page.key || page.name, page.pageId]));+ const idsOf = new Map(leftOut.map((page) => [page.key, [specIds.get(page.key), manifestIds.get(page.key)].filter((id) => typeof id === 'string' && FORM_GUID_RE.test(id)).map((id) => id.toLowerCase())]));+ const wanted = [...new Set([...idsOf.values()].flat())];+ if (wanted.length && !(provision.dataverse && typeof provision.dataverse.get === 'function')) unsettled = 'the pages cannot be read here';+ else if (wanted.length) {+ const rows = await savedPageRows(provision.dataverse, wanted, { label: 'the pages recorded as deployed' });+ for (const page of leftOut) if (idsOf.get(page.key).some((id) => rows.has(id))) found.add(page.key);+ }+ } catch (error) {+ unsettled = (error && error.message) || String(error);+ }+ if (unsettled !== undefined && typeof warn === 'function') warn(unconfirmedDeployedText(leftOut, unsettled));+ const unfound = new Set(leftOut.filter((page) => !found.has(page.key)).map((page) => page.key));+ return unfound.size ? { ...scoped, deployedKeys: scoped.deployedKeys.filter((key) => !unfound.has(key)) } : scoped;+}+// The dry run's share: say on the page's own line that an apply would stop there, and why. The line is marked as a view the build would refuse is (annotateLivePlan): `? unknown` with the reason, and `wouldHalt` so-// the summary counts it among the steps that would stop the build. What an apply would only say is said the same way.+// the summary counts it among the steps that would stop the build. What an apply would only say is said the same way. The pages judged are those an apply judges before it writes anything+// (readPageBindingVerdict) — save a target the run was told is deployed that the dry run does not find in the environment (confirmDeployedTargets): the apply's pages phase makes that one, and+// stops on it (pagesMadeUnchecked), so the plan judges it too.async function checkPageBindingsInPlan(plan, spec, { provision, phases, changedOnly, warn }) {- const verdict = await readPageBindingVerdict(spec, { provision, phases, changedOnly });+ const verdict = await readPageBindingVerdict(spec, { provision, phases, changedOnly: await confirmDeployedTargets(spec, { provision, phases, changedOnly, warn }) });if (!verdict) return;const refusedBy = new Map();for (const finding of verdict.findings.filter((f) => f.severity === 'refuse')) refusedBy.set(finding.page.name, [...(refusedBy.get(finding.page.name) || []), finding.text]);@@ -1541,44 +1608,8 @@ async function checkPageBindingsInPlan(plan, spec, { provision, phases, changedOif (typeof warn === 'function') for (const text of [...verdict.unchecked.map((u) => u.text), ...verdict.findings.filter((f) => f.severity !== 'refuse').map((f) => f.text)]) warn(text);}-// SINGLE-MACHINE advisory lockfile over the pages protocol (design §9, DESCOPED from a cross-machine guarantee).-// A courtesy to stop two LOCAL builds of the same app racing to CREATE duplicate pages; correctness does-// NOT depend on it — the convergence spine (fail-closed enumeration + create-absent-first + persist-after--// each-create) makes any re-run idempotent. Atomic exclusive create picks one winner; if the lock already-// exists we HALT — unless the build that took it is PROVABLY GONE. A build killed outright (SIGKILL, "End-// task", a timeout, a power cut) cannot release its lock, and used to leave every later build stopped on it-// until a person deleted the file; the lock now records who took it (lib/process-owner.js: pid, host, platform,-// and on Linux the process's start time), and a later build releases it itself, and says so (`deps.warn`),-// when that process is no longer running on this machine.-//-// "Provably" is the whole rule, and every doubt keeps the lock, in the words it has always had: a lock whose-// pid still runs, one made on another machine, platform or pid namespace — or where the maker's or this-// process's pid namespace cannot be told (on Linux a pid that is not found proves nothing unless both name-// the same pid space) — one with no readable record (a release before the record existed, a damaged file, a-// field of it that is not what it should be) is never taken — and none is ever taken by AGE, since a-// live build may be paused as long as a laptop sleeps. The take-over itself is the snapshot lease's-// (apply-snapshot-store.js acquireLease): one claim file makes exactly one of several builds that start-// together the winner, and a lock that changed meanwhile is left alone. Release is OWNER-CHECKED: remove-// only if the file still holds OUR exact token. Cross-machine/worktree concurrency for the SAME app is-// UNSUPPORTED. `deps` = seams: now, warn, and owner (the process-owner.js seams).-function acquireAppPagesLease(wsDir, appUnique, deps = {}) {- const now = deps.now || (() => Date.now());- const file = `pages-${String(appUnique).replace(/[^A-Za-z0-9_-]/g, '_')}.lock`;- const lockPath = path.join(wsDir, file);- const lease = acquireLease(wsDir, { file, now, stamp: ownerStamp({ ...deps.owner, now }), isStale: (held) => ownerState(held, deps.owner).state === 'gone' });- if (!lease.ok) {- // A create that failed for any other reason than the lock being there (a workspace that cannot be written) is that error, as it always was.- if (lease.error) throw lease.error;- // `stale`: the lock's owner is gone, but the lock could not be released (another build was releasing it at the same moment, or died doing so).- const unreleased = lease.stale ? ` The build that held it is no longer running, but its lock could not be released: ${lease.reason}.` : '';- // `retry: NEVER`: the lock belongs to a build that is still running, or to one that is gone but whose lock could not be released — running the earlier phases again releases neither — and the message quotes the lock's path, which holds the maker's folder.- throw new BuildHalt(`another build is deploying pages for '${appUnique}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${lockPath} if it is stale.${unreleased}`, { phase: 'pages', code: 'pages-locked', recoverable: true, retry: RETRY.NEVER });- }- if (lease.reclaimed && typeof deps.warn === 'function') {- deps.warn(`released the pages lock for '${appUnique}': the build that held it (${describeOwner(lease.previous)}) is no longer running`);- }- return { release: () => releaseLease(lease) };-}+// The pages lock (acquireAppPagesLease) lives in lib/app-operation-lease.js, beside the build lease that every apply holds outside it; it is+// still exported from this module, where the build and its callers have always found it.function appDef(spec, result, opts = {}) {const sol = spec.solution;@@ -1605,7 +1636,9 @@ function appDef(spec, result, opts = {}) {// page entries left out of a new app's first navigation below are the ones it does not count.const kind = navigationEntryKind(s);if (kind === 'dashboard') {- const dashboardId = (result.dashboards || {})[s.dashboard];+ // Read as an OWN entry (lib/own-keys.js): a dashboard may be called `constructor` or `__proto__`, and a map a caller hands in — or the+ // `{}` of a result with no dashboards — answers those names with an inherited member, which would pass for a built dashboard's id.+ const dashboardId = ownValue(result.dashboards, s.dashboard);if (!dashboardId) throw refusal(`sitemap subarea "${s.title}" references dashboard '${s.dashboard}' which wasn't built — declare it in dashboards[] and don't skip the dashboards phase`);// The designer gives every dashboard entry it creates this launcher Url, recognizes a dashboard// entry by it, and the runtime shows the dashboard glyph only for it — without it the entry@@ -1613,7 +1646,8 @@ function appDef(spec, result, opts = {}) {return { ...withVector, type: 'DashBoard', dashboardId, dashboardUrl: DASHBOARD_LAUNCHER_URL };}if (kind === 'page') {- const genPageId = (result.pages || {})[s.page];+ // An own entry too: a page key is a lowercase slug, so `constructor` is a key a page can have.+ const genPageId = ownValue(result.pages, s.page);if (!genPageId) {// During the initial app-create (app_early) pages aren't uploaded yet — omit the subarea;// the pages phase rewrites the sitemap once the genPageIds exist. A genuinely-missing page@@ -2910,7 +2944,16 @@ function genpageCommand(verb, { env, pageId, app, flags = '' }) {// everything that app has saved, so the user is asked first), or detach it in Maker, or give this app a page of its own. `commands` are the lines `genpageCommand` made, one per app that holds the page.const detachAdvice = (commands) => `Detach it from the other app — ask the user first, since this changes another app: ${commands.join('; ')} (each takes the page out of that app's navigation and publishes that app, which publishes everything that app has saved; the page itself stays) — or detach it in Maker, or give this app its own page.`;-// Every caller enters here; the phases run in runSdkBuildPhases. This wrapper only carries what an attempt+// The entry every caller enters by. An APPLY holds the app's build lease for the whole of it (lib/app-operation-lease.js): one taken here when the+// caller holds none, or the caller's own (`opts.buildLease`, which buildModelApp hands to each attempt), borrowed and left to the caller to let go. A+// second apply of the same app in the same workspace is refused before anything is read or written, so two builds cannot both find the app's icon,+// the app or a page missing and both create it. A dry run reads only, and takes no lease.+async function runSdkBuild(spec, opts = {}) {+ if (!opts.apply) return runSdkBuildAttempt(spec, opts);+ return withAppBuildLease({ workspaceDir: applyWorkspaceOf(opts), appUniqueName: appUniqueName(spec), buildLease: opts.buildLease, warn: opts.warn }, () => runSdkBuildAttempt(spec, opts));+}++// One attempt; the phases run in runSdkBuildPhases. This wrapper only carries what an attempt// still owes out of a halt, for the caller that retries:// - the deferred publishes (default-view enrichment, reconciled views and forms): `owedPublishes`, and// `owedPaid` when this run's publish phase completed — which pays what an earlier attempt of the same@@ -2921,7 +2964,7 @@ const detachAdvice = (commands) => `Detach it from the other app — ask the use// next attempt as `opts.owedLengths` and which that attempt pays at the end of its own data-model phase, to the// table it was recorded for. What is on the halt is everything still owed: what the attempt was handed and did// not pay, and what it created.-async function runSdkBuild(spec, opts = {}) {+async function runSdkBuildAttempt(spec, opts = {}) {// tables: entity logical -> [type, id, names] of a saved view or form that owes its publish, and the names of// what is deferred onto that table: its reconciled views and forms, and its enriched default views// (oweTablePublish). lengths: table logical -> { table, column, asked, tried, tableId, columnId? } of a name column whose@@ -3005,12 +3048,20 @@ async function runSdkBuildPhases(spec, opts, owed) {// A navigation Dataverse will refuse stops the build here, before anything is written, rather than at the app step// after the solution, tables, columns, views and forms have been (app-navigation.js). Only a run that has the app step.if (has('app-shell')) await checkNavigationBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn });- // A binding whose connection reference is another connector's stops the build here too, before anything is written, for the same reason (checkPageBindingsBeforeWriting).- await checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn });+ // A binding whose connection reference is another connector's stops the build here too, before anything is written, for the same reason (checkPageBindingsBeforeWriting). What it reads is kept for+ // the attempt (bindingReads): the pages phase judges a navigation target it finds it has to make by the same reads, and reads only a name this check did not.+ const bindingReadsOfAttempt = bindingReads();+ await checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn, seen: bindingReadsOfAttempt });runner.stopIfRefused('preflight');const createdFormsThisRun = new Set();- const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, pageSourceShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };+ // The maps keyed by a name a maker writes freely — a dashboard's, a page's key, a persona's (its role's), a business process flow's — are+ // null-prototype objects (lib/own-keys.js): any such name can be `__proto__`, `constructor`, `toString`, … and must be stored and read as an+ // entry like any other. On a plain object a dashboard called `__proto__` was never stored, and a page keyed `constructor` that was not built+ // yet read the Object function as its id. JSON.stringify writes them exactly as it writes a plain object with the same entries. The other maps+ // are keyed by Dataverse logical names (a table's, a web resource's: the publisher prefix and `_`, or a system component's), by GUIDs or by+ // `entity|name` pairs, none of which can be such a member.+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: Object.create(null), pages: Object.create(null), pageDeployedShas: Object.create(null), pageSourceShas: Object.create(null), ai: { appFeatures: null, summaries: {} }, roles: Object.create(null), roleGrants: {}, bpfRoleGrants: Object.create(null), app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };// #changed-only (pages-only fast apply): seed the LIVE app id (discovered by unique name upstream) so the// pages phase's `pages-requires-app` guard passes WITHOUT running the app-shell phase in this invocation.// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell@@ -3018,7 +3069,8 @@ async function runSdkBuildPhases(spec, opts, owed) {if (opts.changedOnly && opts.changedOnly.resolvedAppId) result.created.app = opts.changedOnly.resolvedAppId;const sol = spec.solution;// The web resources an earlier run of this build wrote and could not confirm were published (lib/web-resource-records.js), read at first use: the- // spec's web resources, the generated app icon and the page manifest are written again by id when they are in it. One per run of the phases, so the+ // spec's web resources and the generated app icon are written again by id when they are in it, and the page manifest is written again by its id where+ // its published copy is not what the run wants (kept where it is: persistPageManifest). One per run of the phases, so the// build's own re-run of a halt reads what the attempt before it recorded.const unconfirmedWebResources = openUnconfirmedWebResources({ workspaceDir: opts.workspaceDir, environment: opts.env, warn: opts.warn });@@ -6575,7 +6627,7 @@ async function runSdkBuildPhases(spec, opts, owed) {// (e.g. --from pages), there is nothing to upload against — HALT and require a FULL rerun. An app the app step left to this// phase to create has no id yet, by design: it is made below, once the pages exist.if (!result.created.app && !createAppWithPages) throw new BuildHalt('pages phase requires the app (app-shell) in the same run — the app id is not carried across invocations. Re-run a FULL build (do not use --from pages).', { phase: 'pages', code: 'pages-requires-app', recoverable: false, retry: RETRY.NEVER });- const wsDir = opts.workspaceDir || path.join(path.resolve(opts.appDir || '.'), '.maker-workspace');+ const wsDir = applyWorkspaceOf(opts);// Advisory lease: acquired OUTSIDE the try so a failed acquire (pages-locked HALT) never triggers the// finally that would release a lease we never held. Correctness rests on the convergence spine, not this.// A lock a killed build left behind is released by this call, and `opts.warn` says so.@@ -6879,8 +6931,9 @@ async function runSdkBuildPhases(spec, opts, owed) {}}- // A write the SDK could not confirm leaves the manifest's row under the error's id: kept, so that this run's next persist — and the record, the next- // run's — writes it again by id rather than creating the name a second time (persistPageManifest).+ // A write the SDK could not confirm leaves the manifest's row under the error's id: kept, so that this run's next persist writes it again by that id,+ // and the record gives the next run the id to write it by where its published copy is not what that run wants (where it is, that run keeps it) —+ // never a second create of the name (persistPageManifest).const persistNow = async () => {let pr;try { pr = await persistPageManifest(provision, spec, keyToId, sol, appUnique, manifestId, lastManifestContent, solutionMembers, unconfirmedWebResources); } catch (e) {@@ -7057,6 +7110,16 @@ async function runSdkBuildPhases(spec, opts, owed) {}}}+ // The navigation targets this run MAKES (absent: `keyToId` holds no id for them) whose bindings the check before writing did not judge, because the run was told the page is deployed+ // (bindingCheckScope, `changedOnly.deployedKeys`) — one deleted in Maker since the last apply. The create sends the page's spec entry, bindings and all, so they are judged now, before the+ // first page is written, by the same verdict and with the same halt as that check (`preflight`: nothing is written yet — such a run writes nothing before its pages phase), and by what the+ // attempt has already read (bindingReadsOfAttempt): a name that check read is not read again, so a read here can neither add a request for it nor, failing, undo what that read proved. A+ // refused throttle wait stops the run here, as it does after that check. A run that was told nothing has none: every target was checked before it wrote anything.+ const madeUnchecked = pagesMadeUnchecked(spec, { changedOnly: bindingCheckScope(phases, opts.changedOnly), made: new Set(implemented.filter((p) => navTargets.has(keyOf(p)) && !keyToId.has(keyOf(p))).map(keyOf)) });+ if (madeUnchecked.length) {+ haltOnPageBindingConflicts(await judgePageBindings(provision, madeUnchecked, bindingReadsOfAttempt), opts.warn);+ runner.stopIfRefused('preflight');+ }// After the whole scan, so a build that halts on a later page says only why it halted. Nothing has been written yet, and the pages that are warned about are sent as they are.if (typeof opts.warn === 'function') for (const warning of griffelWarnings) opts.warn(warning);diff --git a/plugins/model-apps/scripts/lib/sitemap-merge.js b/plugins/model-apps/scripts/lib/sitemap-merge.jsindex e22109a53..fcc3614d4 100644--- a/plugins/model-apps/scripts/lib/sitemap-merge.js+++ b/plugins/model-apps/scripts/lib/sitemap-merge.js@@ -30,6 +30,7 @@// earlier build of this plugin gave them.const { GENPAGE_DEFAULT_VECTOR_ICON } = require('./genpage-subarea.js');+const { ownValue } = require('./own-keys.js');// The fixed launcher path the designer gives every dashboard entry it creates, and the one the// runtime keys the dashboard glyph on.@@ -448,9 +449,8 @@ function adoptLiveSitemap(desired, live, opts = {}) {return { siteMap: { ...(desired || {}), areas: out }, notes };}-// The id a plain `{ <name or key>: id }` map holds for `name` — only as the map's OWN entry, so a-// dashboard named `constructor` never resolves to Object.prototype's.-const ownId = (map, name) => (map && typeof map === 'object' && Object.prototype.hasOwnProperty.call(map, name) ? map[name] : undefined);+// A dashboard's or page's id is read from `ids` only as the map's OWN entry (ownValue, lib/own-keys.js),+// so a dashboard named `constructor` never resolves to Object.prototype's.const idMap = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});// Every subarea of an App Spec, in document order.@@ -472,8 +472,8 @@ function specSubAreas(spec) {function specSubAreaTargetKey(s, ids = {}) {if (!s || typeof s !== 'object') return undefined;if (s.entity) return subAreaTargetKey({ type: 'Entity', entity: s.entity });- if (s.dashboard) return subAreaTargetKey({ type: 'DashBoard', dashboardId: ownId(idMap(ids.dashboards), s.dashboard) });- if (s.page) return subAreaTargetKey({ type: 'GenPage', genPageId: ownId(idMap(ids.pages), s.page) });+ if (s.dashboard) return subAreaTargetKey({ type: 'DashBoard', dashboardId: ownValue(idMap(ids.dashboards), s.dashboard) });+ if (s.page) return subAreaTargetKey({ type: 'GenPage', genPageId: ownValue(idMap(ids.pages), s.page) });if (s.url) return subAreaTargetKey({ type: 'URL', url: s.url });return undefined;}diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.jsindex 9aa45c861..7ccd3bcf7 100644--- a/plugins/model-apps/scripts/lib/source-literals.js+++ b/plugins/model-apps/scripts/lib/source-literals.js@@ -4063,9 +4063,10 @@ function blankNonCodePreservingTemplateExpressions(code, opts) {* Both spellings count:* export default <expr|function|class|async function>* export { P as default } / export { default } from './x'+ * and the expression may be a generic arrow, `export default <T,>(props: P<T>) => …` (genericArrowIsComplete).*/// Identifiers may be non-ASCII (`Página`), so every name below is matched by Unicode property. White space is TypeScript's (WS, WS_SINGLE_LINE: see isTrivia), as everywhere in this file.-const DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}+default${WS}+[\p{ID_Continue}$({[*]`, 'gmu');+const DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}+default${WS}+[\p{ID_Continue}$({[*<]`, 'gmu');const NAMED_DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}*\{[^}]*\bdefault\b[^}]*\}`, 'm');const EXPORT_MODIFIER = new RegExp(String.raw`^(async|abstract)\b${WS_SINGLE_LINE}*`);const ARROW_CUT_OFF = new RegExp(String.raw`=>${WS}*$`);@@ -4096,6 +4097,8 @@ function hasDefaultExport(code) {// `at` is where the exported thing starts in `bare` (blanked code, so strings and comments are gone).function defaultExportIsComplete(bare, at) {const rest = bare.slice(at);+ // A `<` is a generic arrow's type parameters or an element, by TypeScript's rule; only a complete arrow is an export the host can mount.+ if (rest[0] === '<') return genericArrowIsComplete(rest);// `async` and `abstract` only modify what follows. Cut right after one, or inside the keyword it// modifies (`export default abstract clas`), the export is incomplete. Followed by `;` or a line// break instead, the word is a plain exported name (it is a legal identifier), handled below.@@ -4104,6 +4107,9 @@ function defaultExportIsComplete(bare, at) {const after = rest.slice(mod[0].length);if (!trimTrivia(after)) return false;if (!/^(?:function|class)\b/.test(after) && !/^(?:;|[\r\n\u2028\u2029])/.test(after)) {+ // After `async` on its line TypeScript asks the same rule of a `<` (isParenthesizedArrowFunctionExpressionWorker steps over the `async`), so an async generic+ // arrow is read as a plain one is. A head the rule reads as an element makes no arrow (TypeScript reads `async<T>(x: T)` as a call), and is judged below, as it always was.+ if (mod[1] === 'async' && after[0] === '<' && opensTypeParameters(after, 0, null, true).generic) return genericArrowIsComplete(after);// Only an async ARROW is left — `async (x) => …`, `async x => …` — and it needs its `=>` and body.return mod[1] === 'async' && /=>/.test(after) && !ARROW_CUT_OFF.test(after);}@@ -4175,6 +4181,499 @@ function defaultExportIsComplete(bare, at) {return declaresName(bare, name[1]);}+// `export default <T,>(props: Props<T>) => { … }`: a generic arrow, from its `<` (`rest` is blanked code), with or without `async` before it. In a .tsx file TypeScript reads a+// `<` where an assignment expression starts by one rule (parser.ts, isParenthesizedArrowFunctionExpressionWorker, the JSX branch,+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), which opensTypeParameters reads: type parameters when, after an optional `const`, the first name is+// followed by a `,`, an `=`, or `extends` and a token that is not `=`, `>` or `/` —+// <T,>(props: P<T>) => … <T extends object>(p: T) => … <const T,>(p: T) => … <T = string>(p: T) => …+// and an element for any other head: `<div/>`, `<></>`, and `<T>(x) => x`, which in .tsx is the element `<T>` and does not parse. An element is no component the host can+// mount, so it is refused, as it always was. What follows `export default` is an expression (parseExportAssignment), so the rule is asked as it is where an expression is known+// to start (`inExpression`): a head it reads as an element is no function type here. The type parameters must then close, a parameter list must follow them (an arrow with+// type parameters always has one), the arrow's `=>` must follow the list — at once, or right after a return type, read to its end as TypeScript reads one+// (returnTypeEnd) — and a body must follow the arrow. A write cut off anywhere before the body balances its brackets when it stops between them, so only this sees it:+// export default <T,>(props: P<T>) export default <T,>(props: P<T>): JSX.Element export default <T,>(p: T): (x: T) => T export default <T extends (a: A) => void+function genericArrowIsComplete(rest) {+ if (!opensTypeParameters(rest, 0, null, true).generic) return false;+ const typeParametersEnd = typeAnglesEnd(rest, 0);+ if (typeParametersEnd === -1) return false;+ const open = typeTokenAt(rest, typeParametersEnd);+ if (open.kind !== '(') return false;+ const parametersEnd = typeGroupEnd(rest, open.start);+ if (parametersEnd === -1) return false;+ let arrow = typeTokenAt(rest, parametersEnd);+ if (arrow.kind === ':') {+ const returnEnd = returnTypeEnd(rest, arrow.end);+ if (returnEnd === -1) return false;+ arrow = typeTokenAt(rest, returnEnd);+ }+ if (arrow.kind !== '=>' || !startsArrowBody(typeTokenAt(rest, arrow.end))) return false;+ // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.+ return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);+}++// What begins an arrow's body: a block, or what begins an expression — a name, any word but those that only begin a statement (a keyword that begins an expression, `this`,+// `new`, `typeof`, `class`, `function`, `import`, …, and a word that is a keyword elsewhere, `module`, `let`, `async`), a literal, a bracket, a prefix operator, `<` (an element+// or a generic arrow), `/` (a regex: a comment is blank) or `#` (`#x in y`). Anything else — `;`, a closing bracket, a binary operator, `.`, `...`, `=>`, `@` — is+// `Expression expected` to TypeScript, as is a statement's word after the arrow: `export default <T,>() =>` and `const x = 1;` on the next line has no body.+const EXPRESSION_KEYWORDS = new Set(['class', 'delete', 'false', 'function', 'import', 'new', 'null', 'super', 'this', 'true', 'typeof', 'void']);+const BODY_START_TOKENS = new Set(['{', '(', '[', '!', '~', '+', '-', '++', '--', '<', '/', '#', 'string', 'template', 'number']);+function startsArrowBody(token) {+ if (token.kind === 'word') return EXPRESSION_KEYWORDS.has(token.text) || !(RESERVED_WORDS.has(token.text) || token.text === 'const');+ return BODY_START_TOKENS.has(token.kind);+}++// A token, for the reading of a type and an arrow above and below: the token of `src` (blanked code, where a string or a template is its quotes around blank and a comment is+// blank) at or after `k`, as { kind, text, start, end, newline }. `kind` is 'word' — a name or a keyword; `text` is its characters, or '' for a word written with an escape,+// which is a name and no keyword here — 'string', 'template', 'number', 'eof' (a string the text does not close ends it too), or the punctuator: the longest of+// TYPE_PUNCTUATORS that stands there, as TypeScript's scanner reads one (scanner.ts, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/scanner.ts: `||` is no `|`, and+// `?.` before a digit is a `?`), or else one character — a `>` always, which the parser only joins to what follows it where an operator is expected. `newline` says a line+// terminator stands before the token: TypeScript's parser reads no type arguments, `[`, `extends`, `is` or name of an assertion on a line after what they continue.+const TYPE_PUNCTUATORS = ['===', '!==', '...', '=>', '==', '!=', '||', '&&', '??', '?.', '*=', '|=', '&=', '++', '--'];+function typeTokenAt(src, k) {+ let j = k;+ let newline = false;+ while (j < src.length && isTrivia(src[j])) {+ if (isLineTerminator(src[j])) newline = true;+ j += 1;+ }+ const token = (kind, end, text = src.slice(j, end)) => ({ kind, text, start: j, end, newline });+ if (j >= src.length) return token('eof', j, '');+ const c = src[j];+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, j + 1);+ return close === -1 ? token('eof', src.length, '') : token(c === '`' ? 'template' : 'string', close + 1);+ }+ // A number: digits, letters (hex digits, an exponent, `n`, `_`), points, and a sign right after the `e` of a decimal exponent (`1e+5`).+ if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(src[j + 1] || ''))) {+ const hex = c === '0' && /[xX]/.test(src[j + 1] || '');+ let e = j + 1;+ while (e < src.length && (/[0-9A-Za-z_.]/.test(src[e]) || (!hex && (src[e] === '+' || src[e] === '-') && /[eE]/.test(src[e - 1])))) e += 1;+ return token('number', e);+ }+ if (c === '\\' || /[\p{ID_Start}$_]/u.test(String.fromCodePoint(src.codePointAt(j)))) {+ const word = readRuleToken(src, j);+ if (word.kind === 'word') return token('word', word.end, word.escaped ? '' : word.text);+ }+ const punctuator = TYPE_PUNCTUATORS.find((p) => src.startsWith(p, j) && !(p === '?.' && /[0-9]/.test(src[j + 2] || '')));+ return punctuator ? token(punctuator, j + punctuator.length) : token(c, j + 1);+}++// The index just past the bracket that closes the `(`, `[` or `{` at `open` in `src` (blanked code), or -1 where none does or another kind closes first. Brackets of every kind+// are matched, and a string's or a template's quote, which the blanking keeps, is passed to its pair: what is between them is blank.+function typeGroupEnd(src, open) {+ const closers = [];+ for (let k = open; k < src.length; k += 1) {+ const c = src[k];+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, k + 1);+ if (close === -1) return -1;+ k = close;+ } else if (c === '(') closers.push(')');+ else if (c === '[') closers.push(']');+ else if (c === '{') closers.push('}');+ else if (c === ')' || c === ']' || c === '}') {+ if (closers.pop() !== c) return -1;+ if (closers.length === 0) return k + 1;+ }+ }+ return -1;+}++// The index just past the `>` that closes the type parameters or type arguments whose `<` is at `open` in `src` (blanked code), or -1 where none does. A group in brackets is+// passed over whole (typeGroupEnd), so no angle in it is counted, and the `>` of an `=>` closes nothing: `<T extends (a: A) => void>`, `Map<string, (x: T) => T>`.+function typeAnglesEnd(src, open) {+ let depth = 0;+ for (let k = open; k < src.length; k += 1) {+ const c = src[k];+ if (c === '"' || c === "'" || c === '`' || c === '(' || c === '[' || c === '{') {+ const end = c === '(' || c === '[' || c === '{' ? typeGroupEnd(src, k) : src.indexOf(c, k + 1) + 1;+ if (end <= 0) return -1;+ k = end - 1;+ } else if (c === ')' || c === ']' || c === '}') return -1;+ else if (c === '<') depth += 1;+ else if (c === '>' && src[k - 1] !== '=') {+ depth -= 1;+ if (depth === 0) return k + 1;+ }+ }+ return -1;+}++// The words isStartOfType takes besides a name (and which a name cannot be: a reserved word among them is a type's keyword there).+const TYPE_START_KEYWORDS = new Set([...PRIMITIVE_TYPES, 'readonly', 'unique', 'typeof', 'new', 'infer', 'import', 'asserts', 'function']);+// How deep the reading of a return type goes — a level per function type in a return type, conditional type in a branch or prefix operator — before it refuses the return type+// rather than recurse further: far deeper than any page, and far short of the stack.+const RETURN_TYPE_DEPTH = 200;++// Where a return type ends: the index just past it in `src` (blanked code) when it starts after the colon at `from`, or -1 where TypeScript's parser reports an error before it+// ends, or the text ends first. The arrow's `=>` is the first token after its return type, and a return type may hold an `=>` of its own at its own level — `(p): (x: T) => T => …`,+// `(p): new () => T => …` — so only a reading of the type tells the two apart, and a write cut right after such a type has no arrow. The type is read as TypeScript 5.8 reads it+// (parser.ts, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts: parseTypeOrTypePredicate, parseType and what they call; each function below names its+// own), one level at a time: what a group in brackets, a list in angle brackets, a string or a template holds is passed over whole, since nothing in it can end the type, and+// is not read. Where an author and a guess would part, it reads as TypeScript does:+// - any word names a type, a keyword too (parseEntityNameOfTypeReference reads an identifier NAME): `module<T>`, `namespace` and `declare` are names, and so are `if` and+// `const`, which only the checker refuses. A statement after the return type is not seen by its first word: the type ends before it, and the missing arrow refuses it;+// - a `(` begins a function type only where isUnambiguouslyStartOfFunctionType says so — `()`, `(...`, or a parameter's start (modifiers, then a name, `this` or a binding+// pattern that parses with no error) followed by `:`, `,`, `?` or `=`, or by `)` and `=>` — and a parenthesised type otherwise: `(p): (A) => T => …` holds a function+// type, `(p): (A | B) => …` a parenthesised type and then the arrow, and `(p): ({ a: T }) => p` a function type that takes the arrow's `=>` (an error);+// - type arguments, `[`, `extends`, `is` and an assertion's name continue a type only on its line; a function or constructor type after `|` or `&` is an error (TS1385, TS1388);+// - the JSDoc forms TypeScript's parser takes in a .tsx file and only its checker refuses (`?T`, `T?`, `!T`, `T!`, `*`, `function(…): T`) are read too.+function returnTypeEnd(src, from) {+ let depth = 0;+ const at = (k) => typeTokenAt(src, k);+ const isWord = (token, text) => token.kind === 'word' && token.text === text;+ // isIdentifier: a word that is no reserved word, nor `await`, which parseExportAssignment makes a keyword in an export.+ const identifier = (token) => token.kind === 'word' && (token.text === '' || !(RESERVED_WORDS.has(token.text) || token.text === 'const' || token.text === 'await'));+ // isBindingIdentifier: a word that is no reserved word.+ const bindingIdentifier = (token) => token.kind === 'word' && (token.text === '' || !(RESERVED_WORDS.has(token.text) || token.text === 'const'));+ // A reading that nests one level deeper; past RETURN_TYPE_DEPTH the type is refused.+ const nested = (read) => {+ if (depth >= RETURN_TYPE_DEPTH) return -1;+ depth += 1;+ try {+ return read();+ } finally {+ depth -= 1;+ }+ };++ // parseTypeOrTypePredicate: a name and `is` on its line make a predicate, whose type follows.+ const typeOrPredicate = (k) => {+ const name = at(k);+ if (identifier(name)) {+ const is = at(name.end);+ if (isWord(is, 'is') && !is.newline) return type(is.end, false);+ }+ return type(k, false);+ };+ // parseType: a function or constructor type, or a union and, on its line, `extends` and the rest of a conditional type — where conditional types are allowed: not in the+ // `extends` clause of one (`noConditional`).+ const type = (k, noConditional) => nested(() => {+ if (startsFunctionType(k)) return functionType(k);+ const end = unionOrIntersection(k, '|', noConditional);+ if (end === -1 || noConditional) return end;+ const ext = at(end);+ if (!isWord(ext, 'extends') || ext.newline) return end;+ const extendsEnd = type(ext.end, true);+ if (extendsEnd === -1 || at(extendsEnd).kind !== '?') return -1;+ const trueEnd = type(at(extendsEnd).end, false);+ if (trueEnd === -1 || at(trueEnd).kind !== ':') return -1;+ return type(at(trueEnd).end, false);+ });+ // isStartOfFunctionTypeOrConstructorType.+ const startsFunctionType = (k) => {+ const token = at(k);+ if (token.kind === '<' || isWord(token, 'new')) return true;+ if (isWord(token, 'abstract')) return isWord(at(token.end), 'new');+ return token.kind === '(' && unambiguousFunctionType(token.end);+ };+ // isUnambiguouslyStartOfFunctionType and skipParameterStart, after the `(`. The modifiers before a parameter's name (PARAMETER_MODIFIERS) are stepped over as parseModifiers+ // takes them (nextTokenCanFollowModifier): each where what follows can follow a modifier — on its line, but after `static` and `export` on any (and no `*`, `{` or `as`+ // after `export`).+ const unambiguousFunctionType = (k) => {+ let token = at(k);+ if (token.kind === ')' || token.kind === '...') return true;+ while (token.kind === 'word' && PARAMETER_MODIFIERS.has(token.text)) {+ const next = at(token.end);+ const follows = next.kind === 'word' || ['[', '{', '*', '...', 'string', 'number'].includes(next.kind);+ const exported = token.text !== 'export' || (next.kind !== '*' && next.kind !== '{' && !isWord(next, 'as') && !isWord(next, 'default'));+ if (!follows || !exported || (next.newline && token.text !== 'static' && token.text !== 'export')) break;+ token = next;+ }+ let end;+ if (identifier(token) || isWord(token, 'this')) end = token.end;+ else if (token.kind === '[' || token.kind === '{') end = bindingPatternEnd(token.start);+ else return false;+ if (end === -1) return false;+ const after = at(end);+ if (after.kind === ':' || after.kind === ',' || after.kind === '?' || after.kind === '=') return true;+ return after.kind === ')' && at(after.end).kind === '=>';+ };+ // parseObjectBindingPattern and parseArrayBindingPattern, whose `{` or `[` is at `open`: the index just past the pattern, or -1 where it does not parse with no error. A+ // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd) — a known limit: the comma between a generic call's type arguments,+ // `{ a = f<T, U>() }`, is taken for the end of the value, the pattern reads as none, and a write cut right after a function type with such a parameter is accepted+ // (AGENTS.md, "TSX source lexer — known limits"; the page compile refuses it).+ const bindingPatternEnd = (open) => nested(() => {+ const object = src[open] === '{';+ const closer = object ? '}' : ']';+ let k = open + 1;+ for (;;) {+ let token = at(k);+ if (token.kind === closer) return token.end;+ if (!object && token.kind === ',') {+ k = token.end;+ continue;+ }+ if (token.kind === '...') token = at(token.end);+ let end;+ if (object) {+ // A property name — a word, a string, a number or a computed `[…]` that holds an expression — then `:` and the element; or a binding name alone.+ if (token.kind === 'word' || token.kind === 'string' || token.kind === 'number') end = token.end;+ else if (token.kind === '[' && computedKeyIsExpression(token.start)) end = typeGroupEnd(src, token.start);+ else return -1;+ if (end === -1) return -1;+ const colon = at(end);+ if (colon.kind === ':') end = bindingElementEnd(colon.end);+ else if (!bindingIdentifier(token)) return -1;+ } else {+ end = bindingElementEnd(token.start);+ }+ if (end === -1) return -1;+ let next = at(end);+ if (next.kind === '=') {+ end = defaultValueEnd(next.end, closer);+ if (end === -1) return -1;+ next = at(end);+ }+ if (next.kind === closer) return next.end;+ if (next.kind !== ',') return -1;+ k = next.end;+ }+ });+ const bindingElementEnd = (k) => {+ const token = at(k);+ if (token.kind === '[' || token.kind === '{') return bindingPatternEnd(token.start);+ return bindingIdentifier(token) ? token.end : -1;+ };+ // Whether the `[` at `open` holds an expression, as a binding pattern's computed key must (parseComputedPropertyName: parseExpression, `in` allowed). The same brackets hold+ // an index signature's key, `[key: string]`, and a mapped type's, `[K in keyof T]`, `[K in keyof T as …]`, in an object type — and neither is an expression: a `:` that no `?`+ // opened, or a word right after an operand (`keyof` is a name in an expression, and `T` follows it), ends the reading. So `({ [key: string]: T }) => …` holds a+ // parenthesised type and the arrow, where `({ [key]: v }) => …` and `({ [K in T]: v }) => …` (`K in T` is an expression) hold a function type's parameters. The+ // expression is read only as far as that needs — operands, prefix and binary operators, `?` and `:`, member access, calls, indexes, `!`, type arguments where they close and+ // what follows can follow them (canFollowTypeArgumentsInExpression), and a type after `as` or `satisfies` — and what it does not know (an arrow, `function`, a regex, JSX)+ // is taken for no expression: a type then, never a function type's parameters, so the reading can let a page TypeScript refuses through but never refuse one it parses.+ const computedKeyIsExpression = (open) => {+ const close = typeGroupEnd(src, open);+ if (close === -1) return false;+ const groupEnd = (token) => {+ const end = typeGroupEnd(src, token.start);+ return end !== -1 && end < close ? end : -1;+ };+ let k = open + 1;+ let operand = false;+ let questions = 0;+ for (;;) {+ const token = at(k);+ if (token.start >= close - 1) return token.start === close - 1 && operand && questions === 0;+ const word = token.kind === 'word' ? token.text : null;+ if (!operand) {+ // A prefix operator, then an operand: a name or a keyword that is a value, a literal, or a group (a parenthesised expression, an array, an object).+ if (['!', '~', '+', '-', '++', '--'].includes(token.kind) || ['typeof', 'void', 'delete', 'await', 'new'].includes(word)) k = token.end;+ else if (word !== null && (!(RESERVED_WORDS.has(word) || word === 'const') || ['this', 'null', 'true', 'false', 'super'].includes(word))) { operand = true; k = token.end; }+ else if (token.kind === 'number' || token.kind === 'string' || token.kind === 'template') { operand = true; k = token.end; }+ else if (token.kind === '(' || token.kind === '[' || token.kind === '{') { k = groupEnd(token); operand = true; if (k === -1) return false; }+ else return false;+ } else if (token.kind === '.' || token.kind === '?.') {+ // A member, or after `?.` a call or an index (read next).+ const name = at(token.end);+ if (name.kind === 'word') k = name.end;+ else if (token.kind === '?.' && (name.kind === '(' || name.kind === '[')) k = token.end;+ else return false;+ } else if (token.kind === '(' || token.kind === '[') {+ // A call, or an index — which holds an argument: `T[]` is no expression.+ k = groupEnd(token);+ if (k === -1 || (token.kind === '[' && at(token.end).start === k - 1)) return false;+ } else if (token.kind === '!' || token.kind === '++' || token.kind === '--' || token.kind === 'template') {+ k = token.end;+ } else if (token.kind === '<') {+ // Type arguments where they close and what follows can follow them — `(`, a template, the end, or a binary operator; a comparison otherwise.+ const end = typeAnglesEnd(src, token.start);+ const next = end === -1 || end >= close ? null : at(end);+ if (next !== null && (next.start === close - 1 || ['(', 'template', ',', '?', ':', '==', '===', '!=', '!==', '&&', '||', '??', '|', '&', '^', '*', '/', '%'].includes(next.kind) || ['in', 'instanceof', 'as', 'satisfies'].includes(next.kind === 'word' ? next.text : null))) k = end;+ else {+ operand = false;+ k = token.end;+ }+ } else if ((word === 'as' || word === 'satisfies') && !token.newline) {+ const end = type(token.end, false);+ if (end === -1 || end >= close) return false;+ k = end;+ } else if (token.kind === '?' || token.kind === ':' || word === 'in' || word === 'instanceof'+ || ['+', '-', '*', '/', '%', '<', '>', '&', '|', '^', '=', ',', '==', '===', '!=', '!==', '&&', '||', '??', '*=', '|=', '&='].includes(token.kind)) {+ if (token.kind === '?') questions += 1;+ if (token.kind === ':' && --questions < 0) return false;+ operand = false;+ k = token.end;+ } else {+ // An operand right after an operand (`keyof T`), or what this reading does not know.+ return false;+ }+ }+ };+ const defaultValueEnd = (k, closer) => {+ for (let j = k; j < src.length; j += 1) {+ const c = src[j];+ if (c === ',' || c === closer) return j;+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, j + 1);+ if (close === -1) return -1;+ j = close;+ } else if (c === '(' || c === '[' || c === '{') {+ const end = typeGroupEnd(src, j);+ if (end === -1) return -1;+ j = end - 1;+ } else if (c === ')' || c === ']' || c === '}') return -1;+ }+ return -1;+ };+ // parseFunctionOrConstructorType: [`abstract`] [`new`] [type parameters] parameters `=>` and a return type.+ const functionType = (k) => {+ let token = at(k);+ if (isWord(token, 'abstract')) token = at(token.end);+ if (isWord(token, 'new')) token = at(token.end);+ if (token.kind === '<') {+ const end = typeAnglesEnd(src, token.start);+ if (end === -1) return -1;+ token = at(end);+ }+ if (token.kind !== '(') return -1;+ const parametersEnd = typeGroupEnd(src, token.start);+ if (parametersEnd === -1 || at(parametersEnd).kind !== '=>') return -1;+ return typeOrPredicate(at(parametersEnd).end);+ };+ // parseUnionOrIntersectionType: an optional leading operator, then constituents with the operator between them; a function or constructor type where a constituent+ // follows an operator is an error (parseFunctionOrConstructorTypeToError). A union's constituents are intersections, an intersection's prefix-operator types.+ const unionOrIntersection = (k, operator, noConditional) => {+ const constituent = (j) => (startsFunctionType(j) ? -1 : operator === '|' ? unionOrIntersection(j, '&', noConditional) : typeOperator(j, noConditional));+ const lead = at(k);+ let end = lead.kind === operator ? constituent(lead.end) : operator === '|' ? unionOrIntersection(k, '&', noConditional) : typeOperator(k, noConditional);+ while (end !== -1 && at(end).kind === operator) end = constituent(at(end).end);+ return end;+ };+ // parseTypeOperatorOrHigher: `keyof`, `unique` and `readonly` take the type after them; `infer` a name and maybe a constraint, which it keeps unless a `?` follows it where+ // conditional types are allowed (tryParseConstraintOfInferType: the `extends` then begins a conditional type); anything else is a postfix type.+ const typeOperator = (k, noConditional) => nested(() => {+ const token = at(k);+ if (isWord(token, 'keyof') || isWord(token, 'unique') || isWord(token, 'readonly')) return typeOperator(token.end, noConditional);+ if (!isWord(token, 'infer')) return postfix(k);+ const name = at(token.end);+ if (!identifier(name)) return -1;+ const ext = at(name.end);+ if (!isWord(ext, 'extends')) return name.end;+ const constraint = type(ext.end, true);+ return constraint !== -1 && (noConditional || at(constraint).kind !== '?') ? constraint : name.end;+ });+ // parsePostfixTypeOrHigher: on the type's line, `[…]` (an array or an indexed access) and the JSDoc `!` and `?` — a `?` before what can start a type is a conditional's,+ // and ends the type.+ const postfix = (k) => {+ let end = nonArray(k);+ while (end !== -1) {+ const token = at(end);+ if (token.newline) return end;+ if (token.kind === '!') end = token.end;+ else if (token.kind === '?' && !startsType(token.end, 0)) end = token.end;+ else if (token.kind === '[') end = typeGroupEnd(src, token.start);+ else return end;+ }+ return -1;+ };+ // isStartOfType, for the token at `k` (`nesting` bounds the look into parentheses).+ const startsType = (k, nesting) => {+ const token = at(k);+ if (token.kind === 'word') return TYPE_START_KEYWORDS.has(token.text) || identifier(token);+ if (['{', '[', '<', '|', '&', '*', '?', '!', '...', 'string', 'number', 'template'].includes(token.kind)) return true;+ if (token.kind === '-') return at(token.end).kind === 'number';+ if (token.kind !== '(' || nesting > 4) return false;+ // isStartOfParenthesizedOrFunctionType: `)`, a parameter's start or a type's after the `(`.+ const next = at(token.end);+ return next.kind === ')' || next.kind === '...' || next.kind === '[' || next.kind === '{' || next.kind === '#' || next.kind === '@' || bindingIdentifier(next)+ || startsType(token.end, nesting + 1);+ };+ // parseNonArrayType.+ const nonArray = (k) => nested(() => {+ const token = at(k);+ switch (token.kind) {+ case 'word': return wordType(token, k);+ case 'string': case 'template': case 'number': case '*': return token.end;+ case '{': case '[': case '(': return typeGroupEnd(src, token.start);+ // reScanAsteriskEqualsToken and reScanQuestionToken: `*=` is a `*` and then `=`, `??` two `?`.+ case '*=': return token.start + 1;+ case '??': return jsdocNullable(token.start + 1);+ case '?': return jsdocNullable(token.end);+ case '!': return nonArray(token.end);+ case '-': {+ const number = at(token.end);+ return number.kind === 'number' ? number.end : -1;+ }+ default: return -1;+ }+ });+ // parseJSDocUnknownOrNullableType, after its `?`: a `?` alone before `,`, `}`, `)`, `>`, `=` or `|`, and a prefix to a type otherwise.+ const jsdocNullable = (k) => ([',', '}', ')', '>', '=', '|'].includes(at(k).kind) ? k : type(k, false));+ const wordType = (token, k) => {+ const word = token.text;+ if (word === 'this') {+ // parseThisTypePredicate: `this is` on one line.+ const is = at(token.end);+ return isWord(is, 'is') && !is.newline ? type(is.end, false) : token.end;+ }+ if (word === 'void' || word === 'true' || word === 'false' || word === 'null') return token.end;+ // A keyword type (`string`, `number`, …) is a type of its own unless a `.` follows, which makes it the first name of a dotted one (parseKeywordAndNoDot).+ if (PRIMITIVE_TYPES.has(word)) return at(token.end).kind === '.' ? typeReference(k) : token.end;+ if (word === 'typeof') return isWord(at(token.end), 'import') ? importType(token.end) : typeQuery(token.end);+ if (word === 'import') return importType(k);+ if (word === 'function') {+ // parseJSDocFunctionType: `function(…)` and maybe `: type`; `function` alone is a name.+ const open = at(token.end);+ if (open.kind !== '(') return token.end;+ const end = typeGroupEnd(src, open.start);+ return end !== -1 && at(end).kind === ':' ? typeOrPredicate(at(end).end) : end;+ }+ if (word === 'asserts') {+ // parseAssertsTypePredicate, where a word follows on the line: `asserts this` or `asserts name`, then maybe `is` and a type (on any line).+ const name = at(token.end);+ if (name.kind === 'word' && !name.newline) {+ if (!isWord(name, 'this') && !identifier(name)) return -1;+ const is = at(name.end);+ return isWord(is, 'is') ? type(is.end, false) : name.end;+ }+ }+ return typeReference(k);+ };+ // parseTypeReference: a name — any word, dotted (parseEntityName) — and type arguments on its line.+ const typeReference = (k) => {+ const end = entityName(k);+ return end === -1 ? -1 : typeArgumentsOnLine(end, true);+ };+ const entityName = (k) => {+ const first = at(k);+ if (first.kind !== 'word') return -1;+ let end = first.end;+ for (;;) {+ const dot = at(end);+ if (dot.kind !== '.') return end;+ const name = at(dot.end);+ // `A.<T>`: the dot ends the name (a JSDoc-style list of type arguments, which the checker refuses).+ if (name.kind === '<') return dot.end;+ // parseRightSideOfDot: a word on the next line with another word after it on that line begins a declaration, and the name is missing.+ if (name.kind !== 'word' || (name.newline && at(name.end).kind === 'word' && !at(name.end).newline)) return -1;+ end = name.end;+ }+ };+ // Type arguments where they may stand: on the line of what they follow (parseTypeArgumentsOfTypeReference). Those of `typeof x<T>` are tried, and dropped where they do not+ // close (tryParseTypeArguments): `required` is false there.+ const typeArgumentsOnLine = (end, required) => {+ const open = at(end);+ if (open.kind !== '<' || open.newline) return end;+ const close = typeAnglesEnd(src, open.start);+ return close !== -1 ? close : required ? -1 : end;+ };+ // parseTypeQuery, after `typeof`: a name, then type arguments on its line.+ const typeQuery = (k) => {+ const end = entityName(k);+ return end === -1 ? -1 : typeArgumentsOnLine(end, false);+ };+ // parseImportType, from its `import`: `import(…)`, then maybe `.` and a name, then type arguments on the line.+ const importType = (k) => {+ const open = at(at(k).end);+ let end = open.kind === '(' ? typeGroupEnd(src, open.start) : -1;+ if (end !== -1 && at(end).kind === '.') end = entityName(at(end).end);+ return end === -1 ? -1 : typeArgumentsOnLine(end, true);+ };++ return typeOrPredicate(from);+}+// True when `name` is a local object binding. This is narrower than declaresName on purpose:// `export default pages.Home` is complete when `pages` is an object literal, but `React.memo` at EOF// is usually a truncated call on an imported namespace and remains rejected.diff --git a/plugins/model-apps/scripts/lib/table-schema-metadata.js b/plugins/model-apps/scripts/lib/table-schema-metadata.jsindex 3e6c99628..e10dbef05 100644--- a/plugins/model-apps/scripts/lib/table-schema-metadata.js+++ b/plugins/model-apps/scripts/lib/table-schema-metadata.js@@ -77,15 +77,38 @@ function alternateKeysFromMetadata(keys, labelOf, omitted = []) {return out.sort((a, b) => compareText(a.schemaName, b.schemaName));}-function alternateKeyMatches(keys, key) {- const names = (values) => Array.isArray(values) && values.every((v) => typeof v === 'string' && v)+// The columns of a key as one set that compares: their logical names in lower case, sorted — or null when one is not a name, an answer the+// build cannot read. The platform answers a key's columns in an order of its own, so the order never counts.+function keyColumnSet(values) {+ return Array.isArray(values) && values.every((v) => typeof v === 'string' && v)? values.map((v) => v.toLowerCase()).sort(compareText) : null;- const wanted = names(key.columns);+}+const sameKeyColumns = (found, wanted) => !!found && found.length === wanted.length && found.every((v, i) => v === wanted[i]);++function alternateKeyMatches(keys, key) {+ const wanted = keyColumnSet(key.columns);return !!wanted && wanted.length > 0 && Array.isArray(keys) && keys.some((candidate) => {if (!candidate || String(candidate.SchemaName).toLowerCase() !== String(key.schemaName).toLowerCase()) return false;- const found = names(candidate.KeyAttributes);- return found && found.length === wanted.length && found.every((v, i) => v === wanted[i]);+ return sameKeyColumns(keyColumnSet(candidate.KeyAttributes), wanted);});}-module.exports = { readStatusOptions, statusReasonsFromOptions, alternateKeysFromMetadata, alternateKeyMatches };+// The key of `keys` — the `Keys` a read of the table answers, `[{ SchemaName, KeyAttributes }]` — that is over exactly the columns `key`+// declares, whatever its name, or null. The platform allows one key per set of columns, so there is at most one; it is the key the platform+// means when it refuses the create of `key` because a key with the selected attributes already exists (lib/entity-provision.js,+// KEY_OVER_SAME_COLUMNS).+function alternateKeyOverColumns(keys, key) {+ const wanted = keyColumnSet(key.columns);+ if (!wanted || !wanted.length || !Array.isArray(keys)) return null;+ return keys.find((candidate) => !!candidate && typeof candidate.SchemaName === 'string' && candidate.SchemaName !== ''+ && sameKeyColumns(keyColumnSet(candidate.KeyAttributes), wanted)) || null;+}++// Whether two lists of key columns are the same set (keyColumnSet): the comparison the build makes of a key the environment holds with one the+// spec declares, here for two lists of names — two keys of one spec, say.+function sameKeyColumnSet(a, b) {+ const wanted = keyColumnSet(b);+ return !!wanted && wanted.length > 0 && sameKeyColumns(keyColumnSet(a), wanted);+}++module.exports = { readStatusOptions, statusReasonsFromOptions, alternateKeysFromMetadata, alternateKeyMatches, alternateKeyOverColumns, sameKeyColumnSet };diff --git a/plugins/model-apps/scripts/lib/web-resource-records.js b/plugins/model-apps/scripts/lib/web-resource-records.jsindex 9d8a201fd..b4eeb339c 100644--- a/plugins/model-apps/scripts/lib/web-resource-records.js+++ b/plugins/model-apps/scripts/lib/web-resource-records.js@@ -1,12 +1,14 @@'use strict';-// The web resources a build WROTE and could not confirm were published, kept in the build's workspace so that the next run writes them again.+// The web resources a build WROTE and could not confirm were published, kept in the build's workspace so that the next run can recover or confirm them.//// The bundled SDK writes a web resource, publishes it, and reads its PUBLISHED content back (a plain GET by id); when the publish fails or the// read-back cannot confirm what was written, it throws WEB_RESOURCE_UNVERIFIED — after the row exists, with the row's id (`error.id`). What the// build does with the error is in lib/sdk-build.js (writeOwnedWebResource, persistPageManifest). What it needs from a run that FOLLOWS — the// build's own re-run of a transient halt, and a new invocation — is to know that the row of that name is one this plugin wrote and could not// confirm, so that it writes the content again by id (`updateWebResource(id, { content })`, which publishes and verifies again) instead of-// reusing it untouched as it reuses any web resource that exists. The server holds nothing that says so: a same-named row can be another+// reusing it untouched as it reuses any web resource that exists. (The page manifest is compared with its published copy on every run, and kept+// where that copy already holds what the run would write; for it the record supplies the id of a manifest no plain read finds, and keeps its+// name from being created again.) The server holds nothing that says so: a same-named row can be another// maker's; its name alone grants no right to overwrite it. So the build keeps the id of its own write rather than inferring ownership from content or a name.//// Under the customization lock, a later accepted publish was observed publishing the OLD content after earlier lock-refused publishes,diff --git a/plugins/model-apps/scripts/lib/workspace-binding.js b/plugins/model-apps/scripts/lib/workspace-binding.jsindex 4925ccb8c..5f273ca5c 100644--- a/plugins/model-apps/scripts/lib/workspace-binding.js+++ b/plugins/model-apps/scripts/lib/workspace-binding.js@@ -56,6 +56,8 @@ const WORKSPACE_ORG_MISMATCH = 'WORKSPACE_ORG_MISMATCH';const WORKSPACE_NOT_INITIALIZED = 'WORKSPACE_NOT_INITIALIZED';// The plugin's own: the halt for a manifest the SDK could not read at all (below). The SDK has no code for it.const WORKSPACE_MANIFEST_INVALID = 'WORKSPACE_MANIFEST_INVALID';+// The name of the build lock an apply holds in its workspace (lib/app-operation-lease.js): the hash of the app's name, 64 hex digits.+const BUILD_LOCK = /^app-build\.[0-9a-f]{64}\.lock$/;function isWorkspaceOrgMismatch(err) {return !!err && typeof err === 'object' && err.code === WORKSPACE_ORG_MISMATCH;@@ -149,6 +151,9 @@ function listsNoArtifact(file) {// see the header). Conservative on purpose: "nothing" is only answered when every entry was seen and is one of those,// so a file of any other name (a baseline, a receipt, a journal, an operator's note), a link, a manifest that lists an// artifact, a tree deeper or larger than that scaffold, and anything that could not be read all count as something.+// One file is not: the build lock an apply holds while it runs (`app-build.<sha256>.lock`, lib/app-operation-lease.js).+// The apply that meets this folder took it before it opened the folder, so the folder always holds it here; it records+// which process is building, never anything that was built, and is gone when that build ends.// Read-only.function holdsNothing(folder) {const MAX_DEPTH = 4; // `.metadata/<type>` is two deep; the rest is margin@@ -173,6 +178,7 @@ function holdsNothing(folder) {let manifest = false;for (const entry of entries) {seen += 1;+ if (entry.isFile() && BUILD_LOCK.test(entry.name)) continue;if (entry.isFile() && entry.name === WORKSPACE_MANIFEST) {if (!listsNoArtifact(path.join(folder, entry.name))) return false;manifest = true;diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.jsindex 7cd42fc2d..a9d621a4a 100644--- a/plugins/model-apps/scripts/list-custom-apis.js+++ b/plugins/model-apps/scripts/list-custom-apis.js@@ -85,7 +85,13 @@ function buildCustomApiFilter(entities) {// mapParameterKind). Because the rows arrive nested under their parent API there is no parent id to// group on — unlike the flat cross-API query this replaced.function parameterKindsFromRows(rows) {- const kinds = {};+ // A null-prototype map, as a defence (lib/own-keys.js): a lookup of a name the API does not have reads as absent, never as a member of+ // Object.prototype (`constructor`, `toString`). It changes nothing a listing holds. A parameter's unique name carries no publisher prefix,+ // and Dataverse requires it to begin with a letter (measured live: HTTP 400 `0x800608ab` for one that does not), so no parameter is called+ // `__proto__` — the one name a plain object would have left out — while `constructor`, `toString` or `hasOwnProperty` were own entries of a+ // plain object too. JSON.stringify writes the map as it writes a plain object with the same entries.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/custom-api-tables#customapirequestparameter-table-columns+ const kinds = Object.create(null);for (const row of rows || []) {const name = row.uniquename;const kind = mapParameterKind(row.type);@@ -100,7 +106,9 @@ function parameterKindsFromRows(rows) {// names outside parameterKinds so a required lookup does not disappear when its kind is omitted.// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameterfunction lookupParametersFromRows(rows) {- const lookups = {};+ // Null-prototype, as parameterKindsFromRows's map is, and as a defence too: no parameter is called `__proto__`, whose object a plain object+ // would have taken for its prototype.+ const lookups = Object.create(null);for (const row of rows || []) {if (Number(row.type) !== 5 || !row.uniquename) continue;const lookup = { isOptional: row.isoptional === true };diff --git a/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js b/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.jsindex 84da85580..85bb43596 100644--- a/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js@@ -13,8 +13,8 @@// written for these tests, to be words the English rule cannot read. The codes are the ones lib/entity-provision.js documents// (ALREADY_EXISTS_CODES). What must not move: a code of ANOTHER create, a generic code, and a code that the words only quote do not by// themselves make an answer an already-exists one — given words the English rule cannot read, such an answer stops the build (the 409-// and English-word rules are unchanged and still apply whatever code an answer carries); and the reads that decide a table and a-// relationship are made as before.+// and English-word rules are unchanged and still apply whatever code an answer carries, save a key create's 0x80060894, whose words are+// never read: see its own section below); and the reads that decide a table and a relationship are made as before.//// Two codes are broader than the create they are listed for, and are pinned on both sides of the read that decides: the table create's// 0x80044363 (a schema name that is not unique — what an existing table's create was answered, live, but a name another kind of@@ -159,6 +159,187 @@ test('an alternate key refused in another language with a code that does not say}});+// --- an alternate key refused because ANOTHER key of the table is over its columns (0x80060894) ------------------------------------+// The platform allows one key per set of columns, and answers the create of a second one with EntityKeyWithSelectedAttributesExists, in the+// reference's words:+// HTTP 400 {"error":{"code":"0x80060894","message":"An entity key with the selected attributes already exists on entity."}}+// That does not say the DECLARED key exists: the key over those columns can be another one. Its English words read as an already-exists answer+// all the same, so an English build skipped the key — never created, and its verification then found it missing — while the same answer in+// Spanish stopped the build with the platform's words. The code decides now, in every language: the build reads the table's keys again (the+// read that finds the table) and skips the key only where the key over those columns is the declared one; a key of another name stops the+// build naming it, the columns and what to do; and a read that fails, or shows no key over exactly those columns, stops it with the+// platform's own error. The Spanish text is written for these tests; the English one is the reference's.+const { isTransientHalt } = require('../build-model-app.js');+const { retryPolicyFor, RETRY } = require('../lib/retry-policy.js');++const KEYS_PROBE = `${PROBE}&$expand=Keys($select=SchemaName,KeyAttributes)`;+const TABLE_LIST = '/EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity';+const tableWithKeys = (keys) => ok({ LogicalName: 'contoso_project', EntitySetName: 'contoso_projects', ...(keys ? { Keys: keys } : {}) });+const COLUMNS_TAKEN = {+ English: 'An entity key with the selected attributes already exists on entity.',+ Spanish: 'Ya existe una clave de entidad con los atributos seleccionados en la entidad.',+};+// A key a maker made in Power Apps over the column the spec's key is over, under a name of its own.+const MAKERS_KEY = { SchemaName: 'contoso_ProjectCode', KeyAttributes: ['contoso_code'] };+// The route of a build whose key create gets `keyAnswer`. `reads` answers the read that finds the table and each read of it after that, in+// turn (the last one answers any further read); an Error is a request that got no answer.+const keyAnsweredWith = (keyAnswer, reads) => {+ let n = 0;+ return (method, asked) => {+ if (method === 'GET' && asked === KEYS_PROBE) {+ n += 1;+ const read = reads[Math.min(n, reads.length) - 1];+ if (read instanceof Error) throw read;+ return read;+ }+ if (method === 'GET' && asked === TABLE_LIST) return ok({ value: [{ LogicalName: 'contoso_project', SchemaName: 'contoso_Project', EntitySetName: 'contoso_projects', IsCustomEntity: true }] });+ if (method === 'GET' && asked === COLUMN_LIST) return PROJECT_COLUMNS;+ if (method === 'POST' && asked === KEYS) return keyAnswer;+ return undefined;+ };+};+const AFTER_FOUND = [`GET ${KEYS_PROBE}`, `GET ${COLUMN_LIST}`, `POST ${KEYS}`];++test('an alternate key refused because another key of the table is over its columns (0x80060894) stops the build naming that key, the columns and what to do — in English as in Spanish, never skipped on the words', async () => {+ const runs = {};+ for (const [language, words] of Object.entries(COLUMNS_TAKEN)) {+ const run = await build(KEYED, keyAnsweredWith(refused('0x80060894', words), [tableWithKeys([MAKERS_KEY])]));+ assert.deepStrictEqual(run.unmodelled, [], language);+ assert.ok(run.error instanceof BuildHalt, `${language}: the build stops — ${run.error && run.error.message}`);+ assert.strictEqual(run.error.phase, 'data-model', language);+ assert.strictEqual(run.steps[run.steps.length - 1], 'error alt key contoso_Project.contoso_CodeKey', `${language}: at the key — ${run.steps.join(' | ')}`);+ const message = run.error.message;+ assert.match(message, /^data-model failed: alt key contoso_Project\.contoso_CodeKey was not created: /, `${language}: the declared key`);+ assert.match(message, /the key contoso_ProjectCode over the same column \(contoso_code\)/, `${language}: the key the table has, as the platform names it, and its column`);+ assert.match(message, /Dataverse allows one key per set of columns/, `${language}: why`);+ assert.match(message, /set this key's schemaName to 'contoso_ProjectCode'/, `${language}: what to do to keep that key`);+ assert.match(message, /if contoso_ProjectCode is a leftover that nothing uses, delete it in Power Apps/, `${language}: and what to do if it is a leftover`);+ assert.ok(!message.includes(words), `${language}: the build's own words, not the platform's`);+ assert.strictEqual(retryPolicyFor(run.error), RETRY.NEVER, `${language}: a run again meets the same key`);+ assert.strictEqual(isTransientHalt(run.error), false, `${language}: so the build does not run again`);+ assert.deepStrictEqual(run.requests, [...AFTER_FOUND, `GET ${KEYS_PROBE}`], `${language}: the table's keys are read once more after the refusal, and nothing else is sent`);+ runs[language] = run;+ }+ assert.deepStrictEqual(outcomeOf(runs.Spanish), outcomeOf(runs.English), 'the same steps, warnings, requests and result in either language');+ assert.strictEqual(runs.Spanish.error.message, runs.English.error.message, 'and the same stop');+});++test('a key of several columns refused with 0x80060894 names the other key whatever the order and the case of its columns', async () => {+ const pair = { solution: SOLUTION, relationships: [], entities: [project({+ columns: [{ schemaName: 'contoso_Code', type: 'Text' }],+ alternateKeys: [{ schemaName: 'contoso_PairKey', displayName: 'Clave doble', columns: ['contoso_Name', 'contoso_Code'] }],+ })] };+ const other = { SchemaName: 'contoso_CodeAndName', KeyAttributes: ['contoso_code', 'contoso_name'] };+ const run = await build(pair, keyAnsweredWith(refused('0x80060894', COLUMNS_TAKEN.Spanish), [tableWithKeys([other])]));+ assert.ok(run.error instanceof BuildHalt, run.error && run.error.message);+ assert.match(run.error.message, /alt key contoso_Project\.contoso_PairKey was not created: the table contoso_project already has the key contoso_CodeAndName over the same columns \(contoso_name, contoso_code\)/);+});++test('an alternate key refused with 0x80060894 is skipped as an existing key is when the table\'s keys show the DECLARED key over those columns, under its name in any case — in English as in Spanish', async () => {+ // The read that finds the table fails, so the key could not be proven before it was asked for (as above); the read after the refusal shows it.+ const declared = { SchemaName: 'CONTOSO_CODEKEY', KeyAttributes: ['CONTOSO_CODE'] };+ const reads = [answer(500, GENERIC, 'An unexpected error occurred.'), tableWithKeys([MAKERS_KEY, declared])];+ const english = await build(KEYED, keyAnsweredWith(refused('0x80060894', COLUMNS_TAKEN.English), reads));+ assert.deepStrictEqual(english.unmodelled, []);+ assert.strictEqual(english.error, undefined, english.error && english.error.message);+ assert.strictEqual(english.steps[english.steps.length - 1], 'skip alt key contoso_Project.contoso_CodeKey (exists)', english.steps.join(' | '));+ assert.deepStrictEqual(english.requests, [`GET ${KEYS_PROBE}`, `GET ${TABLE_LIST}`, `GET ${COLUMN_LIST}`, `POST ${KEYS}`, `GET ${KEYS_PROBE}`], 'the keys are read once more after the refusal');+ const spanish = await build(KEYED, keyAnsweredWith(refused('0x80060894', COLUMNS_TAKEN.Spanish), reads));+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');+});++test('an alternate key refused with 0x80060894 whose table\'s keys cannot be read, or show no key over exactly those columns, stops the build with the platform\'s own error — in English as in Spanish', async () => {+ for (const [what, read] of [+ ['a read answered 500', answer(500, GENERIC, 'An unexpected error occurred.')],+ ['a read that got no answer', new Error('socket hang up')],+ ['a read whose answer carries no keys', tableWithKeys(undefined)],+ ['a read that shows a key over another column', tableWithKeys([{ SchemaName: 'contoso_NameKey', KeyAttributes: ['contoso_name'] }])],+ ['a read that shows a key over those columns and one more', tableWithKeys([{ SchemaName: 'contoso_Pair', KeyAttributes: ['contoso_code', 'contoso_name'] }])],+ ['a read that shows a key whose columns cannot be read', tableWithKeys([{ SchemaName: 'contoso_Odd', KeyAttributes: null }])],+ ]) {+ for (const [language, words] of Object.entries(COLUMNS_TAKEN)) {+ const run = await build(KEYED, keyAnsweredWith(refused('0x80060894', words), [tableWithKeys([]), read]));+ assertStopsAt(run, 'alt key contoso_Project.contoso_CodeKey', words, `${what}, ${language}`);+ assert.deepStrictEqual(run.requests, [...AFTER_FOUND, `GET ${KEYS_PROBE}`], `${what}, ${language}: read once, and not guessed at`);+ assert.strictEqual(retryPolicyFor(run.error), RETRY.NEVER, `${what}, ${language}: the platform's refusal is final, as it always was`);+ }+ }+});++test('a spec that declares two keys over the same columns stops at the second, saying the spec declares both', async () => {+ const twice = { solution: SOLUTION, relationships: [], entities: [project({+ columns: [{ schemaName: 'contoso_Code', type: 'Text' }],+ alternateKeys: [+ { schemaName: 'contoso_CodeKey', displayName: 'Clave de codigo', columns: ['contoso_code'] },+ { schemaName: 'contoso_CodeKey2', displayName: 'Otra clave de codigo', columns: ['contoso_Code'] },+ ],+ })] };+ const first = { SchemaName: 'contoso_CodeKey', KeyAttributes: ['contoso_code'] };+ for (const [language, words] of Object.entries(COLUMNS_TAKEN)) {+ const run = await build(twice, keyAnsweredWith(refused('0x80060894', words), [tableWithKeys([first])]));+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);+ assert.deepStrictEqual(run.steps.slice(-2), ['skip alt key contoso_Project.contoso_CodeKey (exists)', 'error alt key contoso_Project.contoso_CodeKey2'], language);+ assert.match(run.error.message, /alt key contoso_Project\.contoso_CodeKey2 was not created: the table contoso_project already has the key contoso_CodeKey over the same column \(contoso_code\), and the spec declares both/, language);+ assert.match(run.error.message, /Keep one of them in the table's alternateKeys/, `${language}: what to do`);+ assert.doesNotMatch(run.error.message, /Power Apps/, `${language}: nothing to delete in the environment: the spec asks for both`);+ }+});++// The spec declares two keys over different columns — which is valid — but the environment's key of the first name is over the second key's+// column: it drifted from the spec (the spec changed that key's columns, or the key was made otherwise). The first create is refused because its+// name exists (0x80060893) and skipped, as it always was; the second is refused because that key is over its column. The spec does not declare two+// keys over one set of columns, so the stop must not say it does, nor ask to drop or change a declaration: it names the key in the environment, the+// columns it is over and the columns the spec declares for it, which is what has to be reconciled before the second key can be made.+test('a key refused with 0x80060894 because the environment\'s key of another DECLARED name is over its columns — that key drifted from the spec — stops naming that key\'s columns and the declared ones, not a duplicate in the spec', async () => {+ const drifted = { solution: SOLUTION, relationships: [], entities: [project({+ columns: [{ schemaName: 'contoso_Code', type: 'Text' }],+ alternateKeys: [+ { schemaName: 'contoso_CodeKey', displayName: 'Clave de codigo', columns: ['contoso_code'] },+ { schemaName: 'contoso_NameKey', displayName: 'Clave de nombre', columns: ['contoso_name'] },+ ],+ })] };+ const environments = { SchemaName: 'contoso_CodeKey', KeyAttributes: ['contoso_name'] };+ const NAME_TAKEN = {+ English: KEY_IN_ENGLISH,+ Spanish: refused('0x80060893', 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.'),+ };+ for (const [language, words] of Object.entries(COLUMNS_TAKEN)) {+ const reads = keyAnsweredWith(undefined, [tableWithKeys([environments])]);+ const route = (method, asked, body) => {+ if (method === 'POST' && asked === KEYS) return body.SchemaName === 'contoso_CodeKey' ? NAME_TAKEN[language] : refused('0x80060894', words);+ return reads(method, asked, body);+ };+ const run = await build(drifted, route);+ assert.deepStrictEqual(run.unmodelled, [], language);+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);+ assert.deepStrictEqual(run.steps.slice(-2), ['skip alt key contoso_Project.contoso_CodeKey (exists)', 'error alt key contoso_Project.contoso_NameKey'], `${language}: the key whose name exists is skipped, as before`);+ const message = run.error.message;+ assert.match(message, /alt key contoso_Project\.contoso_NameKey was not created: the table contoso_project already has the key contoso_CodeKey over the same column \(contoso_name\)/, `${language}: the key in the environment and the columns it is over`);+ assert.match(message, /The spec declares contoso_CodeKey over other columns \(contoso_code\)/, `${language}: and the columns the spec declares for it`);+ assert.match(message, /a build does not change the columns of a key that exists/, `${language}: why the build cannot make the second key`);+ assert.match(message, /Reconcile contoso_CodeKey first: if nothing relies on it as it is .*, delete it in Power Apps \(the table's Keys\) and run the build again/, `${language}: what to do, and with what care`);+ assert.doesNotMatch(message, /the spec declares both|Keep one of them|give the other different columns|set this key's schemaName/, `${language}: no advice to drop or change a declaration that is valid`);+ assert.strictEqual(retryPolicyFor(run.error), RETRY.NEVER, `${language}: a run again meets the same key`);+ assert.deepStrictEqual(run.requests, [`GET ${KEYS_PROBE}`, `GET ${COLUMN_LIST}`, `POST ${KEYS}`, `POST ${KEYS}`, `GET ${KEYS_PROBE}`], `${language}: one read, after the refusal that needs it`);+ }+});++test('a key refused with 0x80060893, with a 409, or in English words that carry no code, is skipped without reading the table again, as before', async () => {+ for (const [what, keyAnswer] of [+ ['0x80060893 in English', KEY_IN_ENGLISH],+ ['0x80060893 in Spanish', refused('0x80060893', 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.')],+ ['a 409', { status: 409, body: { error: { message: 'Conflict.' } } }],+ ['English words with no code', { status: 400, body: { error: { message: 'An entity key with the name contoso_codekey already exists on entity contoso_project.' } } }],+ ]) {+ const run = await build(KEYED, keyAnsweredWith(keyAnswer, [tableWithKeys([])]));+ assert.deepStrictEqual(run.unmodelled, [], what);+ assert.strictEqual(run.error, undefined, `${what}: ${run.error && run.error.message}`);+ assert.strictEqual(run.steps[run.steps.length - 1], 'skip alt key contoso_Project.contoso_CodeKey (exists)', what);+ assert.deepStrictEqual(run.requests, AFTER_FOUND, `${what}: nothing is read after the refusal`);+ }+});+// --- a status reason whose value is already taken ---------------------------------------------------------------------------------// The build pins each status reason's value, so a second insert of it is refused because an option already holds that value. A table// that exists has its reasons read first, and only a reason the read does not show is inserted; when the read fails, every reason is@@ -180,7 +361,8 @@ test('a status reason refused in Spanish because its value is taken (0x80044310)assert.deepStrictEqual(english.unmodelled, []);assert.strictEqual(english.error, undefined, english.error && english.error.message);assert.ok(english.steps.includes('skip status reason contoso_Project: En revision (exists)'), english.steps.join(' | '));- assert.deepStrictEqual(english.result.statusReasonValues, { contoso_project: { 'En revision': { value: 100000000, stateCode: 0 } } }, 'the pinned value is kept for the sample data');+ // `statusReasonValues` holds each table's reasons in a null-prototype map (lib/own-keys.js: a label can be `__proto__`); its JSON is compared.+ assert.deepStrictEqual(JSON.parse(JSON.stringify(english.result.statusReasonValues)), { contoso_project: { 'En revision': { value: 100000000, stateCode: 0 } } }, 'the pinned value is kept for the sample data');const spanish = await build(STATUSED, statusRefusedWith(refused('0x80044310', 'El valor de estado 100000000 no es valido para el conjunto de opciones 00000000-0000-0000-0000-000000000001 porque ya existe otra opcion con ese valor')));assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');diff --git a/plugins/model-apps/scripts/tests/app-build-lease.test.js b/plugins/model-apps/scripts/tests/app-build-lease.test.jsnew file mode 100644index 000000000..5c57d9af1--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-build-lease.test.js@@ -0,0 +1,386 @@+'use strict';+// The build lease (lib/app-operation-lease.js): one apply of an app holds it, in its workspace, for the whole of its work, and a second apply of the+// same app in the same workspace is refused before it reads or writes anything.+//+// What this holds, through the entries a maker's command and a program reach — runSdkBuild, buildModelApp, runChangedOnlyApply — and never through a+// stand-in for them:+// - a second apply is refused (`build-locked`) while the first runs anywhere: in its phases, in the wait before its automatic re-run, in its+// verify, in the close of its journal; the refused one calls nothing of the caller's (no SDK, no snapshot read, no content read, no WhoAmI);+// - an apply nested in another borrows the lease it is handed and lets go of nothing; a lease that is not a live one for that app and workspace+// — a string, one already let go, another app's or another folder's — is refused (`build-lease-invalid`), and no apply runs without a lease;+// - a dry run takes no lease and makes no folder;+// - a lock left by a build that is gone is taken over and said; one held by a build that runs is never taken, however old;+// - a release leaves another build's token alone, and says so when it cannot confirm it removed its own, without changing the result.+// The command line's order (the lease before the auth check, the result printed after the release) is in build-lease-cli.test.js.+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { runSdkBuild, appUniqueName } = require('../lib/sdk-build.js');+const { buildModelApp, isTransientHalt } = require('../build-model-app.js');+const flow = require('../lib/changed-only-flow.js');+const store = require('../lib/apply-snapshot-store.js');+const { sha256 } = require('../lib/hash.js');+const { ownerStamp } = require('../lib/process-owner.js');+const { ConnectionError } = require('../lib/maker-sdk.js');+const { deadPid } = require('./helpers/kill-target-client.js');++// A valid spec, and not the point: one table the phases these tests run never reach.+const spec = (name = 'Lease Probe') => ({+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name },+ entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+});+const APP = appUniqueName(spec());+// The lock's name, worked out here rather than read from the module: what a build of this release creates is pinned by the test.+const buildLock = (dir, app = APP) => path.join(dir, `app-build.${sha256(String(app).toLowerCase())}.lock`);+const REFUSAL = (dir, app = APP) => `another build may be applying '${app}' in this workspace — refusing a second concurrent apply (would risk duplicate creation). Re-run the same command after it finishes. If no build using this workspace is running, inspect ${buildLock(dir, app)} and remove it only if it is abandoned; keep the workspace and its recovery records.`;+const isBuildLocked = (dir, app = APP) => (e) => {+ assert.strictEqual(e && e.code, 'build-locked', String(e && e.stack));+ assert.strictEqual(e.name, 'BuildHalt');+ assert.strictEqual(e.phase, 'preflight');+ assert.strictEqual(e.recoverable, true);+ assert.strictEqual(e.retry, 'never');+ assert.strictEqual(e.transient, false);+ assert.strictEqual(e.message, REFUSAL(dir, app));+ return true;+};+const isLeaseInvalid = (e) => {+ assert.strictEqual(e && e.code, 'build-lease-invalid', String(e && e.stack));+ assert.strictEqual(e.phase, 'preflight');+ assert.strictEqual(e.recoverable, false);+ assert.strictEqual(e.retry, 'never');+ assert.strictEqual(e.transient, false);+ assert.strictEqual(e.message, 'the supplied build lease is not active for this app and workspace — refusing to apply without its own lease');+ return true;+};++function gate() {+ let open;+ const opened = new Promise((resolve) => { open = resolve; });+ return { opened, open };+}++// The engine's one phase that reads first: the solution step asks whether the solution exists. `hold` runs inside that read, while the build holds+// its lease — the place a test starts a second build from.+const solutionDouble = (hold = async () => {}) => {+ const reads = [];+ const sdk = { queryRecords: async (entity) => { reads.push(entity); await hold(); return [{ solutionid: '11111111-1111-4111-8111-111111111111' }]; } };+ return { sdk, reads };+};+const engineBuild = (s, dir, extra = {}) => runSdkBuild(s, { sdk: extra.sdk, provisionSdk: extra.sdk, apply: true, workspaceDir: dir, phases: ['solution'], ...extra });++test('a second apply of the same app in the same workspace is refused before it reads anything, while the first is in its phases — and the first, when it ends, lets go', async () => {+ const dir = makeTempDir('build-lease-');+ const held = gate();+ const inside = gate();+ const first = solutionDouble(async () => { inside.open(); await held.opened; });+ const running = engineBuild(spec(), dir, { sdk: first.sdk });+ await inside.opened;+ // Every applying entry, each on its own: the engine, the build with its retry loop, and the changed-only flow.+ const second = solutionDouble();+ await assert.rejects(engineBuild(spec(), dir, { sdk: second.sdk }), isBuildLocked(dir), 'runSdkBuild');+ const calls = [];+ await assert.rejects(buildModelApp(spec(), { apply: true, workspaceDir: dir }, { runBuild: async () => { calls.push('runBuild'); return { ok: true }; } }), isBuildLocked(dir), 'buildModelApp');+ await assert.rejects(flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true }, deps: {+ readContent: () => { calls.push('readContent'); return null; },+ resolveLiveIdentity: async () => { calls.push('resolveLiveIdentity'); return null; },+ buildModelApp: async () => { calls.push('buildModelApp'); return { ok: true }; },+ } }), isBuildLocked(dir), 'runChangedOnlyApply');+ assert.deepStrictEqual(second.reads, [], 'the refused engine read nothing');+ assert.deepStrictEqual(calls, [], 'the refused build ran nothing of its caller\'s');+ // Another app in the same workspace is another lease.+ const other = solutionDouble();+ assert.strictEqual((await engineBuild(spec('Other Probe'), dir, { sdk: other.sdk })).ok, true);+ held.open();+ assert.strictEqual((await running).ok, true);+ assert.ok(!fs.existsSync(buildLock(dir)), 'the first build let go when it ended');+ // And the next apply proceeds.+ assert.strictEqual((await engineBuild(spec(), dir, { sdk: solutionDouble().sdk })).ok, true);+ assert.deepStrictEqual(fs.readdirSync(dir).filter((n) => /\.lock$/.test(n)), [], 'no lock left');+});++test('two spellings of one app share the lease: an app\'s unique name is compared without regard to case', async () => {+ const dir = makeTempDir('build-lease-case-');+ const held = gate();+ const inside = gate();+ const upper = { ...spec(), app: { name: 'Lease Probe', uniqueName: 'Contoso_LeaseProbe' } };+ const lower = { ...spec(), app: { name: 'Lease Probe', uniqueName: 'contoso_leaseprobe' } };+ const running = engineBuild(upper, dir, { sdk: solutionDouble(async () => { inside.open(); await held.opened; }).sdk });+ await inside.opened;+ await assert.rejects(engineBuild(lower, dir, { sdk: solutionDouble().sdk }), (e) => e.code === 'build-locked' && e.message.includes(buildLock(dir, 'Contoso_LeaseProbe')));+ held.open();+ await running;+});++test('an apply nested in another borrows the lease it is handed and lets go of nothing; a second, independent one in the same process is refused', async () => {+ const dir = makeTempDir('build-lease-nested-');+ let during = null;+ let independent = null;+ const r = await buildModelApp(spec(), { apply: true, workspaceDir: dir }, {+ // Each attempt of the build borrows the build's lease: the real engine, handed what buildModelApp hands every attempt.+ runBuild: async (s, o) => {+ assert.ok(o.buildLease, 'the build hands its lease to the attempt');+ const nested = await runSdkBuild(s, { ...o, phases: ['solution'], sdk: solutionDouble().sdk });+ assert.strictEqual(nested.ok, true, 'a nested engine run borrows the lease');+ during = fs.readFileSync(buildLock(dir), 'utf8');+ // A process is not a lease: a second apply that was not handed this one competes like another process does.+ independent = await runSdkBuild(s, { ...o, buildLease: undefined, phases: ['solution'], sdk: solutionDouble().sdk }).catch((e) => e);+ return { ok: true, dryRun: false, created: {} };+ },+ });+ assert.strictEqual(r.ok, true);+ assert.ok(JSON.parse(during).pid === process.pid, 'the lease was held, by this process, while the nested run borrowed it');+ assert.ok(isBuildLocked(dir)(independent));+ assert.ok(!fs.existsSync(buildLock(dir)), 'one lease, let go once, by the build that took it');+});++test('a lease that is not a live one for that app and that workspace is refused — a string, a lease already let go, another app\'s, another folder\'s — and no apply runs without one', async () => {+ const dir = makeTempDir('build-lease-invalid-');+ const elsewhere = makeTempDir('build-lease-invalid-');+ let kept = null;+ const runs = [];+ await buildModelApp(spec(), { apply: true, workspaceDir: dir }, {+ runBuild: async (s, o) => {+ kept = o.buildLease;+ // A live lease handed to an apply of another app, or of the same app in another folder.+ for (const [what, otherSpec, folder] of [['another app', spec('Other Probe'), dir], ['another folder', spec(), elsewhere]]) {+ const sdk = solutionDouble();+ await assert.rejects(engineBuild(otherSpec, folder, { sdk: sdk.sdk, buildLease: o.buildLease }), isLeaseInvalid, what);+ runs.push(...sdk.reads);+ }+ return { ok: true, dryRun: false, created: {} };+ },+ });+ for (const [what, lease] of [['a string', 'held'], ['true', true], ['an object that is no lease', {}], ['a lease already let go', kept]]) {+ const sdk = solutionDouble();+ await assert.rejects(engineBuild(spec(), dir, { sdk: sdk.sdk, buildLease: lease }), isLeaseInvalid, what);+ await assert.rejects(buildModelApp(spec(), { apply: true, workspaceDir: dir, buildLease: lease }, { runBuild: async () => { runs.push('runBuild'); return { ok: true }; } }), isLeaseInvalid, `${what}: buildModelApp`);+ await assert.rejects(flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true, buildLease: lease }, deps: { readContent: () => runs.push('readContent'), resolveLiveIdentity: async () => runs.push('resolveLiveIdentity') } }), isLeaseInvalid, `${what}: runChangedOnlyApply`);+ runs.push(...sdk.reads);+ }+ assert.deepStrictEqual(runs, [], 'nothing ran under a lease that was refused');+ assert.ok(!fs.existsSync(buildLock(dir)), 'and a refused borrower took no lease of its own');+});++test('a dry run takes no lease and makes no folder', async () => {+ const root = makeTempDir('build-lease-dry-');+ const dir = path.join(root, 'never-made');+ const r = await runSdkBuild(spec(), { apply: false, workspaceDir: dir, livePlan: false, phases: ['solution'] });+ assert.strictEqual(r.dryRun, true);+ const b = await buildModelApp(spec(), { apply: false, workspaceDir: dir, livePlan: false }, { runBuild: async () => ({ ok: true, dryRun: true, planItems: [] }) });+ assert.strictEqual(b.ok, true);+ assert.ok(!fs.existsSync(dir), 'no workspace was made for a lease');+ // And a dry run beside a running apply is not refused.+ const held = gate();+ const inside = gate();+ const running = engineBuild(spec(), root, { sdk: solutionDouble(async () => { inside.open(); await held.opened; }).sdk });+ await inside.opened;+ assert.strictEqual((await runSdkBuild(spec(), { apply: false, workspaceDir: root, livePlan: false, phases: ['solution'] })).dryRun, true);+ held.open();+ await running;+});++test('the lease spans the build\'s automatic re-run and its wait, its verify and the close of its journal: a second apply is refused in each, and the build keeps one lease throughout', async () => {+ const dir = makeTempDir('build-lease-span-');+ const tokens = new Set();+ const refused = [];+ const tryAnother = async (where) => {+ tokens.add(fs.readFileSync(buildLock(dir), 'utf8'));+ const e = await buildModelApp(spec(), { apply: true, workspaceDir: dir }, { runBuild: async () => ({ ok: true }) }).then(() => null, (err) => err);+ refused.push([where, e && e.code]);+ };+ let attempts = 0;+ const journal = { record: () => {}, close: () => { refused.push(['journal (sync)', fs.existsSync(buildLock(dir)) ? 'held' : 'free']); } };+ const r = await buildModelApp(spec(), { apply: true, workspaceDir: dir, verify: true, retryDelayMs: 0 }, {+ journal,+ // A 503 on the first attempt: the build waits and runs again.+ runBuild: async () => { attempts += 1; if (attempts === 1) throw new ConnectionError('https://contoso.crm.dynamics.com/api/data/v9.2/solutions', 503, 'Service Unavailable'); return { ok: true, dryRun: false, created: {} }; },+ sleep: async () => tryAnother('the wait before the re-run'),+ verify: async () => { await tryAnother('the verify'); return { ok: true, checks: [], missing: [] }; },+ });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(attempts, 2, 'the build ran again after the 503');+ assert.deepStrictEqual(refused, [['the wait before the re-run', 'build-locked'], ['the verify', 'build-locked'], ['journal (sync)', 'held']]);+ assert.strictEqual(tokens.size, 1, 'one lease, the same token, from the first attempt to the end');+ assert.ok(!fs.existsSync(buildLock(dir)));+});++test('a halt the build cannot run again still settles under the lease, and is thrown after the lease is let go', async () => {+ const dir = makeTempDir('build-lease-halt-');+ const halt = Object.assign(new Error('bad request'), { statusCode: 400, transient: false });+ let heldAtClose = null;+ const journal = { record: () => {}, close: () => { heldAtClose = fs.existsSync(buildLock(dir)); } };+ await assert.rejects(buildModelApp(spec(), { apply: true, workspaceDir: dir, retryDelayMs: 0 }, { journal, runBuild: async () => { throw halt; } }), (e) => e === halt);+ assert.strictEqual(heldAtClose, true, 'the journal closed while the lease was held');+ assert.ok(!fs.existsSync(buildLock(dir)), 'and the halt reached the caller after the lease was let go');+});++test('a changed-only run and a data-stage apply of the same app exclude each other, before either reads the snapshot — and a finished stage lets the next command in', async (t) => {+ const dir = makeTempDir('build-lease-stage-');+ const reads = { snapshot: 0, distrust: 0 };+ const realRead = store.readSnapshot;+ const realDistrust = store.readDistrust;+ t.mock.method(store, 'readSnapshot', (...a) => { reads.snapshot += 1; return realRead(...a); });+ t.mock.method(store, 'readDistrust', (...a) => { reads.distrust += 1; return realDistrust(...a); });+ const counted = { readContent: 0, resolveLiveIdentity: 0, buildModelApp: 0 };+ const loserDeps = {+ readContent: () => { counted.readContent += 1; return null; },+ resolveLiveIdentity: async () => { counted.resolveLiveIdentity += 1; return null; },+ buildModelApp: async () => { counted.buildModelApp += 1; return { ok: true }; },+ };+ // The data stage holds the lease: the changed-only run is refused before its first read.+ const held = gate();+ const inside = gate();+ const stage = buildModelApp(spec(), { apply: true, workspaceDir: dir, phases: ['solution', 'data-model', 'sample-data'] }, {+ runBuild: async () => { inside.open(); await held.opened; return { ok: true, dryRun: false, created: {} }; },+ });+ await inside.opened;+ const before = { ...reads };+ await assert.rejects(flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true }, deps: loserDeps }), isBuildLocked(dir));+ assert.deepStrictEqual(reads, before, 'no snapshot or distrust read');+ assert.deepStrictEqual(counted, { readContent: 0, resolveLiveIdentity: 0, buildModelApp: 0 }, 'no content read, no WhoAmI, no build');+ held.open();+ assert.strictEqual((await stage).ok, true);+ // The changed-only run holds it: the data stage is refused before it reads its approval record or runs.+ const heldFlow = gate();+ const insideFlow = gate();+ const changed = flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true }, deps: {+ readContent: () => null,+ resolveLiveIdentity: async () => { insideFlow.open(); await heldFlow.opened; return null; },+ buildModelApp: async () => ({ ok: true, dryRun: false, created: {} }),+ log: () => {},+ } });+ await insideFlow.opened;+ let ran = 0;+ await assert.rejects(buildModelApp(spec(), { apply: true, workspaceDir: dir, phases: ['solution', 'data-model', 'sample-data'] }, { runBuild: async () => { ran += 1; return { ok: true }; } }), isBuildLocked(dir));+ assert.strictEqual(ran, 0);+ heldFlow.open();+ await changed;+ // Once it has finished, the next stage runs.+ assert.strictEqual((await buildModelApp(spec(), { apply: true, workspaceDir: dir, phases: ['solution', 'data-model', 'sample-data'] }, { runBuild: async () => ({ ok: true, dryRun: false, created: {} }) })).ok, true);+ assert.ok(!fs.existsSync(buildLock(dir)));+});++test('a build lock whose owner is proven gone is taken over and said; one whose owner runs, or cannot be judged, is never taken — however old — and is refused in the same words, untouched', async () => {+ const gone = deadPid();+ const stamp = (overrides) => JSON.stringify({ ...ownerStamp({ pid: gone }), ...overrides, rnd: 'held' });+ for (const [what, content] of [+ ['this process, which is running, by a record ten minutes old', JSON.stringify({ ...ownerStamp({ now: () => Date.now() - 10 * 60 * 1000 }), rnd: 'held' })],+ ['a record from another machine', stamp({ host: 'some-other-machine' })],+ ['a lock of a release that recorded only { pid, at }', JSON.stringify({ pid: gone, at: Date.now() - 10 * 60 * 1000 })],+ ['an empty file', ''],+ ['text that is not JSON', 'not json'],+ ]) {+ const dir = makeTempDir('build-lease-owner-');+ fs.writeFileSync(buildLock(dir), content);+ const warnings = [];+ const sdk = solutionDouble();+ await assert.rejects(engineBuild(spec(), dir, { sdk: sdk.sdk, warn: (m) => warnings.push(m) }), isBuildLocked(dir), what);+ assert.strictEqual(fs.readFileSync(buildLock(dir), 'utf8'), content, `${what}: untouched`);+ assert.deepStrictEqual(warnings, [], what);+ assert.deepStrictEqual(sdk.reads, [], `${what}: nothing read`);+ }+ const dir = makeTempDir('build-lease-owner-');+ fs.writeFileSync(buildLock(dir), stamp({}));+ const warnings = [];+ assert.strictEqual((await engineBuild(spec(), dir, { sdk: solutionDouble().sdk, warn: (m) => warnings.push(m) })).ok, true);+ assert.strictEqual(warnings.length, 1, JSON.stringify(warnings));+ assert.ok(warnings[0].startsWith(`released the build lock for '${APP}': the build that held it (pid ${gone} on `) && warnings[0].endsWith(') is no longer running'), warnings[0]);+ assert.ok(!fs.existsSync(buildLock(dir)));+ // A take-over that another build is making at the same moment: refused, with the reason added.+ const racing = makeTempDir('build-lease-owner-');+ fs.writeFileSync(buildLock(racing), stamp({}));+ fs.writeFileSync(`${buildLock(racing)}.reclaim`, JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'taking-over' }));+ await assert.rejects(engineBuild(spec(), racing, { sdk: solutionDouble().sdk }), (e) => e.code === 'build-locked' && e.message === `${REFUSAL(racing)} The build that held it is no longer running, but its lock could not be released: lease being reclaimed by another writer.`);+});++test('a refused apply\'s halt is never run again by the build, whatever its folder or app is called', async () => {+ const root = makeTempDir('build-lease-policy-');+ const dir = path.join(root, 'SQL Timeout 503 try again later');+ const held = gate();+ const inside = gate();+ const running = engineBuild(spec(), dir, { sdk: solutionDouble(async () => { inside.open(); await held.opened; }).sdk });+ await inside.opened;+ const halt = await engineBuild(spec(), dir, { sdk: solutionDouble().sdk }).catch((e) => e);+ held.open();+ await running;+ assert.ok(isBuildLocked(dir)(halt));+ assert.ok(halt.message.includes('SQL Timeout 503 try again later'), 'control: the refusal quotes the folder');+ assert.strictEqual(isTransientHalt(halt, { spec: spec() }), false);+});++test('a late release leaves a lock another build holds now as it is, without a word; a removal it cannot confirm is said, and the result stands', async () => {+ const dir = makeTempDir('build-lease-release-');+ const warnings = [];+ const theirs = JSON.stringify({ ...ownerStamp(), pid: process.pid + 1, rnd: 'theirs' });+ const r = await engineBuild(spec(), dir, { sdk: solutionDouble(async () => { fs.writeFileSync(buildLock(dir), theirs); }).sdk, warn: (m) => warnings.push(m) });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(fs.readFileSync(buildLock(dir), 'utf8'), theirs, 'the other build\'s lock stays');+ assert.deepStrictEqual(warnings, []);+ fs.rmSync(buildLock(dir));++ const stuck = makeTempDir('build-lease-release-');+ const said = [];+ const rmSync = fs.rmSync;+ fs.rmSync = (target, ...rest) => {+ if (path.resolve(String(target)) === path.resolve(buildLock(stuck))) throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });+ return rmSync.call(fs, target, ...rest);+ };+ let result;+ try {+ result = await engineBuild(spec(), stuck, { sdk: solutionDouble().sdk, warn: (m) => said.push(m) });+ } finally {+ fs.rmSync = rmSync;+ }+ assert.strictEqual(result.ok, true, 'the build\'s result is what it was');+ assert.deepStrictEqual(said, [`could not confirm removal of the build lock for '${APP}': ${buildLock(stuck)}. This run has finished; keep the workspace and its recovery records. If a later run still stops here, confirm no build is running before removing only this lock.`]);+ fs.rmSync(buildLock(stuck));+});++test('a warning callback that throws never leaves the lease behind: one that throws while a take-over is said lets the lock go, and is what the build throws; one that throws while the lock is let go changes nothing the build answers', async () => {+ const logger = () => { throw new Error('logger unavailable'); };+ // The take-over of a lock whose build is gone, said to a callback that throws.+ const dir = makeTempDir('build-lease-warn-');+ fs.writeFileSync(buildLock(dir), JSON.stringify({ ...ownerStamp({ pid: deadPid() }), rnd: 'held' }));+ const first = solutionDouble();+ await assert.rejects(engineBuild(spec(), dir, { sdk: first.sdk, warn: logger }), /^Error: logger unavailable$/);+ assert.deepStrictEqual(first.reads, [], 'the build did not run');+ assert.ok(!fs.existsSync(buildLock(dir)), 'and the lock it took over was let go — not left stamped with this process, which runs');+ assert.strictEqual((await engineBuild(spec(), dir, { sdk: solutionDouble().sdk })).ok, true, 'the next apply proceeds');+ // A release it cannot confirm, said to a callback that throws: the build's own result — or its own error — is what it answers.+ for (const [what, sdk, outcome] of [+ ['a build that succeeded', solutionDouble().sdk, (settled) => settled.value && settled.value.ok === true],+ ['a build that failed', { queryRecords: async () => { throw new Error('the solution read failed'); } }, (settled) => settled.error && /the solution read failed/.test(settled.error.message)],+ ]) {+ const stuck = makeTempDir('build-lease-warn-');+ const rmSync = fs.rmSync;+ fs.rmSync = (target, ...rest) => {+ if (path.resolve(String(target)) === path.resolve(buildLock(stuck))) throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });+ return rmSync.call(fs, target, ...rest);+ };+ let settled;+ try {+ settled = await engineBuild(spec(), stuck, { sdk, warn: logger }).then((value) => ({ value }), (error) => ({ error }));+ } finally {+ fs.rmSync = rmSync;+ }+ assert.ok(outcome(settled), `${what}: ${settled.error ? settled.error.stack : JSON.stringify(settled.value)}`);+ fs.rmSync(buildLock(stuck));+ }+});++test('a link or a folder at the lock\'s name is the file system problem it is, not another build applying — and nothing runs', async () => {+ const dir = makeTempDir('build-lease-planted-');+ fs.mkdirSync(buildLock(dir));+ const sdk = solutionDouble();+ await assert.rejects(engineBuild(spec(), dir, { sdk: sdk.sdk }), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-file');+ assert.deepStrictEqual(sdk.reads, []);+ // A file where the workspace should be.+ const file = path.join(makeTempDir('build-lease-planted-'), 'not-a-folder');+ fs.writeFileSync(file, '');+ await assert.rejects(engineBuild(spec(), file, { sdk: sdk.sdk }), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-directory');+});diff --git a/plugins/model-apps/scripts/tests/app-membership-build.test.js b/plugins/model-apps/scripts/tests/app-membership-build.test.jsindex 07acc1a13..b6210f124 100644--- a/plugins/model-apps/scripts/tests/app-membership-build.test.js+++ b/plugins/model-apps/scripts/tests/app-membership-build.test.js@@ -5,7 +5,10 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { runSdkBuild, appDef } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, appDef } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { membershipSpec, membershipSdk, FORM_A, FORM_B, DASHBOARD, META, APP } = require('./helpers/app-membership-sdk.js');const { fakeGenpage } = require('./helpers/fake-genpage.js');diff --git a/plugins/model-apps/scripts/tests/app-navigation-build.test.js b/plugins/model-apps/scripts/tests/app-navigation-build.test.jsindex b4a982bdf..92bfc0f06 100644--- a/plugins/model-apps/scripts/tests/app-navigation-build.test.js+++ b/plugins/model-apps/scripts/tests/app-navigation-build.test.js@@ -25,9 +25,13 @@ const assert = require('node:assert');const crypto = require('node:crypto');const fs = require('node:fs');-const { runSdkBuild, existingAppSitemapIsWritten, pagesFirstRule, planFor, PHASES, BuildHalt } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, existingAppSitemapIsWritten, pagesFirstRule, planFor, PHASES, BuildHalt } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { STAGES } = require('../lib/stages.js');-const { buildModelApp, isTransientHalt, discoverOpDiffState } = require('../build-model-app.js');+const { buildModelApp: buildModelAppInPlace, isTransientHalt, discoverOpDiffState } = require('../build-model-app.js');+const buildModelApp = inOwnFolder(buildModelAppInPlace);const { SHAPES, specFor } = require('./helpers/navigation-shapes.js');const { writesIn, environment, pagesEnvironment, pageBackend, appFolder } = require('./helpers/navigation-fakes.js');diff --git a/plugins/model-apps/scripts/tests/app-pages-lease.test.js b/plugins/model-apps/scripts/tests/app-pages-lease.test.jsnew file mode 100644index 000000000..f6e253764--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-pages-lease.test.js@@ -0,0 +1,263 @@+'use strict';+// The pages lock as two files (lib/app-operation-lease.js acquireAppPagesLease, still exported from lib/sdk-build.js): a hashed one keyed without+// regard to case, then the one every earlier release takes, spelled as the app is spelled.+//+// What this holds:+// - two spellings of one app (`Contoso_App`, `contoso_app`) share one page-publish record, and now one pages lock too — on a case-sensitive file+// system, where they used to take two (run over a folder that behaves as a case-sensitive one on every machine, and over the real folder where+// the file system is case-sensitive itself);+// - a build of an earlier release, which takes only the legacy file, and a build of this one keep each other out of the pages phase, in both orders,+// when they spell the app the same way — and the refusal is the sentence it has always been;+// - when the second file refuses, the first is let go again: nothing this build took is left, and nothing of another build's is touched;+// - each file is taken over only from a build proven gone, and said once per build;+// - a release leaves another build's token alone, and says so when it cannot confirm it removed its own.+// The lock's own tests (owner records, real kills, racing processes) are in pages-lock-dead-owner.test.js.+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { acquireAppPagesLease } = require('../lib/sdk-build.js');+const { sha256 } = require('../lib/hash.js');+const { publishedRecordPath } = require('../lib/page-publish-records.js');+const { ownerStamp } = require('../lib/process-owner.js');+const { isTransientHalt } = require('../build-model-app.js');+const { caseSensitiveFolder, foldsCase } = require('./helpers/case-sensitive-fs.js');+const { acquireLegacyPagesLease } = require('./helpers/legacy-pages-lease.js');+const { deadPid } = require('./helpers/kill-target-client.js');++const ENV = 'https://contoso.crm.dynamics.com';+// The hashed name, worked out here rather than read from the module, so that what a build of this release creates is pinned by the test.+const canonicalName = (app) => `app-pages.${sha256(String(app).toLowerCase())}.lock`;+const legacyName = (app) => `pages-${String(app).replace(/[^A-Za-z0-9_-]/g, '_')}.lock`;+// The refusal's words, as they have always been: a person and the skills read them.+const REFUSAL = (lock, app) => `another build is deploying pages for '${app}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${lock} if it is stale.`;+const refusedAt = (lock, app) => (e) => {+ assert.strictEqual(e && e.code, 'pages-locked', String(e && e.stack));+ assert.strictEqual(e.message, REFUSAL(lock, app));+ return true;+};+const names = (dir) => fs.readdirSync(dir).sort();++// The two ways a folder can tell `Contoso_App` from `contoso_app`: modelled on every machine, and the real thing where the file system is case-sensitive.+function caseSensitiveFolders() {+ const folders = [['a folder that behaves as a case-sensitive one', (dir) => caseSensitiveFolder(dir)]];+ const probe = makeTempDir('pages-case-probe-');+ if (!foldsCase(probe)) folders.push(['this machine\'s own case-sensitive folder', () => ({ restore() {} })]);+ return folders;+}++test('two spellings of one app share one pages lease on a case-sensitive file system, as they share one page-publish record — in either order', () => {+ for (const [what, open] of caseSensitiveFolders()) {+ const dir = makeTempDir('pages-case-');+ const folder = open(dir);+ try {+ // The record the pages phase writes is the same file for both spellings: the reason they must not deploy pages at the same time.+ assert.strictEqual(publishedRecordPath(dir, 'Contoso_App', ENV), publishedRecordPath(dir, 'contoso_app', ENV), `${what}: one publish record`);+ for (const [first, second] of [['Contoso_App', 'contoso_app'], ['contoso_app', 'Contoso_App']]) {+ const held = acquireAppPagesLease(dir, first);+ // Control: the folder tells the two legacy names apart, so the legacy file alone would not keep the second spelling out.+ assert.ok(names(dir).includes(legacyName(first)) && !names(dir).includes(legacyName(second)), `${what}: ${first} took its own spelling of the legacy lock, which is not ${second}'s`);+ assert.throws(() => acquireAppPagesLease(dir, second), refusedAt(path.join(dir, canonicalName(second)), second), `${what}: ${second} is refused while ${first} holds the lease`);+ assert.deepStrictEqual(names(dir), [canonicalName(first), legacyName(first)].sort(), `${what}: ${first} holds the hashed lock and its own legacy one; the refused build took nothing and left nothing`);+ held.release();+ assert.deepStrictEqual(names(dir), [], `${what}: released`);+ }+ } finally {+ folder.restore();+ }+ }+});++test('a build of an earlier release, which takes only the legacy file, and a build of this one keep each other out of the pages phase when they spell the app the same way — in both orders', () => {+ for (const app of ['contoso_app', 'Contoso_App']) {+ const dir = makeTempDir('pages-legacy-');+ const legacy = path.join(dir, legacyName(app));+ // The earlier release first: this one is refused by the legacy file, in the words that build's own refusal would use, and lets go of the hashed one.+ const old = acquireLegacyPagesLease(dir, app);+ assert.throws(() => acquireAppPagesLease(dir, app), refusedAt(legacy, app), `${app}: the new build is refused while the old one holds the legacy file`);+ assert.deepStrictEqual(names(dir), [legacyName(app)], `${app}: the new build left nothing of its own behind`);+ old.release();+ // This release first: the earlier one is refused by the same file.+ const held = acquireAppPagesLease(dir, app);+ assert.throws(() => acquireLegacyPagesLease(dir, app), refusedAt(legacy, app), `${app}: the old build is refused while the new one holds the legacy file`);+ held.release();+ assert.deepStrictEqual(names(dir), []);+ }+});++test('the refusal of a live build that holds the lock is the pages refusal it has always been: phase pages, recoverable, never run again, the same sentence', () => {+ const dir = makeTempDir('pages-live-');+ const app = 'contoso_app';+ const old = acquireLegacyPagesLease(dir, app);+ try {+ assert.throws(() => acquireAppPagesLease(dir, app), (e) => {+ assert.strictEqual(e.name, 'BuildHalt');+ assert.strictEqual(e.code, 'pages-locked');+ assert.strictEqual(e.phase, 'pages');+ assert.strictEqual(e.recoverable, true);+ assert.strictEqual(e.retry, 'never');+ assert.strictEqual(e.transient, false);+ assert.strictEqual(isTransientHalt(e), false);+ assert.strictEqual(e.message, REFUSAL(path.join(dir, legacyName(app)), app));+ return true;+ });+ } finally {+ old.release();+ }+});++test('mixed-case and lower-case app names each take their pages lease on this machine\'s own file system — the two files never name one file', () => {+ for (const app of ['Contoso_App', 'contoso_app', 'Contoso App (Preview)']) {+ const dir = makeTempDir('pages-alias-');+ const held = acquireAppPagesLease(dir, app);+ held.release();+ assert.deepStrictEqual(names(dir), [], `${app}: taken and released, nothing left`);+ }+});++test('when the legacy file refuses, the hashed one this build took is let go again, and another build\'s lock is not touched — a stale hashed lock taken over on the way is said, and gone', () => {+ const app = 'contoso_app';+ const foreign = JSON.stringify({ ...ownerStamp(), host: 'some-other-machine', rnd: 'theirs' });+ // A hashed lock nobody holds any more, and a legacy one another machine holds.+ const dir = makeTempDir('pages-partial-');+ const dead = deadPid();+ fs.writeFileSync(path.join(dir, canonicalName(app)), JSON.stringify({ ...ownerStamp({ pid: dead }), rnd: 'killed' }));+ fs.writeFileSync(path.join(dir, legacyName(app)), foreign);+ const warnings = [];+ assert.throws(() => acquireAppPagesLease(dir, app, { warn: (m) => warnings.push(m) }), refusedAt(path.join(dir, legacyName(app)), app));+ assert.deepStrictEqual(names(dir), [legacyName(app)], 'the hashed lock it took over was let go again: nothing of this build is left');+ assert.strictEqual(fs.readFileSync(path.join(dir, legacyName(app)), 'utf8'), foreign, 'the other machine\'s lock is byte for byte what it was');+ assert.strictEqual(warnings.length, 1, `the take-over happened, and is said once: ${JSON.stringify(warnings)}`);+ assert.ok(warnings[0].startsWith(`released the pages lock for '${app}': the build that held it (pid ${dead} on `) && warnings[0].endsWith(') is no longer running'), warnings[0]);++ // A fresh hashed lock and the same foreign legacy one: nothing to say, and nothing left.+ const quiet = makeTempDir('pages-partial-');+ fs.writeFileSync(path.join(quiet, legacyName(app)), foreign);+ const said = [];+ assert.throws(() => acquireAppPagesLease(quiet, app, { warn: (m) => said.push(m) }), refusedAt(path.join(quiet, legacyName(app)), app));+ assert.deepStrictEqual(names(quiet), [legacyName(app)]);+ assert.deepStrictEqual(said, []);+});++test('a folder at a lock\'s name is refused as the file system problem it is — not as another build deploying pages — and nothing this build took is left', () => {+ const app = 'contoso_app';+ // At the legacy name: the hashed lock was taken first, and is let go again.+ const atLegacy = makeTempDir('pages-planted-');+ fs.mkdirSync(path.join(atLegacy, legacyName(app)));+ assert.throws(() => acquireAppPagesLease(atLegacy, app), (e) => {+ assert.notStrictEqual(e.code, 'pages-locked', 'not a refusal that says another build is deploying pages');+ assert.strictEqual(e.code, 'UNSAFE_OUTPUT');+ assert.strictEqual(e.reason, 'not-file');+ return true;+ });+ assert.deepStrictEqual(names(atLegacy), [legacyName(app)], 'only the folder is left: the hashed lock was let go');+ assert.ok(fs.statSync(path.join(atLegacy, legacyName(app))).isDirectory(), 'and the folder is untouched');+ // At the hashed name: refused before anything is taken.+ const atCanonical = makeTempDir('pages-planted-');+ fs.mkdirSync(path.join(atCanonical, canonicalName(app)));+ assert.throws(() => acquireAppPagesLease(atCanonical, app), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-file');+ assert.deepStrictEqual(names(atCanonical), [canonicalName(app)], 'the legacy lock was never taken');+});++test('the hashed lock is taken over only from a build proven gone: a live one, a record of another machine, platform or version, an old { pid, at } lock, a damaged or empty file — refused in the same words, untouched, nothing said', () => {+ const app = 'contoso_app';+ const gone = deadPid();+ const stamp = (overrides) => JSON.stringify({ ...ownerStamp({ pid: gone }), ...overrides, rnd: 'held' });+ const cases = [+ ['this process, which is running', JSON.stringify({ ...ownerStamp(), rnd: 'held' })],+ ['this process, by a record ten minutes old', JSON.stringify({ ...ownerStamp({ now: () => Date.now() - 10 * 60 * 1000 }), rnd: 'held' })],+ ['a record from another machine', stamp({ host: 'some-other-machine' })],+ ['a record from another kind of system', stamp({ platform: process.platform === 'win32' ? 'linux' : 'win32' })],+ ['a record from another pid namespace', stamp({ ns: 'pid:[1]' })],+ ['a lock of a release that recorded only { pid, at }', JSON.stringify({ pid: gone, at: Date.now() - 10 * 60 * 1000 })],+ ['a record of a version this one does not know', stamp({ v: 2 })],+ ['an empty file', ''],+ ['text that is not JSON', 'not json'],+ ];+ for (const [what, content] of cases) {+ const dir = makeTempDir('pages-owner-');+ const file = path.join(dir, canonicalName(app));+ fs.writeFileSync(file, content);+ const warnings = [];+ assert.throws(() => acquireAppPagesLease(dir, app, { warn: (m) => warnings.push(m) }), refusedAt(file, app), what);+ assert.strictEqual(fs.readFileSync(file, 'utf8'), content, `${what}: the lock is as it was`);+ assert.deepStrictEqual(warnings, [], `${what}: nothing was released, so nothing is said`);+ assert.deepStrictEqual(names(dir), [canonicalName(app)], `${what}: the legacy lock was never taken, and no claim was left`);+ }+ // Control: the same lock of a process that is gone is taken over, said once, and the build holds both files.+ const dir = makeTempDir('pages-owner-');+ fs.writeFileSync(path.join(dir, canonicalName(app)), stamp({}));+ fs.writeFileSync(path.join(dir, legacyName(app)), stamp({}));+ const warnings = [];+ const held = acquireAppPagesLease(dir, app, { warn: (m) => warnings.push(m) });+ assert.strictEqual(warnings.length, 1, `one build held both files, so its take-over is said once: ${JSON.stringify(warnings)}`);+ for (const name of [canonicalName(app), legacyName(app)]) assert.strictEqual(JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')).pid, process.pid, `${name} is this build's now`);+ held.release();+ assert.deepStrictEqual(names(dir), []);+});++test('a release leaves a lock another build holds now as it is, without a word — and says so, without failing, when it cannot confirm it removed its own', () => {+ const app = 'contoso_app';+ const dir = makeTempDir('pages-release-');+ const warnings = [];+ const held = acquireAppPagesLease(dir, app, { warn: (m) => warnings.push(m) });+ // Another build took the hashed lock over meanwhile (this one was judged gone): its token stays.+ const theirs = JSON.stringify({ ...ownerStamp(), pid: process.pid + 1, rnd: 'theirs' });+ fs.writeFileSync(path.join(dir, canonicalName(app)), theirs);+ held.release();+ assert.deepStrictEqual(names(dir), [canonicalName(app)], 'this build\'s legacy lock is gone; the other build\'s hashed one stays');+ assert.strictEqual(fs.readFileSync(path.join(dir, canonicalName(app)), 'utf8'), theirs);+ assert.deepStrictEqual(warnings, [], 'a lock that is another build\'s is not this build\'s to report');+ fs.rmSync(path.join(dir, canonicalName(app)));++ // A removal the file system does not carry out (a scanner holds the file, say): the lock is still there, and the release says which file.+ const stuck = makeTempDir('pages-release-');+ const said = [];+ const mine = acquireAppPagesLease(stuck, app, { warn: (m) => said.push(m) });+ const legacy = path.join(stuck, legacyName(app));+ const rmSync = fs.rmSync;+ fs.rmSync = (target, ...rest) => {+ if (path.resolve(String(target)) === path.resolve(legacy)) throw Object.assign(new Error(`EPERM: operation not permitted, unlink '${legacy}'`), { code: 'EPERM' });+ return rmSync.call(fs, target, ...rest);+ };+ try {+ assert.doesNotThrow(() => mine.release(), 'a release never fails what the lock guarded');+ } finally {+ fs.rmSync = rmSync;+ }+ assert.deepStrictEqual(said, [`could not confirm removal of the pages lock for '${app}': ${legacy}. This run has finished; keep the workspace and its recovery records. If a later run still stops here, confirm no build is running before removing only this lock.`]);+ assert.deepStrictEqual(names(stuck), [legacyName(app)], 'the hashed lock was removed; the one that could not be is reported, and left');+ fs.rmSync(legacy);+});++test('a warning callback that throws never leaves a pages lock behind: one that throws while a take-over is said lets go of every file the call took, and is what it throws; one that throws while the files are let go does not stop the release of the others', () => {+ const app = 'contoso_app';+ const logger = () => { throw new Error('logger unavailable'); };+ const gone = JSON.stringify({ ...ownerStamp({ pid: deadPid() }), rnd: 'held' });+ // The take-over of the hashed file, and of the legacy one (the hashed one then taken as it was free).+ for (const [what, planted] of [['the hashed file', canonicalName(app)], ['the legacy file', legacyName(app)]]) {+ const dir = makeTempDir('pages-warn-');+ fs.writeFileSync(path.join(dir, planted), gone);+ assert.throws(() => acquireAppPagesLease(dir, app, { warn: logger }), /^Error: logger unavailable$/, what);+ assert.deepStrictEqual(names(dir), [], `${what}: every file the call took was let go`);+ acquireAppPagesLease(dir, app).release();+ assert.deepStrictEqual(names(dir), [], `${what}: and the next build takes both`);+ }+ // The legacy file cannot be removed, and the warning about it throws: the hashed file is let go all the same, and the release does not throw.+ const dir = makeTempDir('pages-warn-');+ const held = acquireAppPagesLease(dir, app, { warn: logger });+ const legacy = path.join(dir, legacyName(app));+ const rmSync = fs.rmSync;+ fs.rmSync = (target, ...rest) => {+ if (path.resolve(String(target)) === path.resolve(legacy)) throw Object.assign(new Error(`EPERM: operation not permitted, unlink '${legacy}'`), { code: 'EPERM' });+ return rmSync.call(fs, target, ...rest);+ };+ try {+ assert.doesNotThrow(() => held.release());+ } finally {+ fs.rmSync = rmSync;+ }+ assert.deepStrictEqual(names(dir), [legacyName(app)], 'the hashed lock was let go after the legacy one could not be');+ fs.rmSync(legacy);+});diff --git a/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js b/plugins/model-apps/scripts/tests/apply-snapshot-index.test.jsindex fc24f763a..8f7c646a4 100644--- a/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js+++ b/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js@@ -81,11 +81,12 @@ test('optional projection hashes + sitemap hash are recorded when provided', ()test('missing/empty created maps are defensive (no throw, empty submaps)', () => {const a = indexArtifacts(spec(), {});- assert.deepStrictEqual(a.pages, {});+ // `pages` (and `dashboards`) are null-prototype maps (lib/own-keys.js: a page's key can be `constructor`), so their entries are compared.+ assert.deepStrictEqual({ ...a.pages }, {});assert.deepStrictEqual(a.views, {});assert.deepStrictEqual(a.app, {});const b = indexArtifacts({}, {});- assert.deepStrictEqual(b.pages, {});+ assert.deepStrictEqual({ ...b.pages }, {});});test('a page with no content hash records sourceSha:null (still id-tracked)', () => {diff --git a/plugins/model-apps/scripts/tests/bpf-security-roles.test.js b/plugins/model-apps/scripts/tests/bpf-security-roles.test.jsindex 3d360587c..e3d110068 100644--- a/plugins/model-apps/scripts/tests/bpf-security-roles.test.js+++ b/plugins/model-apps/scripts/tests/bpf-security-roles.test.js@@ -24,7 +24,10 @@const { test } = require('node:test');const assert = require('node:assert');const { validateAppSpec, bpfUniqueName, BPF_ROLE_ACCESS, SDK_ROLE_MARKER } = require('../lib/app-spec.js');-const { planFor, runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { planFor, runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const PERSONA = { persona: 'Dispatcher', jobs: [{ name: 'Dispatch', privileges: [{ entity: 'contoso_ticket', access: ['read'] }] }] };const FLOW = {diff --git a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.jsindex 5c2c5a1d2..743523ec0 100644--- a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js+++ b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js@@ -22,7 +22,10 @@ const path = require('node:path');const fs = require('node:fs');const { validateAppSpec } = require('../lib/app-spec.js');-const { bpfDef, runSdkBuild, inspectBpfStages, applyBpfStages } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { bpfDef, runSdkBuild: runSdkBuildInPlace, inspectBpfStages, applyBpfStages } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { desiredBpfStages, deployedBpfStages, diffBpfStages, describeBpfEdit, describeBpfRefusals } = require('../lib/bpf-stages.js');const { classifyChanges } = require('../lib/classify-changes.js');diff --git a/plugins/model-apps/scripts/tests/build-lease-cli.test.js b/plugins/model-apps/scripts/tests/build-lease-cli.test.jsnew file mode 100644index 000000000..f6f715ed2--- /dev/null+++ b/plugins/model-apps/scripts/tests/build-lease-cli.test.js@@ -0,0 +1,140 @@+'use strict';+// The build command (build-model-app.js main) under the build lease (lib/app-operation-lease.js): what it does BEFORE the lease, what it does under+// it, and what it prints after it is let go.+//+// An apply takes the app's build lease after its arguments, its spec and its paths are checked and BEFORE the auth check, the language read, the+// SDK's workspace, the journal, the snapshot and the baseline. So:+// - a second apply of the same app in the workspace is refused at once, and has checked no identity, opened no SDK and touched no file the first+// one is using — its journal, its status, its snapshot, its approval record, its baseline;+// - every way an apply can end — refused identity, a language it cannot use, an SDK or a journal that cannot be opened, a halted phase, a verify that+// could not run, a baseline that could not be written — happened while the lease was held, and what the command prints comes after the lease is+// let go: the result printer ends the process, so a release after it would never run.+// The command is loaded with its real modules, the lease's included; only what reaches an environment or the SDK is a double+// (helpers/build-command-harness.js).+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { appFolder: folderFor, command, settle } = require('./helpers/build-command-harness.js');+const realEntityProvision = require('../lib/entity-provision.js');+const { RETRY } = require('../lib/retry-policy.js');++const SPEC = {+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Lease Probe' },+ entities: [{ schemaName: 'contoso_order', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+};+const appFolder = () => folderFor(SPEC);++function gate() {+ let open;+ const opened = new Promise((resolve) => { open = resolve; });+ return { opened, open };+}++test('a second apply of the same app is refused before its auth check, its SDK or its journal, and leaves the first one\'s journal, status, snapshot, approval and baseline as they were', async () => {+ const folder = appFolder();+ fs.mkdirSync(folder.workspaceDir, { recursive: true });+ // What the first build has on disk while it runs.+ const files = {+ 'build-log.jsonl': '{"phase":"data-model","status":"ok"}\n',+ 'build-status.json': '{"status":"running"}\n',+ 'apply-snapshot.json': '{"schemaVersion":1,"eligible":true}\n',+ 'destructive-approval.json': '{"schemaVersion":1,"formRemovals":{},"sitemapRemovals":[]}\n',+ 'last-applied.json': '{"app":{"name":"Lease Probe"}}\n',+ };+ for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(folder.workspaceDir, name), text);+ const bytes = () => Object.fromEntries(Object.keys(files).map((name) => [name, fs.readFileSync(path.join(folder.workspaceDir, name), 'utf8')]));+ const before = bytes();++ const held = gate();+ const inside = gate();+ const first = command(folder, { auth: async () => { inside.open(); await held.opened; return { ok: false, error: 'the first build stops here' }; } });+ const firstRun = settle(first);+ await inside.opened;++ const second = command(folder, { auth: () => ({ ok: false, error: 'the second build checked its identity' }) });+ const outcome = await settle(second);+ assert.ok(outcome.thrown, `refused, not run: ${JSON.stringify(outcome)} ${second.calls}`);+ assert.strictEqual(outcome.thrown.code, 'build-locked');+ assert.deepStrictEqual(second.calls, [], 'no auth check, no language read, no SDK');+ assert.deepStrictEqual(bytes(), before, 'the first build\'s files are as they were');+ // What main().catch prints for it: the refusal on stderr, nothing on stdout, exit 1.+ assert.throws(() => second.authCli.exports.emitResult(false, outcome.thrown), (e) => e.exitCode === 1);+ assert.strictEqual(second.authCli.stdoutText(), '', 'no stdout JSON');+ assert.strictEqual(second.authCli.stderrText(), `${outcome.thrown.message}\n`);+ assert.match(outcome.thrown.message, /^another build may be applying 'contoso_leaseprobe' in this workspace/);++ held.open();+ assert.deepStrictEqual(await firstRun, { exitCode: 1 });+ assert.ok(!first.held(), 'the first build let go when it ended');+});++test('an identity the auth check refuses, and a language that cannot be used, end an apply that already held its lease — and what is printed, or thrown to main().catch, comes after the release', async () => {+ // The identity: the result is the `{ ok: false, error }` the command has always printed for it.+ const refused = appFolder();+ let heldAtAuth = null;+ const auth = command(refused, { auth: (held) => { heldAtAuth = held(); return { ok: false, error: 'sign in as [email protected]' }; } });+ assert.deepStrictEqual(await settle(auth), { exitCode: 1 });+ assert.strictEqual(heldAtAuth, true, 'the lease was held when the auth check ran');+ assert.strictEqual(auth.printed.heldThen, false, 'and let go before the result was printed');+ assert.deepStrictEqual(JSON.parse(auth.authCli.stdoutText()), { ok: false, error: 'sign in as [email protected]' });+ assert.strictEqual(auth.authCli.stderrText(), 'sign in as [email protected]\n');+ assert.deepStrictEqual(auth.calls, ['auth'], 'no language read, no SDK, no journal');+ assert.ok(!fs.existsSync(path.join(refused.workspaceDir, 'build-log.jsonl')), 'no journal was opened');++ // The language: an error, which main().catch prints.+ const language = appFolder();+ let heldAtLanguage = null;+ const lang = command(language, { language: (held) => { heldAtLanguage = held(); throw new Error('language 1031 is not provisioned in this environment'); } });+ const outcome = await settle(lang);+ assert.strictEqual(heldAtLanguage, true, 'the lease was held when the language was read');+ assert.ok(outcome.thrown instanceof Error && /1031 is not provisioned/.test(outcome.thrown.message), JSON.stringify(outcome));+ assert.strictEqual(outcome.heldThen, false, 'and let go before the error reached main().catch');+ assert.deepStrictEqual(lang.calls, ['auth', 'language'], 'no SDK, no journal');+ assert.strictEqual(lang.printed.ok, null, 'nothing was printed under the lease');+});++test('an SDK or a journal that cannot be opened, a halted phase, a verify that cannot run and a baseline that cannot be written each happen under the lease, which is let go before anything is printed', async () => {+ const halt = new realEntityProvision.BuildHalt('data-model failed: bad request', { phase: 'data-model', code: 'sdk-error', retry: RETRY.NEVER });+ const cases = [+ ['the SDK cannot be made', { makeSdk: () => { throw new Error('the SDK could not be made'); } }, { thrown: /SDK could not be made/ }],+ ['the journal cannot be opened', { openJournal: () => { throw new Error('the journal could not be opened'); } }, { thrown: /journal could not be opened/ }],+ ['a phase halts', { engine: () => { throw halt; } }, { thrown: /data-model failed/ }],+ ['the verify cannot run', { argv: ['--verify'], verify: () => { throw new Error('the verify could not read the app'); } }, { exitCode: 0 }],+ ['the baseline cannot be written', { writeBaseline: () => { throw new Error('ENOSPC: no space left on device'); } }, { exitCode: 0 }],+ ];+ for (const [what, doubles, expected] of cases) {+ const folder = appFolder();+ const heldAt = [];+ const wrapped = Object.fromEntries(Object.entries(doubles).map(([key, fn]) => [key, typeof fn === 'function' ? (held, ...rest) => { heldAt.push(held()); return fn(held, ...rest); } : fn]));+ const run = command(folder, wrapped);+ const outcome = await settle(run);+ assert.deepStrictEqual(heldAt, [true], `${what}: it happened while the lease was held`);+ if (expected.thrown) {+ assert.match(String(outcome.thrown && outcome.thrown.message), expected.thrown, `${what}: ${JSON.stringify(outcome)}`);+ assert.strictEqual(outcome.heldThen, false, `${what}: let go before the error reached main().catch`);+ } else {+ assert.deepStrictEqual(outcome, { exitCode: expected.exitCode }, what);+ assert.strictEqual(run.printed.heldThen, false, `${what}: let go before the result was printed`);+ }+ assert.ok(!run.held(), `${what}: no lock left`);+ }+});++test('the baseline a successful apply writes is written under the lease: a second apply started then is refused', async () => {+ const folder = appFolder();+ let refusal = null;+ const run = command(folder, {+ writeBaseline: () => {+ const other = command(folder);+ // Started from inside the first one's baseline write, so it is checked synchronously here: the lease it meets is the first one's.+ refusal = other.cli.main().then(() => null, (e) => e);+ },+ });+ assert.deepStrictEqual(await settle(run), { exitCode: 0 });+ const e = await refusal;+ assert.strictEqual(e && e.code, 'build-locked', String(e && e.stack));+});diff --git a/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.jsnew file mode 100644index 000000000..66a2881e9--- /dev/null+++ b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js@@ -0,0 +1,256 @@+'use strict';+// The build lease (lib/app-operation-lease.js) over the REAL vendored SDK, the plugin's own HTTP client and the stateful fake Dataverse of+// helpers/fake-lifecycle-org.js, through the harness the lifecycle tests share (helpers/lifecycle-harness.js): two builds of one app started+// in one workspace, the second while the first is inside a window where two builds would each create what only one may.+//+// Before the lease, the overlap was measured live: two builds in one workspace both looked up the app's generated icon (`<app>_icon`), both+// found nothing, and both created one and added it to the solution; one app create then failed with a 412. So a barrier holds the first build+// INSIDE such a window — at its request that looks the icon up, at the write of a web resource its spec authors, at the create of an app whose+// navigation holds only pages (made at the end of the pages phase) — and the second build is started then. It is refused (`build-locked`) and+// sends nothing; the first is released once that refusal is seen — never after waiting for a request of the second's, which would not come —+// and creates one of each. A build without the lease sends the second build's lookup too, and the barrier, released once both lookups are in,+// lets both builds create an icon: what these tests fail on there.+//+// And what the lease changes for nobody else: a teardown still deletes the one icon its lookup (`$top=1`) answers, not every row of that name;+// a build that runs alone sends exactly the requests it sent before the lease.+const { test } = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createLifecycleHarness, ICON_SVG } = require('./helpers/lifecycle-harness.js');+const { appUniqueName } = require('../lib/sdk-build.js');+const { sha256 } = require('../lib/hash.js');++// One table and an app over it, with a generated icon (the spec names none). `authored` adds a web resource the spec authors; `pagesOnly` makes+// the navigation one generative page, so the app is created at the end of the pages phase (the page's source is the file the harness writes into+// the app folder, KitchenPage.tsx).+function raceSpec({ authored = false, pagesOnly = false } = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoLeaseRace', displayName: 'Contoso Lease Race', publisherPrefix: 'contoso' },+ app: { name: 'Lease Race' },+ entities: [{ schemaName: 'contoso_project', displayName: 'Project', pluralName: 'Projects', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],+ ...(authored ? { webResources: [{ name: 'contoso_leaserace.svg', displayName: 'Lease Race Image', type: 'svg', content: ICON_SVG }] } : {}),+ ...(pagesOnly ? { pages: [{ key: 'overview', name: 'Race Page', purpose: 'A page over projects.', dataSources: ['contoso_project'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }] } : {}),+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: [pagesOnly ? { page: 'overview', title: 'Race Page' } : { entity: 'contoso_project', title: 'Projects' }] }] }] },+ };+}+const APP = appUniqueName(raceSpec());+const ICON = `${APP}_icon`;++// A request as the fake's transport receives it, read for matching: the path below the API root, the query decoded, the body parsed.+// GET /api/data/v9.2/webresourceset?$select=webresourceid&$filter=name eq 'contoso_leaserace_icon'&$top=1+const pathOf = (req) => decodeURIComponent(new URL(req.url).pathname).replace(/^\/api\/data\/v9\.\d/, '');+const queryOf = (req) => decodeURIComponent(new URL(req.url).search);+const bodyOf = (req) => { try { return JSON.parse(req.body); } catch { return null; } };++const looksUpIcon = (r) => r.method === 'GET' && r.path === '/webresourceset' && r.query.includes(`name eq '${ICON}'`);+const writesWebResource = (name) => (r) => r.method === 'POST' && r.path === '/webresourceset' && r.body && r.body.name === name;+const createsApp = (r) => r.method === 'POST' && r.path === '/appmodules';++// A fake environment whose transport holds every request `holdIf` matches until `release()`, and records every request (`wire`) as it arrives —+// a held one included. `holding(n)` resolves once n requests are held.+function raceEnvironment(holdIf) {+ const org = createLifecycleOrg();+ const wire = [];+ const held = [];+ const waiters = [];+ let release;+ const released = new Promise((resolve) => { release = resolve; });+ const request = async (req) => {+ const entry = { method: req.method, path: pathOf(req), query: queryOf(req), body: bodyOf(req) };+ wire.push(entry);+ if (holdIf && holdIf(entry)) {+ held.push(entry);+ for (const w of waiters.splice(0)) w();+ await released;+ }+ return org.request(req);+ };+ const holding = (n) => new Promise((resolve) => {+ const check = () => (held.length >= n ? resolve() : waiters.push(check));+ check();+ });+ const harness = createLifecycleHarness({ ...org, request }, makeTempDir('build-lease-race-'));+ if (!fs.existsSync(path.join(harness.appDir, 'KitchenPage.tsx'))) throw new Error('the harness writes the page source');+ return { org, harness, wire, held, holding, release };+}++// The first build held in its window, a second build of the same app started in the same workspace, and the first released once the second has+// settled — or, where nothing refuses the second, once the second's own request reached the window as well. Answers what each came to, and the+// requests the second sent before it settled.+async function overlap(env, spec) {+ const first = env.harness.build(spec).then((r) => r, (e) => ({ error: e }));+ await env.holding(1);+ const mark = env.wire.length;+ // The second build's SDK keeps its copies apart from the first's: the command makes none for an apply its lease refuses.+ const second = env.harness.build(spec, { sdkWorkspace: makeTempDir('build-lease-second-sdk-') }).then((r) => r, (e) => ({ error: e }));+ let sentBySecond = null;+ await Promise.race([second.then(() => { sentBySecond = env.wire.slice(mark); }), env.holding(2)]);+ env.release();+ return { first: await first, second: await second, sentBySecond };+}++const refusedAsLocked = (outcome) => {+ const e = outcome.error;+ assert.ok(e, `the second build was refused, not run: ${JSON.stringify(outcome.result && { ok: outcome.result.ok, errors: outcome.result.errors })}`);+ assert.strictEqual(e.code, 'build-locked', String(e.stack));+ assert.strictEqual(e.retry, 'never');+};+const built = (outcome, what) => {+ assert.ok(!outcome.error, `${what}: ${outcome.error && outcome.error.stack}`);+ assert.strictEqual(outcome.result.ok, true, `${what}: ${JSON.stringify(outcome.result.errors)}`);+};+const noLockLeft = (env) => {+ const lock = path.join(env.harness.workspaceDir, `app-build.${sha256(APP.toLowerCase())}.lock`);+ assert.ok(!fs.existsSync(lock), 'no build lock is left');+};++test('two first builds of one app in one workspace cannot create its generated icon twice: the second is refused before it sends a request, and the first makes one icon and one app', async () => {+ const env = raceEnvironment(looksUpIcon);+ const { first, second, sentBySecond } = await overlap(env, raceSpec());+ // The counts first: where nothing refuses the second build, they are what shows the race.+ assert.strictEqual(env.wire.filter(writesWebResource(ICON)).length, 1, 'one icon create');+ assert.strictEqual(env.org.find('webresourceset', (w) => w.name === ICON).length, 1, 'the environment holds one icon');+ assert.strictEqual(env.wire.filter(createsApp).length, 1, 'one app create');+ assert.strictEqual(env.org.find('appmodules', (a) => a.uniquename === APP).length, 1, 'and one app');+ assert.strictEqual(env.held.length, 1, 'one lookup reached the window');+ refusedAsLocked(second);+ assert.deepStrictEqual(sentBySecond, [], 'the second build sent nothing — not even the lookup');+ built(first, 'the first build');+ noLockLeft(env);+});++test('a second build is refused while the first writes a web resource its spec authors', async () => {+ {+ const env = raceEnvironment(writesWebResource('contoso_leaserace.svg'));+ const { first, second, sentBySecond } = await overlap(env, raceSpec({ authored: true }));+ assert.strictEqual(env.wire.filter(writesWebResource('contoso_leaserace.svg')).length, 1, 'one write of the authored web resource');+ assert.strictEqual(env.org.find('webresourceset', (w) => w.name === 'contoso_leaserace.svg').length, 1);+ refusedAsLocked(second);+ assert.deepStrictEqual(sentBySecond, [], 'the second build sent nothing');+ built(first, 'the first build');+ noLockLeft(env);+ }+});++test('a second build is refused while the first creates, at the end of its pages, an app whose navigation holds only pages', async () => {+ {+ const env = raceEnvironment(createsApp);+ const { first, second, sentBySecond } = await overlap(env, raceSpec({ pagesOnly: true }));+ assert.strictEqual(env.wire.filter(createsApp).length, 1, 'one app create');+ assert.strictEqual(env.org.find('appmodules', (a) => a.uniquename === APP).length, 1);+ refusedAsLocked(second);+ assert.deepStrictEqual(sentBySecond, [], 'the second build sent nothing');+ built(first, 'the first build');+ noLockLeft(env);+ }+});++test('a teardown deletes the one generated icon its lookup answers ($top=1) — a second row of that name, in the app\'s solution, is not deleted', async () => {+ const env = raceEnvironment(null);+ const spec = raceSpec();+ built(await env.harness.build(spec).then((r) => r, (e) => ({ error: e })), 'the build');+ const [builtIcon] = env.org.find('webresourceset', (w) => w.name === ICON);+ assert.ok(builtIcon, 'the build made the icon');+ // Another row of the same name, added to the same solution — as a build without the lease could have left.+ const planted = '33333333-0000-4000-8000-000000000001';+ const res = await env.org.request({+ url: `${env.org.API}/webresourceset`, method: 'POST',+ headers: { 'Content-Type': 'application/json', 'MSCRM.SolutionUniqueName': spec.solution.uniqueName },+ body: JSON.stringify({ webresourceid: planted, name: ICON, displayname: 'Lease Race Icon', webresourcetype: 11, content: Buffer.from(ICON_SVG).toString('base64') }),+ });+ assert.ok(res.statusCode < 300, `planted: ${res.statusCode} ${res.body}`);+ const mark = env.wire.length;+ const { result } = await env.harness.teardown(spec);+ assert.ok(result, 'the teardown ran');+ const lookups = env.wire.slice(mark).filter(looksUpIcon);+ assert.ok(lookups.length >= 1, 'the teardown looked the icon up by name');+ for (const l of lookups) assert.ok(/\$top=1(&|$)/.test(l.query), `by its name, for one row: ${l.query}`);+ assert.deepStrictEqual(env.org.find('webresourceset', (w) => w.name === ICON).map((w) => w.webresourceid), [planted], 'the icon the lookup answered is deleted; the other row is kept');+});++// What a build that runs alone sends, by `METHOD entity set` — ids, keys and queries left out — as the build sent it before the lease (2.18.0),+// for the first build and an unchanged rebuild of the same spec. The lease is a file in the workspace: a build that meets no other sends exactly+// this, and a request the lease added would show here.+const ALONE = {+ build: {+ 'GET /appmodulecomponents': 5,+ 'GET /appmodules': 4,+ 'GET /appmodules()': 2,+ 'GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 4,+ 'GET /appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 1,+ 'GET /EntityDefinitions': 1,+ 'GET /EntityDefinitions()': 11,+ 'GET /EntityDefinitions()/Attributes': 1,+ 'GET /publishers': 1,+ 'GET /roles': 1,+ 'GET /savedqueries': 1,+ 'GET /savedqueryvisualizations': 1,+ 'GET /settingdefinitions': 1,+ 'GET /sitemaps': 2,+ 'GET /sitemaps()': 1,+ 'GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 1,+ 'GET /solutions': 2,+ 'GET /systemforms': 1,+ 'GET /webresourceset': 2,+ 'GET /webresourceset()': 2,+ 'POST /AddAppComponents': 1,+ 'POST /AddSolutionComponent': 4,+ 'POST /appmodules': 1,+ 'POST /appmodules()/appmoduleroles_association/$ref': 1,+ 'POST /appsettings': 1,+ 'POST /EntityDefinitions': 1,+ 'POST /publishers': 1,+ 'POST /PublishXml': 5,+ 'POST /sitemaps': 1,+ 'POST /solutions': 1,+ 'POST /webresourceset': 2,+ },+ rebuild: {+ 'GET /appmodulecomponents': 19,+ 'GET /appmodules': 6,+ 'GET /appmodules()': 6,+ 'GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 22,+ 'GET /EntityDefinitions': 1,+ 'GET /EntityDefinitions()': 10,+ 'GET /EntityDefinitions()/Attributes': 2,+ 'GET /savedqueries': 1,+ 'GET /savedqueryvisualizations': 1,+ 'GET /sitemaps': 3,+ 'GET /sitemaps()': 6,+ 'GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 6,+ 'GET /solutioncomponents': 1,+ 'GET /solutions': 3,+ 'GET /systemforms': 1,+ 'GET /systemforms/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 1,+ 'GET /uxagentprojects': 1,+ 'GET /webresourceset': 3,+ 'PATCH /sitemaps()': 1,+ 'POST /AddAppComponents': 1,+ 'POST /PublishXml': 3,+ },+};+// PATCH /EntityDefinitions(LogicalName='contoso_project')/Attributes(3f…) -> 'PATCH /EntityDefinitions()/Attributes()'+const multiset = (requests) => {+ const out = {};+ for (const r of requests) {+ const key = `${r.method} ${r.path.replace(/\([^)]*\)/g, '()')}`;+ out[key] = (out[key] || 0) + 1;+ }+ return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b)));+};++test('a build that meets no other sends the requests it sent before the lease: its first build and an unchanged rebuild', async () => {+ const env = raceEnvironment(null);+ const spec = raceSpec({ authored: true });+ const first = env.wire.length;+ built(await env.harness.build(spec).then((r) => r, (e) => ({ error: e })), 'the build');+ const afterBuild = env.wire.length;+ built(await env.harness.build(spec).then((r) => r, (e) => ({ error: e })), 'the rebuild');+ const seen = { build: multiset(env.wire.slice(first, afterBuild)), rebuild: multiset(env.wire.slice(afterBuild)) };+ if (process.env.PRINT_ALONE) process.stdout.write(`# ALONE ${JSON.stringify(seen)}\n`);+ assert.deepStrictEqual(seen, ALONE);+});diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex a75cd933f..1660c91c9 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -6,7 +6,11 @@ const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');const fs = require('node:fs');-const { buildModelApp, isTransientHalt, discoverOpDiffState, parseLanguageCode, assertSnapshotInvalidated } = require(path.join(__dirname, '..', 'build-model-app.js'));+// An apply that names no app folder and no workspace gets a workspace of its own, which holds its build lease (helpers/own-app-folder.js): its specs name+// page source that is not on disk, which an app folder would make the build check.+const { inOwnWorkspace } = require('./helpers/own-app-folder.js');+const { buildModelApp: buildModelAppInPlace, isTransientHalt, discoverOpDiffState, parseLanguageCode, assertSnapshotInvalidated } = require(path.join(__dirname, '..', 'build-model-app.js'));+const buildModelApp = inOwnWorkspace(buildModelAppInPlace);const { verifySpec } = require(path.join(__dirname, '..', 'lib', 'verify-spec.js'));const { resolveLanguageCode } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));const { validateAppSpec, normalizeLanguageCode } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));diff --git a/plugins/model-apps/scripts/tests/business-process-flows.test.js b/plugins/model-apps/scripts/tests/business-process-flows.test.jsindex d9db134ae..c8a98a1a3 100644--- a/plugins/model-apps/scripts/tests/business-process-flows.test.js+++ b/plugins/model-apps/scripts/tests/business-process-flows.test.js@@ -20,7 +20,10 @@ const path = require('node:path');const fs = require('node:fs');const { validateAppSpec } = require('../lib/app-spec.js');-const { bpfDef, bpfFilter, runSdkBuild, planFor, PHASES } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { bpfDef, bpfFilter, runSdkBuild: runSdkBuildInPlace, planFor, PHASES } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { verifySpec } = require('../lib/verify-spec.js');const { planTeardown, KIND_HANDLERS } = require('../lib/sdk-teardown.js');const { PHASES: STAGE_PHASES, STAGES } = require('../lib/stages.js');diff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsindex 14bdcd98d..3897a73fc 100644--- a/plugins/model-apps/scripts/tests/business-rules.test.js+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -466,7 +466,10 @@ test('verify fails CLOSED when the workflow read itself errors', async () => {//// An ordered, complete read makes reuse deterministic and reports additional matches. A name// does not prove another definition was created by this run, so rebuild must not delete it.-const { runSdkBuild: runBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runBuildInPlace } = require('../lib/sdk-build.js');+const runBuild = inOwnFolder(runBuildInPlace);function ruleOnlySpec() {const s = specWith([{diff --git a/plugins/model-apps/scripts/tests/changed-only-flow.test.js b/plugins/model-apps/scripts/tests/changed-only-flow.test.jsindex 8fa375513..4d8a4e056 100644--- a/plugins/model-apps/scripts/tests/changed-only-flow.test.js+++ b/plugins/model-apps/scripts/tests/changed-only-flow.test.js@@ -265,6 +265,44 @@ test('run: FAST apply calls buildModelApp pages-only + re-blesses the snapshot e} finally { rm(dir); }});+// The fast apply writes the changed pages, and a navigation target only when it is absent (the pages phase makes it first). The build checks a page's bindings before it writes anything, before the pages+// phase has read which targets exist, so the flow tells it the pages its snapshot records the last verified apply deployed: a target among them is not checked, and one that is not may be absent.+test('run: a FAST apply tells the build which pages its snapshot records as deployed — each with a page id, and no other', async () => {+ const dir = ws();+ try {+ const prior = annotate(baseSpec(), 'v1');+ const env = snap.makeEnvelope(LIVE, { generation: 'g0' });+ env.priorSpec = prior;+ env.artifacts = { pages: {+ overview: { pageId: 'page-1', sourceSha: prior.pages[0].__contentSha, deployedSha: prior.pages[0].__contentSha },+ detail: { pageId: 'page-2', sourceSha: 'sha-detail', deployedSha: 'sha-detail' },+ unplaced: { pageId: null, sourceSha: 'sha-unplaced', deployedSha: 'sha-unplaced' },+ } };+ snap.markEligible(env);+ store.writeSnapshotAtomic(dir, env);+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { record, buildModelApp: stubBuild(record), readContent: readFor('v2') }) });+ assert.strictEqual(r.changedOnly.decision, 'fast');+ assert.deepStrictEqual(record[0].changedOnly.selectedKeys, ['overview']);+ assert.deepStrictEqual([...record[0].changedOnly.deployedKeys].sort(), ['detail', 'overview'], 'a record without a page id proves no page');+ } finally { rm(dir); }+});++test('run: a FAST apply over a snapshot that records no pages tells the build that none is deployed — so it checks every navigation target', async () => {+ const dir = ws();+ try {+ const prior = annotate(baseSpec(), 'v1');+ const env = snap.makeEnvelope(LIVE, { generation: 'g0' });+ env.priorSpec = prior;+ snap.markEligible(env);+ store.writeSnapshotAtomic(dir, env);+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { record, buildModelApp: stubBuild(record), readContent: readFor('v2') }) });+ assert.strictEqual(r.changedOnly.decision, 'fast');+ assert.deepStrictEqual(record[0].changedOnly.deployedKeys, []);+ } finally { rm(dir); }+});+test('run: a fast apply whose page VERIFY did not pass is NOT re-blessed (fail-closed)', async () => {const dir = ws();try {@@ -597,6 +635,12 @@ test('run: the no-identity fallback on a workspace with no snapshot sees a teard// Two no-identity builds that read the same generation, one inside the other, each saw it unchanged at the end and// both reported success. Each now takes a generation of its own before it builds, so the first sees the second's.+//+// The build lease (lib/app-operation-lease.js) now refuses a second apply of the same app in the same workspace before it+// reads anything, so a build of this release can no longer start inside another. The snapshot's generation fence is still+// what guards against a writer the lease does not hold back — a build of an earlier release, which takes no build lease, a+// teardown — so the tests of that fence start their second writer with the first one's lease (`buildLease: o.buildLease`,+// what a nested apply borrows): it then runs beside the first exactly as such a writer would.test('run: overlapping no-identity builds do not both pass', async () => {for (const [what, seed] of [['on a workspace with no snapshot', () => {}],@@ -607,8 +651,8 @@ test('run: overlapping no-identity builds do not both pass', async () => {seed(dir);let inner = null;const innerDeps = baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => null });- const build = async () => {- inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: innerDeps });+ const build = async (s, o) => {+ inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease: o.buildLease }, deps: innerDeps });return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } };};const outer = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });@@ -651,8 +695,8 @@ test('run: the no-identity fallback invalidates an existing baseline before it b// cannot noop on it.test('run: a build that saw the workspace change under it leaves no eligible baseline behind', async () => {const FRESH = { ...LIVE, appId: null, appIdKnown: true };- const blessedInside = async (dir) => {- const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ const blessedInside = async (dir, buildLease) => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });assert.strictEqual(inner.ok, true, JSON.stringify(inner.errors));assert.strictEqual(store.readSnapshot(dir).eligible, true, 'precondition: the inner build blessed a fresh baseline');};@@ -663,7 +707,7 @@ test('run: a build that saw the workspace change under it leaves no eligible basconst dir = ws();try {seed(dir);- const build = async () => { await blessedInside(dir); return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } }; };+ const build = async (s, o) => { await blessedInside(dir, o.buildLease); return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } }; };await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: outerIdentity }) });assert.strictEqual(store.readSnapshot(dir).eligible, false, `${what}: the baseline blessed meanwhile is no longer eligible`);const next = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => ({ ...LIVE }) }) });@@ -691,8 +735,8 @@ test('run: a build paused before its baseline write cannot bless it after anotheresolveLiveIdentity: async () => { calls += 1; if (calls === 2) { signalPaused(); await gate; } return FRESH; },});let inner = null;- const outerBuild = async () => {- inner = flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: innerDeps });+ const outerBuild = async (s, o) => {+ inner = flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease: o.buildLease }, deps: innerDeps });await paused;return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } };};@@ -715,8 +759,8 @@ test('run: a build that fails or throws still distrusts a baseline another build]) {const dir = ws();try {- const build = async () => {- const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ const build = async (s, o) => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease: o.buildLease }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });assert.strictEqual(inner.ok, true, `${what}: ${JSON.stringify(inner.errors)}`);assert.strictEqual(store.readSnapshot(dir).eligible, true, `${what}: precondition: the inner build blessed a baseline`);return finish();@@ -738,16 +782,19 @@ test('run: a baseline blessed between a build and its own baseline write is distconst dir = ws();try {let calls = 0;+ // The other writer runs with this build's lease (see 'run: overlapping no-identity builds do not both pass'), which the build hands its builds.+ let held;+ const build = async (s, o, d) => { held = o.buildLease; return stubBuild([])(s, o, d); };const resolve = async () => {calls += 1;if (calls === 2) {- const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease: held }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });assert.strictEqual(inner.ok, true, JSON.stringify(inner.errors));assert.strictEqual(store.readSnapshot(dir).eligible, true, 'precondition: blessed between the build and the write');}return FRESH;};- const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: resolve }) });+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: resolve }) });assert.ok(calls >= 2, 'the fresh build looked its identity up again before writing');assert.strictEqual(store.readSnapshot(dir).eligible, false);assert.strictEqual(r.ok, false, 'the refused write was a conflict, so the run fails');@@ -809,8 +856,8 @@ test('run: a distrust that cannot land leaves a marker, and the next run builds]) {const dir = ws();try {- const build = async () => {- const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ const build = async (s, o) => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true, buildLease: o.buildLease }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });assert.strictEqual(inner.ok, true, `${what}: ${JSON.stringify(inner.errors)}`);// Another live writer holds the lease, so no invalidate this run's distrust tries can land.fs.writeFileSync(store.leasePath(dir), JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'held' }));diff --git a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.jsindex c2611b21f..463791ec1 100644--- a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js@@ -34,6 +34,7 @@ const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdkconst { isTransientHalt } = require('../build-model-app.js');const { sha256 } = require('../lib/hash.js');const { environmentFingerprint } = require('../lib/page-ownership-records.js');+const { leaveLocksOfKilledBuild } = require('./helpers/killed-build-locks.js');// Loaded where it is used, so that every test below fails on its own assertion when the module is not there.const records = () => require('../lib/dashboard-creation-records.js');@@ -288,6 +289,8 @@ function ran(step, label) {// The build is killed the moment it sends the new dashboard's membership add: that request never answers, and nothing of the run happens after// it — no undo, no record cleared, no app. Answers the id the add named, which is the row the create committed. `buildSpec` is the spec it builds.+// A kill also ends the process, which leaves the build's lock in the workspace under a pid that is gone, for the next build to take over+// (helpers/killed-build-locks.js): the unsettled build here is in this process, so its lock is handed to such a pid.async function dieAtMembership(env, buildSpec = spec) {let named;const reached = new Promise((resolve) => { named = resolve; });@@ -298,6 +301,7 @@ async function dieAtMembership(env, buildSpec = spec) {fault.lift();await new Promise((resolve) => setImmediate(resolve));assert.equal(settled, false, 'the killed build never finishes');+ leaveLocksOfKilledBuild(env.harness.workspaceDir);return id;}diff --git a/plugins/model-apps/scripts/tests/dataverse-auth.test.js b/plugins/model-apps/scripts/tests/dataverse-auth.test.jsindex ec1af30e5..ef1d42753 100644--- a/plugins/model-apps/scripts/tests/dataverse-auth.test.js+++ b/plugins/model-apps/scripts/tests/dataverse-auth.test.js@@ -711,12 +711,13 @@ test('both CLIs report an auth-preflight failure with the SAME payload shape', (// for the identical failure — and the one users hit on an apply printed the count, replacing a// message written specifically to say which identity to sign in as.//- // Asserted on the SOURCE because the alternative is spawning both CLIs against a live tenant.+ // Asserted on the SOURCE because the alternative is spawning both CLIs against a live tenant. build-model-app.js answers the result+ // (`payload`) for main() to print once its build lease is let go (tests/build-lease-cli.test.js prints it through the real printer).const fs = require('node:fs');const path = require('node:path');for (const cli of ['build-model-app.js', 'download-model-app.js']) {const src = fs.readFileSync(path.join(__dirname, '..', cli), 'utf8');- const line = src.split('\n').find((l) => /emitResult\(false,.*auth\.error/.test(l));+ const line = src.split('\n').find((l) => /(?:emitResult\(false,|payload:\s*\{).*auth\.error/.test(l));assert.ok(line, `${cli}: expected an emitResult call carrying auth.error`);assert.match(line, /error:\s*auth\.error/, `${cli}: a single explained failure must use \`error\`: ${line.trim()}`);assert.doesNotMatch(line, /errors:\s*\[/, `${cli}: \`errors: [...]\` is for PARTIAL failures and prints only a count: ${line.trim()}`);diff --git a/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.jsindex 5f7a37c27..7fc0c0673 100644--- a/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js+++ b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js@@ -16,7 +16,10 @@ const test = require('node:test');const assert = require('node:assert');const { readDashboards } = require('../download-model-app.js');const { hydrateSpec } = require('../lib/hydrate-spec.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { createHarness } = require('./helpers/form-store-harness.js');const DASHBOARD_ID = '33333333-3333-4333-8333-333333333333';diff --git a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.jsindex 63ad77ee9..034aa71a2 100644--- a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js+++ b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js@@ -266,7 +266,8 @@ test('downloaded ownership survives rebuild and teardown planning', async () =>});assert.strictEqual(rebuild.ok, true);assert.strictEqual(rebuild.created.app, APP_ID, 'a display-name rename cannot redirect the rebuild');- assert.deepStrictEqual(rebuild.created.pages, { overview: OVERVIEW_ID, detail: DETAIL_ID });+ // `created.pages` is a null-prototype map (lib/own-keys.js: a page's key can be `constructor`), so its entries are compared.+ assert.deepStrictEqual({ ...rebuild.created.pages }, { overview: OVERVIEW_ID, detail: DETAIL_ID });assert.ok(!fixture.calls.some((c) => ['createTable', 'createRelationship', 'enrichDefaultViews'].includes(c.method)),`reused tables and relationships are not recreated or enriched: ${JSON.stringify(fixture.calls.filter((c) => ['createTable', 'createRelationship', 'enrichDefaultViews'].includes(c.method)))}`);assert.strictEqual(spec.entities.every((e) => e.existing === true), true);@@ -571,7 +572,7 @@ async function redeployAfterRedownload(earlierKeyOfId, { fromEmptyFolder = falseconst rebuilt = await deploy(portable(again));// What matters first: the other environment's pages. Each id holds its own name and content, as it did before the second download.assert.deepStrictEqual(held(target, TARGET_IDS), before, 'each page of the other environment still holds its own name and content');- assert.deepStrictEqual(rebuilt.created.pages, { [earlierKeyOfId[OVERVIEW_ID]]: TARGET_IDS[0], [earlierKeyOfId[DETAIL_ID]]: TARGET_IDS[1] });+ assert.deepStrictEqual({ ...rebuilt.created.pages }, { [earlierKeyOfId[OVERVIEW_ID]]: TARGET_IDS[0], [earlierKeyOfId[DETAIL_ID]]: TARGET_IDS[1] });assert.strictEqual(target.genpage.of('create').length, 0, 'no page is created: every key binds the page it built');// And why: each page has the key it had.assert.deepStrictEqual(keysByName(again), expectedKeys, 'every page keeps the key it had');diff --git a/plugins/model-apps/scripts/tests/form-field-flags-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-field-flags-real-bundle.test.jsindex d47362f07..b39460496 100644--- a/plugins/model-apps/scripts/tests/form-field-flags-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-field-flags-real-bundle.test.js@@ -13,7 +13,10 @@const test = require('node:test');const assert = require('node:assert');const ai = require('../lib/artifact-intent.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { validateAppSpec } = require('../lib/app-spec.js');const { guid, createHarness, seedForm, verifyForms } = require('./helpers/form-store-harness.js');diff --git a/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.jsindex dae5aeda9..30142f1e6 100644--- a/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-label-language-real-bundle.test.js@@ -20,8 +20,12 @@const test = require('node:test');const assert = require('node:assert');const ai = require('../lib/artifact-intent.js');-const { runSdkBuild } = require('../lib/sdk-build.js');-const { buildModelApp } = require('../build-model-app.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);+const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+const buildModelApp = inOwnFolder(buildModelAppInPlace);const { createHarness, seedForm, verifyForms } = require('./helpers/form-store-harness.js');const { readLanguageCodeFlag } = require('../lib/dataverse-auth.js');const { workbookXml, zipOf, exportZip, exportAnswer } = require('./helpers/translation-export.js');diff --git a/plugins/model-apps/scripts/tests/form-order-build.test.js b/plugins/model-apps/scripts/tests/form-order-build.test.jsindex 6234fbb8f..fa8cbf5b9 100644--- a/plugins/model-apps/scripts/tests/form-order-build.test.js+++ b/plugins/model-apps/scripts/tests/form-order-build.test.js@@ -12,7 +12,10 @@const test = require('node:test');const assert = require('node:assert');-const { runSdkBuild, planFor } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, planFor } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk, rolesOfDisplayConditions, applyRolesWrite } = require('./helpers/mock-sdk.js');const FORM_TYPE = { Main: 2, QuickCreate: 7, QuickView: 6 };diff --git a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.jsindex fe9b2a41c..a52d2b80d 100644--- a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js@@ -8,7 +8,10 @@ const os = require('node:os');const path = require('node:path');const fs = require('node:fs');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');const FORM_ID = '11111111-1111-1111-1111-111111111111';diff --git a/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.jsindex 46045d5c9..705e12104 100644--- a/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js@@ -8,7 +8,10 @@ const os = require('node:os');const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');const ai = require('../lib/artifact-intent.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { verifySpec } = require('../lib/verify-spec.js');const { readerFor } = require('../verify-model-app.js');diff --git a/plugins/model-apps/scripts/tests/form-security-roles.test.js b/plugins/model-apps/scripts/tests/form-security-roles.test.jsindex 40e711141..9a1e8e8ad 100644--- a/plugins/model-apps/scripts/tests/form-security-roles.test.js+++ b/plugins/model-apps/scripts/tests/form-security-roles.test.js@@ -19,7 +19,10 @@const test = require('node:test');const assert = require('node:assert');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');const ROLE_DISPATCHER = 'dddddddd-dddd-dddd-dddd-dddddddddddd';diff --git a/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.jsindex f66a15459..8d4c88d5e 100644--- a/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js@@ -6,7 +6,10 @@const test = require('node:test');const assert = require('node:assert');const ai = require('../lib/artifact-intent.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { createHarness, seedForm, verifyForms, clone, NOTES_CLASS_ID, SUBGRID_CLASS_ID, VIEW_ID } = require('./helpers/form-store-harness.js');const TASK = 'new_ticket_new_task';diff --git a/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.jsindex 398d5b858..4b8c59686 100644--- a/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js@@ -5,7 +5,10 @@const test = require('node:test');const assert = require('node:assert');const ai = require('../lib/artifact-intent.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { renderFormWireframe } = require('../lib/form-preview.js');const { createHarness, seedForm, verifyForms, sectionXml, collapseEmptyRows, clone, NOTES_CLASS_ID, DEFAULT_ATTRIBUTES } = require('./helpers/form-store-harness.js');diff --git a/plugins/model-apps/scripts/tests/genpage-worker-output.test.js b/plugins/model-apps/scripts/tests/genpage-worker-output.test.jsindex 3a1af7bce..147959d66 100644--- a/plugins/model-apps/scripts/tests/genpage-worker-output.test.js+++ b/plugins/model-apps/scripts/tests/genpage-worker-output.test.js@@ -74,6 +74,33 @@ test('validatePageOutput accepts a complete TSX module', () => {assert.deepEqual(result.problems, []);});+// A page whose default export is a generic arrow — `<T,>`, a constraint or `const` before the name, as TypeScript requires in .tsx — was refused as having+// no default export, and the page was sent to the inline rewrite. The CLI is what the skill runs.+test('the CLI accepts a page whose default export is a generic arrow, and still refuses one cut off before its body', () => {+ const { spawnSync } = require('node:child_process');+ const script = path.join(__dirname, '..', 'genpage-worker-output.js');+ const run = (code) => spawnSync(process.execPath, [script, '--file', write(code)], { encoding: 'utf8' });+ for (const code of [+ 'type Props<T> = { items: T[] };\nexport default <T,>(props: Props<T>) => {\n return <div>{props.items.length}</div>;\n};\n',+ 'export default <T extends object>(props: T) => <div>ok</div>;\n',+ 'export default <const T,>(props: T): JSX.Element => <div>ok</div>;\n',+ 'export default async <T,>(props: T) => {\n await Promise.resolve(props);\n return null;\n};\n',+ // A return type is read to its end: a type named `module` is a name, and the arrow follows it.+ 'type module<T> = Promise<T>;\nexport default async <T,>(p: T): module<T> => p;\n',+ ]) {+ const accepted = run(code);+ assert.equal(accepted.status, 0, accepted.stdout);+ assert.deepEqual(JSON.parse(accepted.stdout).problems, [], code);+ }+ // Cut off after the parameter list, after a return type, and after a return type that is a function type (its `=>` is no arrow); an element; an arrow with no body.+ for (const code of ['export default <T,>(props: { items: T[] })', 'export default <T,>(props: T): JSX.Element', 'export default <T>(props: T) => <div>ok</div>;\n',+ 'export default <T,>(p: T): (x: T) => T', 'export default <T,>() => ;\n']) {+ const refused = run(code);+ assert.equal(refused.status, 3, code);+ assert.match(JSON.parse(refused.stdout).problems.join('\n'), /no complete default export/, code);+ }+});+// The skill runs the CLI and acts on its exit code: 0 accepts the worker's file, 3 sends the page to// the inline fallback. A missing or empty file is output that failed, never a pass.test('the CLI accepts with exit 0 and sends a failed page to the fallback with exit 3', () => {diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.jsindex 70edfce0a..80747a1dc 100644--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js@@ -23,9 +23,12 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const { scanHaltSites, scanBareErrors, haltSitesOf } = require('./helpers/halt-sites.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');const {- runSdkBuild, haltOnUnpublishedAppHeader, acquireAppPagesLease, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt,+ runSdkBuild: runSdkBuildInPlace, haltOnUnpublishedAppHeader, acquireAppPagesLease, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt,} = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { BuildHalt, makeRunner, requireSuccessfulPush, findExistingTable, resolveLanguageCode, checkLocalizedLabelLanguages } = require('../lib/entity-provision.js');const { buildModelApp, isTransientHalt } = require('../build-model-app.js');const { SdkError, ConnectionError, createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');@@ -59,6 +62,10 @@ const POLICY = {'relationship-name-taken': { kinds: ['never'], via: 'entity-provision.test.js' },'view-filter-label-unresolved': { kinds: ['by-failure'], via: 'view-filter-labels.test.js' },'pages-locked': { kinds: ['never'] },+ // The build lease (lib/app-operation-lease.js): another build of the app holds the workspace, or a lease handed to an apply is not a live one for it.+ // Running the phases again releases neither, and the refusal quotes the lock's path, which holds the maker's folder.+ 'build-locked': { kinds: ['never'] },+ 'build-lease-invalid': { kinds: ['never'] },'app-header-unpublished': { kinds: ['never'] },'app-copy-unpushed-edits': { kinds: ['never'] },'sitemap-removal-unapproved': { kinds: ['never'] },@@ -367,6 +374,17 @@ const ROWS = {dirs.push(path.dirname(workspace));return haltOf(() => acquireAppPagesLease(workspace, 'contoso_app')).finally(() => held.release());},+ // Raised by the real entries: a second apply of the app while a first holds its lease, in a folder whose name reads as a transient error; and an+ // apply handed a lease that is no lease — the label itself.+ 'build-locked': async () => {+ const workspace = path.join(tempDir('halt-policy-build'), LABEL);+ let halt;+ await buildModelApp(loopSpec(), { apply: true, workspaceDir: workspace, retryDelayMs: 0 }, {+ runBuild: async (s, o) => { halt = await haltOf(() => runSdkBuild(s, { ...o, buildLease: undefined, phases: [] })); return { ok: true, dryRun: false, created: {} }; },+ });+ return halt;+ },+ 'build-lease-invalid': () => haltOf(() => runSdkBuild(loopSpec(), { apply: true, workspaceDir: path.join(tempDir('halt-policy-build'), LABEL), buildLease: LABEL, phases: [] })),'language-not-provisioned': () => haltOf(() => resolveLanguageCode({ spec: {}, languageCode: 1031, provisionedLanguages: async () => [1033] })),'localized-label-language-not-provisioned': () => haltOf(() => checkLocalizedLabelLanguages({ entities: [{ schemaName: LABEL, displayName: { 1033: 'Name', 3082: 'Nombre' }, columns: [] }] }, async () => [1033])),'table-probe-inconclusive': ({ failure }) => haltOf(() => findExistingTable({ dataverse: { get: async () => { throw failure || Object.assign(new Error('bad request'), { statusCode: 400 }); } } }, LABEL, { hasLocalizedLabels: true, attempts: 1 })),diff --git a/plugins/model-apps/scripts/tests/helpers/build-command-harness.js b/plugins/model-apps/scripts/tests/helpers/build-command-harness.jsnew file mode 100644index 000000000..39ad83831--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/build-command-harness.js@@ -0,0 +1,89 @@+'use strict';+// The build command (build-model-app.js main), loaded over its real modules — the build lease's included — with doubles for what reaches an+// environment or the SDK (helpers/cli-harness.js): the auth check, the language read, the SDK's factory and its HTTP client, the journal, the+// engine, the verify and the baseline writer.+//+// Each double is handed `held()`, which answers whether the app's build lock is on disk right now. What the command prints goes through the real+// printer (emitResult), whose process exit is the harness's: `printed` says what it printed and whether the lock was still there at that moment.+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./temp-dirs.js');+const { loadCli } = require('./cli-harness.js');+const { sha256 } = require('../../lib/hash.js');+const realEntityProvision = require('../../lib/entity-provision.js');+const realSdkBuild = require('../../lib/sdk-build.js');+const realBaseline = require('../../lib/deployed-baseline.js');++const SCRIPTS = path.join(__dirname, '..', '..');+const ENV = 'https://contoso.crm.dynamics.com';++// An app folder holding `spec`, and the workspace the command makes beside it. `lock` is the app's build lock, named here the way the lease names it+// (its app unique name, lower-cased, hashed) rather than asked of the lease, so that a test using it runs on a build that has no lease at all.+function appFolder(spec) {+ const appDir = path.join(makeTempDir('build-command-'), 'app');+ fs.mkdirSync(appDir, { recursive: true });+ const specPath = path.join(appDir, 'app-spec.json');+ fs.writeFileSync(specPath, JSON.stringify(spec));+ const workspaceDir = path.join(appDir, '.maker-workspace');+ const app = realSdkBuild.appUniqueName(spec);+ return { appDir, specPath, workspaceDir, lock: path.join(workspaceDir, `app-build.${sha256(app.toLowerCase())}.lock`) };+}++// The command for `folder`'s spec, with `--apply` and `argv`, and these doubles — each optional, each handed `held` first:+// auth(held) what the auth check answers (else `{ ok: true }`);+// language(held) the authoring language (else 1033);+// makeSdk(held) called as the SDK is made; it may throw;+// openJournal(held) called as the journal is opened (the real one is opened after it); it may throw;+// engine(held, opts) the engine (runSdkBuild) — `opts` is what buildModelApp hands it — and what it answers (else a success);+// verify(held) the inline verify (else a pass);+// writeBaseline(held) called as the baseline is written (the real one is written after it); it may throw.+// `calls` lists, in order, which doubles ran.+function command(folder, { argv = [], auth, language, makeSdk, openJournal, engine, verify, writeBaseline } = {}) {+ const held = () => fs.existsSync(folder.lock);+ const authCli = loadCli(path.join(SCRIPTS, 'lib', 'dataverse-auth.js'));+ const printed = { at: null, ok: null, heldThen: null };+ const calls = [];+ const note = (what) => { calls.push(what); return held(); };+ const sdk = { initWorkspace: async () => {}, queryRecords: async () => [] };+ const requires = {+ './lib/dataverse-auth.js': {+ ...authCli.exports,+ preflightAuth: async () => { note('auth'); return auth ? auth(held) : { ok: true }; },+ emitResult: (ok, payload) => { printed.ok = ok; printed.heldThen = held(); printed.at = calls.length; authCli.exports.emitResult(ok, payload); },+ },+ './lib/entity-provision.js': { ...realEntityProvision, resolveAuthoringLanguage: async () => { note('language'); return language ? language(held) : 1033; } },+ './lib/sdk-http-client.js': { createAzHttpClient: () => ({}), SQL_DEADLOCK_VICTIM: /Sql Number: 1205/ },+ './lib/maker-sdk.js': {+ createNodeWorkspaceStorage: (dir) => ({ dir }),+ createMakerSdk: () => { note('sdk'); if (makeSdk) makeSdk(held); return sdk; },+ },+ './lib/sdk-build.js': { ...realSdkBuild, runSdkBuild: async (s, o) => { note('engine'); return engine ? engine(held, o) : { ok: true, dryRun: false, created: {} }; } },+ './lib/genpage-sdk.js': { ...require('../../lib/genpage-sdk.js'), makeGenpageSdk: () => ({ dispose: async () => ({ left: [] }) }) },+ './lib/verify-spec.js': { ...require('../../lib/verify-spec.js'), verifySpec: async () => { note('verify'); return verify ? verify(held) : { ok: true, checks: [], missing: [] }; } },+ './lib/deployed-baseline.js': { ...realBaseline, writeBaseline: (...a) => { note('baseline'); if (writeBaseline) writeBaseline(held); return realBaseline.writeBaseline(...a); } },+ };+ if (openJournal) {+ const realJournal = require('../../lib/build-journal.js');+ requires['./lib/build-journal.js'] = { ...realJournal, openJournal: (...a) => { note('journal'); openJournal(held); return realJournal.openJournal(...a); } };+ }+ const cli = loadCli(path.join(SCRIPTS, 'build-model-app.js'), {+ argv: ['--env', ENV, '--spec', `@${folder.specPath}`, '--apply', ...argv],+ env: { PATH: path.dirname(process.execPath), POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },+ requires,+ });+ return { cli, authCli, printed, calls, held };+}++// What main() does with its outcome: a printed result ends the process (the harness's exit throws, with its code); an error it throws goes to+// main().catch, which prints it the same way — the harness has no main().catch, so the error itself is the rejection, and `heldThen` says whether+// the lock was still there when it came.+async function settle(run) {+ try {+ await run.cli.main();+ return { returned: true };+ } catch (e) {+ return e && e.exitCode !== undefined ? { exitCode: e.exitCode } : { thrown: e, heldThen: run.held() };+ }+}++module.exports = { appFolder, command, settle, ENV };diff --git a/plugins/model-apps/scripts/tests/helpers/case-sensitive-fs.js b/plugins/model-apps/scripts/tests/helpers/case-sensitive-fs.jsnew file mode 100644index 000000000..cd9942fbe--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/case-sensitive-fs.js@@ -0,0 +1,62 @@+'use strict';+// One real folder that behaves as a case-sensitive one, on any file system, for as long as a test needs it.+//+// WHY. Whether two spellings of one app's name lock each other out depends on whether the file system folds case: on Windows and on a default macOS+// volume `pages-Contoso_App.lock` and `pages-contoso_app.lock` are one file, on Linux (and on a case-sensitive Windows folder or macOS volume) they+// are two. A test that should prove what happens on the second kind must not depend on the machine it runs on, so this stores every name directly+// inside `root` under an escaped name in which an upper-case letter is `^` and that letter in lower case: two spellings that differ only in case are+// then two files on every file system, and a name in lower case alone is stored as it is.+//+// It works by replacing, on the one `fs` object every module shares, the functions the lease code calls with a path (and readdirSync, which answers+// the names unescaped); a call about any other path, and a call with a descriptor, goes through untouched. `restore()` puts the functions back.+// Nothing here is used by the plugin itself.+const fs = require('node:fs');+const path = require('node:path');++const PATH_FUNCTIONS = ['readFileSync', 'writeFileSync', 'appendFileSync', 'statSync', 'lstatSync', 'openSync', 'rmSync', 'unlinkSync', 'readlinkSync', 'existsSync', 'mkdirSync'];++// An upper-case letter is stored as `^` and the letter in lower case. A name that is already stored that way has no upper-case letter left, so storing it+// again changes nothing — which matters, because Node's own fs functions call one another through the same object (writeFileSync calls openSync), and+// a name would otherwise be escaped twice. The tests name no file with a `^` in it.+const escapeName = (name) => name.replace(/[A-Z]/g, (c) => `^${c.toLowerCase()}`);+const unescapeName = (name) => name.replace(/\^([a-z])/g, (_, c) => c.toUpperCase());++function caseSensitiveFolder(root) {+ const rootPath = path.resolve(root);+ const sameFolder = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);+ const inRoot = (p) => typeof p === 'string' && sameFolder(path.dirname(path.resolve(p)), rootPath);+ const map = (p) => (inRoot(p) ? path.join(rootPath, escapeName(path.basename(path.resolve(p)))) : p);+ const saved = new Map();+ for (const name of PATH_FUNCTIONS) {+ const original = fs[name];+ saved.set(name, original);+ fs[name] = function mapped(target, ...rest) { return original.call(fs, map(target), ...rest); };+ }+ const readdir = fs.readdirSync;+ saved.set('readdirSync', readdir);+ fs.readdirSync = function mappedReaddir(target, ...rest) {+ const names = readdir.call(fs, target, ...rest);+ return typeof target === 'string' && sameFolder(path.resolve(target), rootPath) && names.every((n) => typeof n === 'string') ? names.map(unescapeName) : names;+ };+ let restored = false;+ return {+ restore() {+ if (restored) return;+ restored = true;+ for (const [name, original] of saved) fs[name] = original;+ },+ };+}++// Whether the folder `dir` (which must exist and be empty of `case-probe-*`) already tells two spellings apart: on Linux, yes.+function foldsCase(dir) {+ const lower = path.join(dir, 'case-probe-a');+ fs.writeFileSync(lower, '');+ try {+ return fs.existsSync(path.join(dir, 'case-probe-A'));+ } finally {+ fs.rmSync(lower, { force: true });+ }+}++module.exports = { caseSensitiveFolder, foldsCase };diff --git a/plugins/model-apps/scripts/tests/helpers/killed-build-locks.js b/plugins/model-apps/scripts/tests/helpers/killed-build-locks.jsnew file mode 100644index 000000000..a52c8323f--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/killed-build-locks.js@@ -0,0 +1,33 @@+'use strict';+// What a killed build leaves of its locks, for a test that "kills" a build by leaving it unsettled in the test's own process.+//+// A test of what a killed build leaves behind (SIGKILL, "End task", an agent's timeout) can run the build in its own process and leave it unsettled+// — a request that never answers, and nothing of the run happens after that moment — and then run the next build there, as a new process would.+// A real kill also ENDS the process: the locks the build held (lib/app-operation-lease.js — the build lock, and in the pages phase the two pages+// locks) stay in the workspace under its pid, and a later build takes them over once that pid is gone (lib/process-owner.js). In one process the pid+// is this one, which runs, so the next build would be refused as a second concurrent build — rightly, for a build that is still running. This makes+// the locks say what a real kill leaves: each lock this process holds in the workspace is handed to a process that has ended. Nothing else changes.+const fs = require('node:fs');+const path = require('node:path');+const { ownerStamp } = require('../../lib/process-owner.js');+const { deadPid } = require('./kill-target-client.js');++const LOCK = /^(?:app-build\.[0-9a-f]{64}|app-pages\.[0-9a-f]{64}|pages-.+)\.lock$/;++// Answers { pid, locks }: the pid the locks now name, and the names of the locks handed to it.+function leaveLocksOfKilledBuild(workspaceDir) {+ const gone = deadPid();+ const locks = [];+ for (const name of fs.readdirSync(workspaceDir).sort()) {+ if (!LOCK.test(name)) continue;+ const file = path.join(workspaceDir, name);+ let held;+ try { held = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }+ if (!held || held.pid !== process.pid) continue;+ fs.writeFileSync(file, JSON.stringify({ ...ownerStamp({ pid: gone }), rnd: held.rnd }));+ locks.push(name);+ }+ return { pid: gone, locks };+}++module.exports = { leaveLocksOfKilledBuild };diff --git a/plugins/model-apps/scripts/tests/helpers/legacy-pages-lease.js b/plugins/model-apps/scripts/tests/helpers/legacy-pages-lease.jsnew file mode 100644index 000000000..1ffe62d82--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/legacy-pages-lease.js@@ -0,0 +1,28 @@+'use strict';+// The pages lock exactly as model-apps 2.17.0 and 2.18.0 take it: ONE file, `pages-<app unique name, unsafe characters as _>.lock`, spelled as the+// app's name is spelled. A build of those releases is still out there while makers upgrade, and the pages lock of this release must keep it out of the+// pages phase — and be kept out by it — when both spell the app the same way. This is that release's function, kept verbatim (only the requires+// changed), so the tests meet the protocol an old build really follows rather than a reading of it.+const path = require('node:path');+const { acquireLease, releaseLease } = require('../../lib/apply-snapshot-store.js');+const { ownerStamp, ownerState, describeOwner } = require('../../lib/process-owner.js');+const { BuildHalt } = require('../../lib/entity-provision.js');+const { RETRY } = require('../../lib/retry-policy.js');++function acquireLegacyPagesLease(wsDir, appUnique, deps = {}) {+ const now = deps.now || (() => Date.now());+ const file = `pages-${String(appUnique).replace(/[^A-Za-z0-9_-]/g, '_')}.lock`;+ const lockPath = path.join(wsDir, file);+ const lease = acquireLease(wsDir, { file, now, stamp: ownerStamp({ ...deps.owner, now }), isStale: (held) => ownerState(held, deps.owner).state === 'gone' });+ if (!lease.ok) {+ if (lease.error) throw lease.error;+ const unreleased = lease.stale ? ` The build that held it is no longer running, but its lock could not be released: ${lease.reason}.` : '';+ throw new BuildHalt(`another build is deploying pages for '${appUnique}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${lockPath} if it is stale.${unreleased}`, { phase: 'pages', code: 'pages-locked', recoverable: true, retry: RETRY.NEVER });+ }+ if (lease.reclaimed && typeof deps.warn === 'function') {+ deps.warn(`released the pages lock for '${appUnique}': the build that held it (${describeOwner(lease.previous)}) is no longer running`);+ }+ return { release: () => releaseLease(lease) };+}++module.exports = { acquireLegacyPagesLease };diff --git a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.jsindex e5871fef2..1df8ce5e7 100644--- a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js+++ b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js@@ -145,10 +145,12 @@ function createLifecycleHarness(org, root) {const throwaway = (prefix) => fs.mkdtempSync(path.join(root, prefix));// build-model-app.js: the two SDK instances its makeSdk makes — one that names the solution, and the header-less one that owns the app- // folder's workspace and recovers a form create whose answer was lost — and the deps its main() hands buildModelApp.- async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir, languageCode = 1033 } = {}) {+ // folder's workspace and recovers a form create whose answer was lost — and the deps its main() hands buildModelApp. `sdkWorkspace` is+ // where that second one keeps its copies: the build's workspace, as the CLI makes it, unless a test says otherwise — the CLI makes no SDK+ // for an apply its build lease refuses, so a second build a test starts beside a running one is given copies of its own.+ async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir, sdkWorkspace = workspace, languageCode = 1033 } = {}) {const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: spec.solution.uniqueName, languageCode });- const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? workspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode, createRecovery: 'adoptExact' });+ const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? sdkWorkspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode, createRecovery: 'adoptExact' });await provisionSdk.initWorkspace();const genpage = makeGenpageSdk(org.origin, { httpClient: client });const warnings = [];diff --git a/plugins/model-apps/scripts/tests/helpers/own-app-folder.js b/plugins/model-apps/scripts/tests/helpers/own-app-folder.jsnew file mode 100644index 000000000..9d6cbf2ac--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/own-app-folder.js@@ -0,0 +1,33 @@+'use strict';+// A folder of its own for a test's apply.+//+// An apply opens its workspace — and holds the app's build lease in it (lib/app-operation-lease.js) — in `<app folder>/.maker-workspace`, and a call+// that names no app folder and no workspace means `.`: the folder the suite runs in, which is the plugin's own, and which scripts/run-tests.js+// refuses to see a `.maker-workspace` made in. So a test that runs an apply and names neither is given a folder of its own, removed with the file's+// other temporary folders (helpers/temp-dirs.js). A call that names either keeps what it named, and a dry run, which opens no workspace and takes no+// lease, is left as it is.+//+// Which of the two it is given decides nothing else the test relies on only when it is chosen for that test:+// - inOwnFolder names an APP FOLDER, one per test file (the tests of a file run one at a time), whose workspace the build makes inside it and keeps+// nothing in but the lease, which it lets go. The build then checks that the source files the spec names (a page's `codeFile`, a web resource's+// `contentPath`) are in that folder, so it is for a spec that names none, or a test that never gets that far;+// - inOwnWorkspace names a WORKSPACE, and leaves the app folder unnamed, so the build checks no source file, as it did for such a call. A workspace+// is also where the build keeps its records (the destructive approval, the page receipts), which such a call never had, so each call is given a+// new one: no record one test's build writes is there for the next.+const { makeTempDir } = require('./temp-dirs.js');++let sharedAppDir = null;++const namesNone = (opts) => !!opts && !!opts.apply && opts.appDir === undefined && opts.workspaceDir === undefined;+function ownAppFolder(opts) {+ if (!namesNone(opts)) return opts;+ if (!sharedAppDir) sharedAppDir = makeTempDir('build-app-');+ return { ...opts, appDir: sharedAppDir };+}+const ownWorkspace = (opts) => (namesNone(opts) ? { ...opts, workspaceDir: makeTempDir('build-workspace-') } : opts);++// `runSdkBuild(spec, opts)` or `buildModelApp(spec, opts, deps)`, with its options given a folder of their own when they need one.+const inOwnFolder = (entry) => (spec, opts, ...rest) => entry(spec, ownAppFolder(opts), ...rest);+const inOwnWorkspace = (entry) => (spec, opts, ...rest) => entry(spec, ownWorkspace(opts), ...rest);++module.exports = { ownAppFolder, ownWorkspace, inOwnFolder, inOwnWorkspace };diff --git a/plugins/model-apps/scripts/tests/journal-eval.test.js b/plugins/model-apps/scripts/tests/journal-eval.test.jsindex 3a58f4a34..9dd59729a 100644--- a/plugins/model-apps/scripts/tests/journal-eval.test.js+++ b/plugins/model-apps/scripts/tests/journal-eval.test.js@@ -5,7 +5,10 @@const { test } = require('node:test');const fs = require('node:fs');const path = require('node:path');-const { buildModelApp } = require('../build-model-app.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+const buildModelApp = inOwnFolder(buildModelAppInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');const { assertGolden } = require('./helpers/golden.js');diff --git a/plugins/model-apps/scripts/tests/list-custom-apis.test.js b/plugins/model-apps/scripts/tests/list-custom-apis.test.jsindex 117385c98..2df04ed54 100644--- a/plugins/model-apps/scripts/tests/list-custom-apis.test.js+++ b/plugins/model-apps/scripts/tests/list-custom-apis.test.js@@ -94,6 +94,8 @@ test('buildCustomApiFilter includes Global plus the page tables, escaping quotesassert.match(escaped, /boundentitylogicalname eq 'o''brien'/);});+// The kind and lookup maps are null-prototype objects (a defence, lib/own-keys.js — Dataverse requires a parameter's name to begin with a+// letter, so none is called `__proto__`), so the assertions below compare their entries: `{ ...map }`.test('parameterKindsFromRows maps one API\'s expanded params and drops unknown types', () => {// Rows arrive inline via $expand — each element has uniquename + type, but no parent id.const kinds = parameterKindsFromRows([@@ -102,24 +104,24 @@ test('parameterKindsFromRows maps one API\'s expanded params and drops unknown t{ uniquename: 'Mystery', type: 999 }, // unknown → dropped{ uniquename: null, type: 10 }, // no name → dropped]);- assert.deepEqual(kinds, { Comment: 'String', Amount: 'Decimal' });+ assert.deepEqual({ ...kinds }, { Comment: 'String', Amount: 'Decimal' });});test('parameterKindsFromRows tolerates missing/empty input', () => {- assert.deepEqual(parameterKindsFromRows(undefined), {});- assert.deepEqual(parameterKindsFromRows([]), {});+ assert.deepEqual({ ...parameterKindsFromRows(undefined) }, {});+ assert.deepEqual({ ...parameterKindsFromRows([]) }, {});});test('lookup request parameters remain absent from the declared primitive kind map', () => {- assert.deepEqual(parameterKindsFromRows([+ assert.deepEqual({ ...parameterKindsFromRows([{ uniquename: 'Ref', type: 5 },{ uniquename: 'Note', type: 10 },- ]), { Note: 'String' });+ ]) }, { Note: 'String' });});test('every emitted declared kind belongs to the ten supported primitive kinds', () => {const rows = Array.from({ length: 13 }, (_, type) => ({ uniquename: `Parameter${type}`, type }));- assert.deepEqual(parameterKindsFromRows(rows), {+ assert.deepEqual({ ...parameterKindsFromRows(rows) }, {Parameter0: 'Boolean',Parameter1: 'DateTime',Parameter2: 'Decimal',@@ -169,11 +171,11 @@ test('toCustomApiEntry retains lookup names, optionalness and table hints outsidbindingtype: 0,CustomAPIRequestParameters: rows,}, parameterKindsFromRows(rows));- assert.deepEqual(entry.lookupParameters, {+ assert.deepEqual({ ...entry.lookupParameters }, {Ref: { isOptional: false, logicalEntityName: 'account' },Fallback: { isOptional: true },});- assert.deepEqual(entry.parameterKinds, { Note: 'String' });+ assert.deepEqual({ ...entry.parameterKinds }, { Note: 'String' });});// The child runs the real CLI, argument parser, feature gate and Dataverse request implementation.diff --git a/plugins/model-apps/scripts/tests/lookup-label-default.test.js b/plugins/model-apps/scripts/tests/lookup-label-default.test.jsindex bb885c505..402bf7555 100644--- a/plugins/model-apps/scripts/tests/lookup-label-default.test.js+++ b/plugins/model-apps/scripts/tests/lookup-label-default.test.js@@ -1238,7 +1238,10 @@ test('REAL BUNDLE (ADO 6691205 rebuild): a lookup the form holds twice with no o// ── 7. the whole engine: data-model repair, then the existing form ────────────────────────────────-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');// An existing app whose `contoso_task` form carries the lookup's cell, labelled `cellLabel`, rebuilt by the wholediff --git a/plugins/model-apps/scripts/tests/output-token-forms.test.js b/plugins/model-apps/scripts/tests/output-token-forms.test.jsindex c1b7ce0b4..f05890339 100644--- a/plugins/model-apps/scripts/tests/output-token-forms.test.js+++ b/plugins/model-apps/scripts/tests/output-token-forms.test.js@@ -193,10 +193,13 @@ test('a token PERCENT-ENCODED (upper- or lower-case hex) or spelled with HTML ENassert.equal(redactTokens(`plain ${SPECIAL} end`, [SPECIAL]), `plain ${MARK} end`, 'and the token as it is, as before');});-test('spellingsOf is the list of the other spellings taken out: base64 of the token, standard and URL-safe, at each alignment; percent and HTML spellings only where they differ — a JWT has none; nothing shorter than the floor', () => {+test('spellingsOf is the list of the other spellings taken out: base64 of the token and of each of its parts of 24 characters or more, standard and URL-safe, at each alignment; percent and HTML spellings only where they differ — a JWT has none; nothing shorter than the floor', () => {const { spellingsOf } = redaction;const jwt = spellingsOf(TOKEN);- assert.deepEqual([...jwt].sort(), [...new Set(BASE64)].sort(), 'what is spelled the same whatever stands around the token, at each of the three alignments, in both alphabets — and nothing else: a JWT is base64url and dots');+ const plain = redaction.needlesOf(TOKEN);+ const expected = [...new Set(plain.flatMap((needle) => [...base64Of(needle, 'base64'), ...base64Of(needle, 'base64url')]))].filter((spelling) => spelling.length >= FLOOR && !plain.includes(spelling));+ assert.deepEqual([...jwt].sort(), expected.sort(), 'what is spelled the same whatever stands around the token or one of its parts, at each of the three alignments, in both alphabets — and nothing else: a JWT is base64url and dots');+ for (const part of PARTS) assert.ok(base64Of(part, 'base64').every((spelling) => jwt.includes(spelling)), `the base64 of ${part} at each alignment`);assert.ok(jwt.every((spelling) => spelling.length >= FLOOR));const special = spellingsOf(SPECIAL);const upper = encodeURIComponent(SPECIAL);@@ -210,6 +213,110 @@ test('spellingsOf is the list of the other spellings taken out: base64 of the toassert.deepEqual(redaction.needlesOf(TOKEN), [TOKEN, PARTS[2], PARTS[1], PARTS[0]], 'and the list the Dataverse client scrubs with is what it was');});+// A token whose parts are 24, 25 and 26 characters long: the three lengths a part's base64 can end with — no fringe and no padding; a character that also holds bits of what follows, and `==`; and one and `=`. The second+// ends with `y`, whose last two bits make the character after the part's own ones `Q`.+const RESIDUE_PARTS = ['residueHeaderPartNotReal', 'residuePayloadNotARealKey', 'residueSignatureNotRealKey'];+const RESIDUE_TOKEN = RESIDUE_PARTS.join('.');++test('the BASE64 of each PART of a token — 24 characters or more, standard and URL-safe, at each of the three byte alignments — is taken out: a text that is exactly the characters made of the part\'s own bits becomes the marker, and JSON around it is JSON still', () => {+ assert.deepEqual(RESIDUE_PARTS.map((part) => part.length % 3), [0, 1, 2]);+ const failures = [];+ for (const [token, parts] of [[TOKEN, PARTS], [RESIDUE_TOKEN, RESIDUE_PARTS]]) {+ for (const part of parts) {+ for (const alphabet of ['base64', 'base64url']) {+ base64Of(part, alphabet).forEach((spelling, offset) => {+ const where = `${part}, ${alphabet}, alignment ${offset}`;+ if (spelling.length < FLOOR) failures.push(`${where}: a spelling shorter than the floor`);+ if (redactTokens(spelling, [token]) !== MARK) failures.push(`${where}: ${redactTokens(spelling, [token])}`);+ const json = redactTokens(JSON.stringify({ err: spelling, ok: false }), [token]);+ try {+ if (JSON.parse(json).err !== MARK) failures.push(`${where}: in JSON ${json}`);+ } catch {+ failures.push(`${where}: no JSON ${json}`);+ }+ if (redactTokens(`Rejected ${spelling} for this write`, [token]) !== `Rejected ${MARK} for this write`) failures.push(`${where}: in a sentence`);+ });+ }+ }+ }+ assert.deepEqual(failures, []);+});++test('a COMPLETE base64 encoding of a part — alone, and inside a longer value at each alignment, standard and URL-safe — loses the characters made of the part\'s own bits, and only those: the characters that also hold bits of what stands around it, the padding and the rest of the value stay', () => {+ const failures = [];+ for (const [token, parts] of [[TOKEN, PARTS], [RESIDUE_TOKEN, RESIDUE_PARTS]]) {+ const spellings = [...new Set(parts.flatMap((part) => [...base64Of(part, 'base64'), ...base64Of(part, 'base64url')]))];+ for (const part of parts) {+ for (const alphabet of ['base64', 'base64url']) {+ for (const before of ['', 'B', 'Be', 'Bearer ']) {+ for (const after of ['', 'x', '\r\n', ' and the rest of the header']) {+ const encoded = Buffer.from(`${before}${part}${after}`).toString(alphabet);+ // Where the part's own characters stand in it, found with the spelling that is the same whatever stands around the part (base64Of), not with the module's arithmetic.+ const own = base64Of(part, alphabet)[before.length % 3];+ const at = encoded.indexOf(own);+ const expected = `${encoded.slice(0, at)}${MARK}${encoded.slice(at + own.length)}`;+ const where = `${part}, ${alphabet}, ${JSON.stringify(before)} + part + ${JSON.stringify(after)}`;+ if (at < 0) failures.push(`${where}: the spelling is not in the encoding`);+ const alone = redactTokens(encoded, [token]);+ if (alone !== expected) failures.push(`${where}: ${alone} is not ${expected}`);+ const inBlob = redactTokens(`blob ${encoded} end`, [token]);+ if (inBlob !== `blob ${expected} end`) failures.push(`${where}: in a blob ${inBlob}`);+ const json = redactTokens(JSON.stringify({ blob: encoded, ok: false }), [token]);+ try {+ if (JSON.parse(json).blob !== expected) failures.push(`${where}: in JSON ${json}`);+ } catch {+ failures.push(`${where}: no JSON ${json}`);+ }+ if (piecesIn(inBlob, spellings).length > 0) failures.push(`${where}: a piece of a spelling is left in ${inBlob}`);+ }+ }+ }+ }+ }+ assert.deepEqual(failures, []);+ // The fringe as it is written: a 25-character part that ends with `y`, encoded alone, keeps the character after its own ones and the padding.+ assert.equal(redactTokens(Buffer.from(RESIDUE_PARTS[1]).toString('base64'), [RESIDUE_TOKEN]), `${MARK}Q==`);+ // A whole token's complete encoding the same way: its own characters are the marker, its fringe and padding stay.+ const whole = Buffer.from(RESIDUE_TOKEN).toString('base64');+ const own = base64Of(RESIDUE_TOKEN, 'base64')[0];+ assert.equal(whole.indexOf(own), 0);+ assert.ok(whole.length > own.length, 'the encoding of a token of 77 characters has a fringe and padding');+ assert.equal(redactTokens(whole, [RESIDUE_TOKEN]), `${MARK}${whole.slice(own.length)}`);+ assert.equal(redactTokens(own, [RESIDUE_TOKEN]), MARK, 'a text that is exactly its own characters is one marker');+});++test('what the base64 of a part does NOT reach: a part shorter than 24 characters has no spelling, a piece of a token that is not a whole part is not read in base64, a token of 18 characters keeps the one spelling it has, and the Dataverse client still scrubs the token and its parts only', () => {+ const { spellingsOf, needlesOf } = redaction;+ // A part of 23 characters is no needle, so its base64 is none either — though that base64 is longer than the floor.+ const short = 'shortPartIsNotANeedle23';+ assert.equal(short.length, FLOOR - 1);+ const withShort = `${short}.${RESIDUE_PARTS[2]}`;+ assert.ok(!needlesOf(withShort).includes(short));+ const shortSpellings = [...base64Of(short, 'base64'), ...base64Of(short, 'base64url')];+ assert.ok(shortSpellings.every((spelling) => spelling.length >= FLOOR && !spellingsOf(withShort).includes(spelling)), 'no spelling of the short part');+ const encodedShort = Buffer.from(short).toString('base64');+ assert.equal(redactTokens(`blob ${encodedShort} end`, [withShort]), `blob ${encodedShort} end`);+ // Thirty characters from the middle of a part: not a whole part, so its base64 is ordinary data.+ const slice = PARTS[1].slice(4, 34);+ for (const alphabet of ['base64', 'base64url']) {+ const encoded = Buffer.from(slice).toString(alphabet);+ assert.equal(redactTokens(encoded, [TOKEN]), encoded, alphabet);+ assert.equal(redactTokens(`blob ${encoded} end`, [TOKEN], { edges: true }), `blob ${encoded} end`, alphabet);+ }+ // A token of 18 characters: its base64 at the first alignment is 24 characters, and it stays a spelling (the floor is the spelling's length, not the token's).+ const eighteen = 'eighteenCharsTokn1';+ assert.equal(eighteen.length, 18);+ const first = base64Of(eighteen, 'base64')[0];+ assert.equal(first.length, FLOOR);+ assert.ok(spellingsOf(eighteen).includes(first));+ assert.equal(redactTokens(`x ${first} y`, [eighteen]), `x ${MARK} y`);+ // The client's scrubber reads the token and its parts, as it did: the base64 of a part stays in what it scrubs.+ const { scrub } = require('../lib/sdk-http-client.js');+ const partBase64 = base64Of(PARTS[1], 'base64')[0];+ assert.ok(scrub(`refused: ${partBase64}`, TOKEN).includes(partBase64), 'the client scrubs with needlesOf, which is what it was');+ assert.deepEqual(needlesOf(RESIDUE_TOKEN), [RESIDUE_TOKEN, RESIDUE_PARTS[2], RESIDUE_PARTS[1], RESIDUE_PARTS[0]]);+});+// ── A token a formatter cut short ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────// A string util.inspect cuts after `kept` characters of the token: it prints the first 10,000 characters of a string (https://nodejs.org/api/util.html#utilinspectobject-options, `maxStringLength`).@@ -608,4 +715,48 @@ test('a write the stream REFUSES at once — an encoding it does not know, a chuguardStream(eager, (chunk, options) => redactTokens(chunk, [token], { edges: true, ...options }));eager.write(head, () => eager.write(tail));assert.equal(chunks.join(''), expected);+});+test('a write the stream REFUSES after a write made inside it was refused too leaves the memory of the last write the stream took: the write after both is what it would have been, JSON again; a write taken inside a refused one keeps the memory it made', () => {+ const token = SPLIT_ESCAPES[0].token;+ const head = `{"error":"${'A'.repeat(24)}\\`;+ const tail = `/${'B'.repeat(27)}"}`;+ const guarded = (write) => {+ const stream = { chunks: [], write };+ guardStream(stream, (chunk, options) => redactTokens(chunk, [token], { edges: true, ...options }));+ return stream;+ };+ const control = guarded(function write(chunk) { this.chunks.push(chunk); return true; });+ control.write(head);+ control.write(tail);+ const expected = control.chunks.join('');+ assert.deepEqual(JSON.parse(expected), { error: `${MARK}/${MARK}` });+ // The stream calls the callback of a write at once, the callback writes again and that write is refused; then the stream refuses the outer write as well. Neither wrote anything.+ const outer = new TypeError('refused: the outer write');+ const inner = new TypeError('refused: the write inside it');+ const refusing = guarded(function write(chunk, callback) {+ if (chunk === 'a nested write') throw inner;+ if (typeof callback === 'function') {+ assert.throws(() => this.write('a nested write'), (error) => error === inner, 'the write inside it is refused with the stream\'s own error');+ throw outer;+ }+ this.chunks.push(chunk);+ return true;+ });+ refusing.write(head);+ assert.throws(() => refusing.write('interleaved', () => {}), (error) => error === outer, 'the stream\'s own error');+ refusing.write(tail);+ assert.equal(refusing.chunks.join(''), expected, 'the write after both refusals reads on from the last write the stream took');+ assert.deepEqual(JSON.parse(refusing.chunks.join('')), { error: `${MARK}/${MARK}` });+ // A write the stream TAKES inside a refused one stands: what it wrote was written, and the memory it made is the one the next write reads on from.+ const taking = guarded(function write(chunk, callback) {+ if (typeof callback === 'function') {+ this.write(head);+ throw outer;+ }+ this.chunks.push(chunk);+ return true;+ });+ assert.throws(() => taking.write('interleaved', () => {}), (error) => error === outer);+ taking.write(tail);+ assert.equal(taking.chunks.join(''), expected, 'the write taken inside the refused one is the memory the next write reads on from');});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/output-token-writers.test.js b/plugins/model-apps/scripts/tests/output-token-writers.test.jsindex 1efb92770..2bda4fbca 100644--- a/plugins/model-apps/scripts/tests/output-token-writers.test.js+++ b/plugins/model-apps/scripts/tests/output-token-writers.test.js@@ -6,6 +6,8 @@ const test = require('node:test');const assert = require('node:assert');const fs = require('node:fs');const path = require('node:path');+const vm = require('node:vm');+const { spawnSync } = require('node:child_process');const bundle = require('../vendor/cds-maker-sdk.cjs');const { createMakerSdk } = require('../lib/maker-sdk.js');const { createAzHttpClient } = require('../lib/sdk-http-client.js');@@ -15,7 +17,7 @@ const { noteToken } = require('../lib/output-redaction.js');const ai = require('../lib/artifact-intent.js');const { createHarness, seedForm, NOTES_CLASS_ID } = require('./helpers/form-store-harness.js');const { scriptsMatching, productionScripts, scriptLabel, withoutComments } = require('./helpers/production-scripts.js');-const { TOKEN, SECRETS, FOLDED } = require('./helpers/synthetic-token.js');+const { TOKEN, PARTS, SECRETS, FOLDED } = require('./helpers/synthetic-token.js');const { leaksIn } = require('./helpers/token-leaks.js');const { makeTempDir } = require('./helpers/temp-dirs.js');@@ -77,6 +79,222 @@ test('lib/apply-snapshot-store.js writes the snapshot, the baseline and the recoassert.strictEqual(JSON.parse(dashboards).dashboards['Clean Overview'].id, id, 'ordinary dashboard names are unchanged');});+// ── Bytes given to a file writer ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const STARS = (secret) => '*'.repeat(secret.length);+// A text of even length (a Uint16Array is two bytes an element) with the token in it, and what a file must hold of it.+const BYTES_TEXT = `bearer ${TOKEN} end`;+const BYTES_MASKED = `bearer ${STARS(TOKEN)} end`;+// `text` as bytes inside a larger allocation of its own: six `#` stand before it and after it, which no view below covers.+function allocationOf(text) {+ const bytes = Buffer.from(text);+ const buffer = new ArrayBuffer(bytes.length + 12);+ new Uint8Array(buffer).fill(0x23);+ new Uint8Array(buffer).set(bytes, 6);+ return { buffer, offset: 6, length: bytes.length };+}+// Every kind of view Node's file writers write as raw bytes, each covering the text in the middle of its allocation.+const VIEWS = {+ Buffer: ({ buffer, offset, length }) => Buffer.from(buffer, offset, length),+ Uint8Array: ({ buffer, offset, length }) => new Uint8Array(buffer, offset, length),+ Uint16Array: ({ buffer, offset, length }) => new Uint16Array(buffer, offset, length / 2),+ DataView: ({ buffer, offset, length }) => new DataView(buffer, offset, length),+};+// The three writers, each into a file of its own in `dir`.+const WRITERS = {+ writeFileSafe: (file, data, opts) => writeFileSafe(file, data, opts),+ 'writeFileSafe exclusive': (file, data, opts) => writeFileSafe(file, data, { ...opts, exclusive: true }),+ appendFileSafe: (file, data, opts) => appendFileSafe(file, data, opts),+ writeFileAtomic: (file, data) => writeFileAtomic(file, data),+};++test('BYTES given to a file writer — a Buffer, a Uint8Array, a Uint16Array, a DataView, each a view inside a larger allocation — are written without the token: masked with as many `*`, the file as long as the view, the bytes around the view and the caller\'s memory as they were; through every writer', () => {+ const dir = makeTempDir('file-bytes-tokens-');+ const failures = [];+ for (const [kind, view] of Object.entries(VIEWS)) {+ for (const [writer, write] of Object.entries(WRITERS)) {+ const allocation = allocationOf(BYTES_TEXT);+ const before = Buffer.from(allocation.buffer).toString('latin1');+ const data = view(allocation);+ const file = path.join(dir, `${kind}-${writer.replace(/\W/g, '-')}.bin`);+ write(file, data);+ const written = fs.readFileSync(file);+ if (written.toString('latin1') !== BYTES_MASKED) failures.push(`${kind} through ${writer}: ${written.toString('latin1').slice(0, 60)}`);+ if (written.length !== data.byteLength) failures.push(`${kind} through ${writer}: ${written.length} bytes for a view of ${data.byteLength}`);+ if (Buffer.from(allocation.buffer).toString('latin1') !== before) failures.push(`${kind} through ${writer}: the caller's memory was written into`);+ }+ }+ assert.deepStrictEqual(failures, []);+ // A view from another realm (a vm context, a worker's allocation) is a view all the same.+ const { redactFileData } = require('../lib/output-redaction.js');+ const foreign = vm.runInNewContext(`new Uint8Array(${JSON.stringify([...Buffer.from(BYTES_TEXT)])})`);+ assert.strictEqual(Buffer.from(redactFileData(foreign)).toString('latin1'), BYTES_MASKED);+ const foreignClean = vm.runInNewContext('new Uint8Array([1, 2, 3])');+ assert.strictEqual(redactFileData(foreignClean), foreignClean, 'with no token: the very object');+});++test('a string a file writer DECODES — `hex`, `base64`, `base64url` — is written as its bytes without the token, the encoding left out of the masked write; one with no token is written as it was; a text in `utf8` or `latin1` is a text', () => {+ const dir = makeTempDir('file-encoded-tokens-');+ writeFileSafe(path.join(dir, 'hex.bin'), Buffer.from(`bearer ${TOKEN}`).toString('hex'), { encoding: 'hex' });+ assert.strictEqual(fs.readFileSync(path.join(dir, 'hex.bin'), 'latin1'), `bearer ${STARS(TOKEN)}`);+ appendFileSafe(path.join(dir, 'part.bin'), Buffer.from(`part ${PARTS[1]} end`).toString('base64'), { encoding: 'base64' });+ assert.strictEqual(fs.readFileSync(path.join(dir, 'part.bin'), 'latin1'), `part ${STARS(PARTS[1])} end`);+ writeFileSafe(path.join(dir, 'url.bin'), Buffer.from(`x ${TOKEN} y`).toString('base64url'), { encoding: 'BASE64URL', exclusive: true });+ assert.strictEqual(fs.readFileSync(path.join(dir, 'url.bin'), 'latin1'), `x ${STARS(TOKEN)} y`);+ // The masked bytes are handed over without the encoding, which the file system would apply to them a second time.+ const recorder = recordingFs();+ writeFileSafe(path.join(dir, 'recorded.bin'), Buffer.from(`bearer ${TOKEN}`).toString('hex'), { encoding: 'hex', fs: recorder.fs });+ const [handed] = recorder.calls.filter(([name]) => name === 'writeFileSync');+ assert.ok(Buffer.isBuffer(handed[2]) && handed.length === 3, 'bytes, and no encoding with them');+ // No token: the very string and encoding reach the file system, and the file is what an unguarded write makes.+ const clean = Buffer.from('no token in these bytes \x00\xff').toString('base64');+ writeFileSafe(path.join(dir, 'clean.bin'), clean, { encoding: 'base64' });+ fs.writeFileSync(path.join(dir, 'clean-unguarded.bin'), clean, { encoding: 'base64' });+ assert.deepStrictEqual(fs.readFileSync(path.join(dir, 'clean.bin')), fs.readFileSync(path.join(dir, 'clean-unguarded.bin')));+ writeFileSafe(path.join(dir, 'text.txt'), `bearer ${TOKEN}`, { encoding: 'latin1' });+ assert.strictEqual(fs.readFileSync(path.join(dir, 'text.txt'), 'latin1'), `bearer ${MARK}`, 'a text in another text encoding is cleaned as a text');+});++test('what does not move for bytes: bytes with no token are the very object and the same file, an empty view is written as it was, two appends are two lines, and a raw ArrayBuffer — no view — is refused by Node as it always was', () => {+ const { redactFileData } = require('../lib/output-redaction.js');+ const dir = makeTempDir('file-bytes-neighbours-');+ const plain = Buffer.from('bytes with no token');+ assert.strictEqual(redactFileData(plain), plain);+ const allocation = allocationOf('a DataView with no token in it.');+ const view = new DataView(allocation.buffer, allocation.offset, allocation.length);+ assert.strictEqual(redactFileData(view), view);+ writeFileSafe(path.join(dir, 'view.bin'), view);+ fs.writeFileSync(path.join(dir, 'view-unguarded.bin'), view);+ assert.deepStrictEqual(fs.readFileSync(path.join(dir, 'view.bin')), fs.readFileSync(path.join(dir, 'view-unguarded.bin')));+ const empty = new Uint8Array(0);+ assert.strictEqual(redactFileData(empty), empty);+ writeFileSafe(path.join(dir, 'empty.bin'), empty);+ assert.strictEqual(fs.readFileSync(path.join(dir, 'empty.bin')).length, 0);+ appendFileSafe(path.join(dir, 'log.jsonl'), Buffer.from(`${JSON.stringify({ line: 1, error: `bearer ${TOKEN}` })}\n`));+ appendFileSafe(path.join(dir, 'log.jsonl'), Buffer.from(`${JSON.stringify({ line: 2 })}\n`));+ const lines = fs.readFileSync(path.join(dir, 'log.jsonl'), 'utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line));+ assert.deepStrictEqual(lines, [{ line: 1, error: `bearer ${STARS(TOKEN)}` }, { line: 2 }], 'both lines, the first masked');+ const raw = new ArrayBuffer(4);+ assert.strictEqual(redactFileData(raw), raw, 'a raw ArrayBuffer is no view: passed on');+ assert.throws(() => appendFileSafe(path.join(dir, 'raw.bin'), raw), (error) => error.code === 'ERR_INVALID_ARG_TYPE');+ assert.ok(!fs.existsSync(path.join(dir, 'raw.bin')));+ // A piece shorter than 24 characters, in one call, is no token: each call is read alone, as a text is.+ const short = Buffer.from(`the start ${TOKEN.slice(0, 23)}`);+ assert.strictEqual(redactFileData(short), short);+ assert.strictEqual(redactFileData(TOKEN.slice(0, 23)), TOKEN.slice(0, 23));+ appendFileSafe(path.join(dir, 'short.txt'), short);+ appendFileSafe(path.join(dir, 'short.txt'), Buffer.from(TOKEN.slice(23, 40)));+ assert.strictEqual(fs.readFileSync(path.join(dir, 'short.txt'), 'latin1'), `the start ${TOKEN.slice(0, 40)}`, 'the residual: a token split between two appends, each piece shorter than 24');+});++// A file system that writes as the real one does and records every call that is given data: what the writers handed it.+function recordingFs() {+ const calls = [];+ const record = (name) => (...args) => { calls.push([name, ...args]); return fs[name](...args); };+ return { calls, fs: { ...fs, writeFileSync: record('writeFileSync'), appendFileSync: record('appendFileSync'), openSync: record('openSync'), linkSync: record('linkSync'), renameSync: record('renameSync') } };+}++test('data that cannot be checked is NOT written: a view whose bytes cannot be read (detached), and a string whose decoding fails, throw before anything is opened — the target as it was, no temporary file, nothing handed to the file system — and the error does not hold the data', () => {+ const { redactFileData } = require('../lib/output-redaction.js');+ const dir = makeTempDir('file-unchecked-');+ const target = path.join(dir, 'target.bin');+ fs.writeFileSync(target, 'as it was');+ const detached = () => {+ const view = new Uint8Array(Buffer.from(BYTES_TEXT));+ structuredClone(view.buffer, { transfer: [view.buffer] });+ return view;+ };+ for (const [writer, write] of Object.entries({ writeFileSafe, appendFileSafe })) {+ const recorder = recordingFs();+ assert.throws(() => write(target, detached(), { fs: recorder.fs }), (error) => error instanceof TypeError && /could not be checked/.test(error.message) && !error.message.includes(TOKEN), writer);+ assert.deepStrictEqual(recorder.calls, [], `${writer}: nothing reached the file system`);+ }+ assert.throws(() => writeFileAtomic(target, detached()), /could not be checked/);+ assert.strictEqual(fs.readFileSync(target, 'utf8'), 'as it was');+ assert.deepStrictEqual(fs.readdirSync(dir), ['target.bin'], 'no temporary file is left');+ // A decoding that fails once: the file system would take the original string and decode it itself — it is never given it.+ const encoded = Buffer.from(`bearer ${TOKEN}`).toString('hex');+ const realFrom = Buffer.from;+ for (const [writer, write] of Object.entries({ writeFileSafe, appendFileSafe })) {+ let failOnce = true;+ Buffer.from = function from(value, ...rest) {+ if (failOnce && value === encoded && rest[0] === 'hex') {+ failOnce = false;+ throw new RangeError('a decoding that fails');+ }+ return realFrom.call(this, value, ...rest);+ };+ const recorder = recordingFs();+ let thrown = null;+ try {+ write(target, encoded, { encoding: 'hex', fs: recorder.fs });+ } catch (error) {+ thrown = error;+ } finally {+ Buffer.from = realFrom;+ }+ assert.strictEqual(failOnce, false, `${writer}: the decoding was tried`);+ assert.deepStrictEqual(recorder.calls.filter((call) => call.includes(encoded)), [], `${writer}: a write was given the string unchecked`);+ assert.ok(thrown !== null && /could not be checked/.test(thrown.message) && !thrown.message.includes(encoded), `${writer}: ${thrown && thrown.message}`);+ assert.deepStrictEqual(recorder.calls, [], `${writer}: nothing reached the file system`);+ }+ assert.strictEqual(fs.readFileSync(target, 'utf8'), 'as it was');+ assert.deepStrictEqual(fs.readdirSync(dir), ['target.bin']);+ // Read with no fault, the same string is checked and masked.+ assert.strictEqual(redactFileData(encoded, { encoding: 'hex' }).toString('latin1'), `bearer ${STARS(TOKEN)}`);+});++test('an append that writes part of its chunk and fails: the part it wrote is of the chunk as cleaned, the error is the file system\'s, and nothing is appended again or removed', () => {+ const dir = makeTempDir('file-append-partial-');+ const target = path.join(dir, 'build-log.jsonl');+ fs.writeFileSync(target, '{"line":0}\n');+ const failure = Object.assign(new Error('the disk is full'), { code: 'ENOSPC' });+ const calls = [];+ const partial = { ...fs, appendFileSync(file, data, ...rest) { calls.push(['appendFileSync', file]); fs.appendFileSync(file, data.subarray(0, 40), ...rest); throw failure; }, unlinkSync(...args) { calls.push(['unlinkSync', ...args]); return fs.unlinkSync(...args); }, renameSync(...args) { calls.push(['renameSync', ...args]); return fs.renameSync(...args); } };+ assert.throws(() => appendFileSafe(target, Buffer.from(`{"line":1,"error":"${TOKEN}"}\n`), { fs: partial }), (error) => error === failure);+ // appendFileSafe appends to the file in the folder's REAL path (assertSafeOutputDir resolves it with realpathSync.native), so the+ // path the append is given is that one: a temp folder reached through a link (macOS's /var is /private/var) or an 8.3 short name+ // (`C:\Users\RUNNER~1\…` on a Windows runner) is not the path the test made the file under.+ const appendedTo = path.join(fs.realpathSync.native(dir), 'build-log.jsonl');+ assert.deepStrictEqual(calls, [['appendFileSync', appendedTo]], 'one append, no retry, no delete');+ const text = fs.readFileSync(target, 'latin1');+ assert.strictEqual(text, `{"line":0}\n${`{"line":1,"error":"${STARS(TOKEN)}"}\n`.slice(0, 40)}`, 'the part written is the masked chunk\'s');+});++test('a process that has obtained NO token writes every kind of data exactly as Node does: the very argument reaches the file system — an ordinary view, an empty one, a detached one, a string to decode', () => {+ const dir = makeTempDir('file-no-token-');+ const run = spawnSync(process.execPath, ['-e', `+ const fs = require('node:fs');+ const path = require('node:path');+ const { redactFileData } = require('./lib/output-redaction.js');+ const { writeFileSafe } = require('./lib/safe-fs.js');+ const dir = ${JSON.stringify(dir)};+ const detached = new Uint8Array([1, 2, 3]);+ structuredClone(detached.buffer, { transfer: [detached.buffer] });+ const cases = {+ view: [new DataView(Buffer.from('bearer ${TOKEN}').buffer, 0, 10)],+ empty: [new Uint8Array(0)],+ detached: [detached],+ encoded: [Buffer.from('bearer ${TOKEN}').toString('hex'), { encoding: 'hex' }],+ };+ const outcome = (write) => { try { write(); return 'written'; } catch (error) { return 'error ' + (error.code || error.name); } };+ const result = {};+ for (const [name, [data, opts]] of Object.entries(cases)) {+ const same = redactFileData(data, opts) === data;+ const guarded = outcome(() => writeFileSafe(path.join(dir, name + '.guarded'), data, opts));+ const unguarded = outcome(() => fs.writeFileSync(path.join(dir, name + '.unguarded'), data, opts));+ const bytes = (file) => (fs.existsSync(file) ? fs.readFileSync(file).toString('hex') : null);+ result[name] = { same, guarded, unguarded, equal: bytes(path.join(dir, name + '.guarded')) === bytes(path.join(dir, name + '.unguarded')) };+ }+ fs.writeSync(1, JSON.stringify(result));+ `], { cwd: path.resolve(__dirname, '..'), env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' }, encoding: 'utf8' });+ assert.strictEqual(run.status, 0, run.stderr);+ const result = JSON.parse(run.stdout);+ for (const [name, outcome] of Object.entries(result)) {+ assert.deepStrictEqual(outcome, { same: true, guarded: 'written', unguarded: 'written', equal: true }, name);+ }+});+// A form whose labels hold the token — as a label a maker typed could, or an answer that echoes a header — read by the SDK, which writes the form, its metadata and the manifest into the workspace: the SDK factory's storage keeps// the token out of every one of those files, and the SDK as the bundle ships it does not.test('REAL BUNDLE: a success answer that repeats the token — a form whose labels hold it — reaches no file of the SDK\'s workspace made by the factory; the bundle\'s own storage writes it', async () => {@@ -123,10 +341,10 @@ test('REAL BUNDLE: a success answer that repeats the token — a form whose labe// A call that writes or copies a file's content: `fs.writeFileSync`, `fsx.writeFileSync(fd, …)`, `fs.promises.writeFile`, `appendFileSync`, `createWriteStream`, `writeSync`, `copyFileSync`, `cpSync`.const WRITES = /\.(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|writeSync|copyFileSync|copyFile|cpSync)\s*\(/;-// The writers that clean a text first, and what makes each one so.+// The writers that clean what they write first, and what makes each one so.const GUARDED_WRITERS = {- 'lib/safe-fs.js': /redactOutput\(data\)/,- 'lib/apply-snapshot-store.js': /fs\.writeFileSync\(fd, redactOutput\(text\)\)/,+ 'lib/safe-fs.js': /redactFileData\(data, opts\)/,+ 'lib/apply-snapshot-store.js': /fs\.writeFileSync\(fd, redactFileData\(text\)\)/,};// The writers that are not guarded, and why none of them can write a token: each writes what the plugin made itself, or what a person gave it, never a word of a service's, or runs in a process that obtains no token.@@ -156,6 +374,11 @@ test('every write of file content in the plugin is a guarded writer or one of aconst file = productionScripts().find((candidate) => scriptLabel(candidate) === label);assert.match(withoutComments(fs.readFileSync(file, 'utf8')), evidence, `${label} cleans the text it writes`);}+ // The listed writers that hand data on unaltered stay so: the settings a person gave and the package handed to pac are not masked.+ for (const label of ['solution-settings.js', 'lib/private-folder.js']) {+ const file = productionScripts().find((candidate) => scriptLabel(candidate) === label);+ assert.doesNotMatch(withoutComments(fs.readFileSync(file, 'utf8')), /redactFileData/, `${label} writes its data as it is`);+ }for (const label of ['capture-fixture.js', 'generate-page-manifest.js', 'genpage-worker-output.js', 'promote-intent-pages.js', 'regenerate-verified-icons.js', 'smoke-eval.js', 'write-page-plan.js', 'lib/temp-workspace.js', 'lib/private-folder.js']) {const file = productionScripts().find((candidate) => scriptLabel(candidate) === label);assert.doesNotMatch(withoutComments(fs.readFileSync(file, 'utf8')), TOKEN_CALLS, `${label} calls nothing that obtains a token`);diff --git a/plugins/model-apps/scripts/tests/page-binding-targets-real-bundle.test.js b/plugins/model-apps/scripts/tests/page-binding-targets-real-bundle.test.jsnew file mode 100644index 000000000..3af14f077--- /dev/null+++ b/plugins/model-apps/scripts/tests/page-binding-targets-real-bundle.test.js@@ -0,0 +1,226 @@+'use strict';+// A changed-only apply checks the bindings of the pages it writes, and of no page it leaves alone. These run it through the changed-only flow itself (lib/changed-only-flow.js → build-model-app.js →+// lib/sdk-build.js) over the REAL vendored SDK, whose reads go to a stateful fake of Dataverse (helpers/fake-app-build-org.js), and the REAL page backend over a fake of the page service+// (helpers/fake-genpage-server.js), so what is asserted is what reached the wire.+//+// The app holds three pages: Alpha; Bravo, which navigates to Charlie; and Charlie, whose connector binding goes through the connection reference `contoso_msnweather`. Since the app was built, the+// environment has come to hold a reference of that name for ANOTHER connector. A changed-only apply writes the pages it changed, and makes a navigation target only when the target is absent:+// - an edit of Alpha writes Alpha alone. Charlie exists, so it is not made, and its binding is neither read nor judged — the run neither refuses nor says anything of it;+// - an edit of Charlie writes Charlie, so its binding is refused, before anything is written;+// - an edit of Alpha after Charlie was deleted in Maker makes Charlie from its spec entry, bindings and all, so it is refused too, before anything is written — though the flow's record of its last+// apply says Charlie is there.+// The real SDK reads a table's rows in two requests — the table's entity set name, then the rows:+// GET /EntityDefinitions(LogicalName='connectionreference')?$select=EntitySetName -> { "EntitySetName": "connectionreferences" }+// GET /connectionreferences?$select=connectionreferencelogicalname,connectorid,connectionid,_customconnectorid_value&$filter=connectionreferencelogicalname eq 'contoso_msnweather'+// Neither is in the fake, so the environment's references are answered here (`references`); no request that names the table is what "not read" means.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');+const { runSdkBuild, appUniqueName } = require('../lib/sdk-build.js');+const { buildModelApp } = require('../build-model-app.js');+const { validateAppSpec } = require('../lib/app-spec.js');+const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+const { annotateContentHashes } = require('../lib/content-hash.js');+const flow = require('../lib/changed-only-flow.js');+const store = require('../lib/apply-snapshot-store.js');+const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');+const { FakeGenPageServer } = require('./helpers/fake-genpage-server.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const ORG_ID = '0f0f0f0f-0000-4000-8000-000000000001';+const NAV = 'Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_charlie", data: {} });';+const SOURCES = {+ 'Alpha.tsx': "import * as React from 'react';\nexport default function Alpha() { return <div>Alpha</div>; }\n",+ 'Bravo.tsx': `import * as React from 'react';\nexport default function Bravo() { ${NAV} return <div>Bravo</div>; }\n`,+ 'Charlie.tsx': "import * as React from 'react';\nexport default function Charlie() { return <div>Charlie</div>; }\n",+};+const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };+// The reference of that name, as the environment holds it now: for another connector.+const OTHER_CONNECTOR = { connectionreferencelogicalname: 'contoso_msnweather', connectorid: '/providers/Microsoft.PowerApps/apis/shared_office365users', connectionid: 'shared-office365users-0001', _customconnectorid_value: null };++function abcSpec({ alpha = {} } = {}) {+ return {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoReview', displayName: 'Contoso Review', publisherPrefix: 'contoso' },+ app: { name: 'Binding Targets', uniqueName: 'contoso_bindingtargets' },+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],+ pages: [+ { key: 'alpha', name: 'Alpha', source: { kind: 'tsx', codeFile: 'Alpha.tsx' }, ...alpha },+ { key: 'bravo', name: 'Bravo', navigatesTo: [{ targetKey: 'charlie' }], source: { kind: 'tsx', codeFile: 'Bravo.tsx' } },+ { key: 'charlie', name: 'Charlie', source: { kind: 'tsx', codeFile: 'Charlie.tsx' }, connectorBindings: [WEATHER] },+ ],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: [{ entity: 'contoso_item', title: 'Items' }, { page: 'alpha' }, { page: 'bravo' }, { page: 'charlie' }] }] }] },+ };+}+// Alpha names Charlie's connection reference too, and states the connector the environment's reference is for: Alpha is fine, Charlie conflicts.+const SHARED_ALPHA = { connectorBindings: [{ ...WEATHER, connectorId: OTHER_CONNECTOR.connectorid, operations: [] }] };++// The app as a first build leaves it — its three pages created and in its navigation — with the changed-only baseline its flow records for it. `references` is what the environment answers for+// connection references from then on (none while the app was built); `answerReferences`, when set, answers each read of their rows instead (a refusal, say). `alpha`: what Alpha states besides its source.+async function builtApp(t, { alpha } = {}) {+ const org = createFakeBuildOrg({ entities: { contoso_item: { attributes: { contoso_name: 'String' } } }, solution: { uniqueName: 'ContosoReview' } });+ const server = new FakeGenPageServer();+ const dir = makeTempDir('binding-targets-');+ for (const [file, text] of Object.entries(SOURCES)) fs.writeFileSync(path.join(dir, file), text);+ const state = { references: [], answerReferences: null };+ org.intercept((c) => c.method === 'GET' && /^\/EntityDefinitions\(LogicalName='connectionreference'\)/.test(c.path), () => ({ status: 200, headers: {}, body: { EntitySetName: 'connectionreferences' } }));+ org.intercept((c) => c.method === 'GET' && /^\/connectionreferences\?/.test(c.path), () => (state.answerReferences ? state.answerReferences() : { status: 200, headers: {}, body: { value: state.references } }));+ const pages = makeGenpageSdk(org.origin, { httpClient: server.http() });+ t.after(async () => { await pages.dispose(); });+ // The page backend the build uses, the real one. A page it creates is listed by the environment's own page table too, which the build reads through the provisioning SDK.+ const backend = {+ enumerateEnv: (...args) => pages.enumerateEnv(...args),+ read: (...args) => pages.read(...args),+ fileVersions: (...args) => pages.fileVersions(...args),+ projectVersions: (...args) => pages.projectVersions(...args),+ publishedDiffers: (...args) => pages.publishedDiffers(...args),+ create: async (options) => {+ const result = await pages.create(options);+ org.pages.set(result.pageId, { uxagentprojectid: result.pageId, name: options.name, componentstate: 0 });+ return result;+ },+ update: (...args) => pages.update(...args),+ };+ // Each build gets a fresh SDK over the same workspace folder, as every CLI run does.+ const makeSdk = async () => {+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: org.origin, httpClient: org.httpClient });+ await sdk.initWorkspace();+ return sdk;+ };+ const spec = abcSpec({ alpha });+ const first = await runSdkBuild(spec, { sdk: await makeSdk(), apply: true, phases: ['app-shell', 'pages'], workspaceDir: dir, appDir: dir, env: org.origin, genpage: backend });+ assert.equal(first.ok, true);+ assert.deepEqual(Object.keys(first.created.pages).sort(), ['alpha', 'bravo', 'charlie'], 'the first build made the three pages');+ // What the flow records once a fresh full build of the app is verified: the baseline its next changed-only run starts from.+ const live = () => ({ orgId: ORG_ID, envUrl: org.origin, appUniqueName: appUniqueName(spec), appId: org.appId() || null, appIdKnown: true });+ const readContent = (relative) => fs.readFileSync(path.join(dir, relative));+ const baseline = flow.assembleBaselineSnapshot({ annotatedSpec: annotateContentHashes(spec, readContent), created: first.created, live: live(), prior: null, appPreExisted: false, sampleDataApplied: false });+ assert.equal(baseline.eligible, true);+ store.writeSnapshotAtomic(dir, baseline);++ const warnings = [];+ // The changed-only apply, as the CLI runs it on `--apply --changed-only`. Verification is not what is under test: it passes.+ const changedOnlyApply = async () => {+ const mark = { org: org.calls.length, pages: server.requests.length, warned: warnings.length };+ const outcome = await flow.runChangedOnlyApply({+ spec,+ opts: { apply: true, workspaceDir: dir, appDir: dir, env: org.origin, maxRetries: 0 },+ deps: {+ log: () => {},+ buildModelApp,+ buildDeps: {+ sdk: await makeSdk(),+ genpage: backend,+ warn: (w) => warnings.push(String(w)),+ verify: async () => ({ ok: true, checks: [{ kind: 'page', name: 'pages' }], missing: [] }),+ },+ readContent,+ resolveLiveIdentity: async () => live(),+ },+ }).then((result) => ({ result }), (error) => ({ error }));+ const orgCalls = org.calls.slice(mark.org);+ return {+ ...outcome,+ referenceReads: orgCalls.filter((c) => /connectionreference/i.test(c.path)),+ orgWrites: orgCalls.filter((c) => c.method !== 'GET'),+ pageWrites: server.requests.slice(mark.pages).filter((r) => r.method !== 'GET'),+ warnings: warnings.slice(mark.warned),+ };+ };+ const edit = (file) => fs.appendFileSync(path.join(dir, file), '// edited\n');+ return { org, server, dir, state, pages, first, edit, changedOnlyApply };+}++const conflict = (page) => (error) => error && error.code === 'pages-binding-reference-conflict' && error.phase === 'preflight' && error.recoverable === false && error.transient === false+ && error.message.includes(`page "${page}": connector binding "contoso_msnweather" is for connector shared_msnweather, but the connection reference of that name in this environment is for connector shared_office365users`)+ && error.message.includes('The build stopped before writing anything.');++test('the spec these cases build is valid, so none of them rests on a spec the CLI would refuse', () => {+ for (const spec of [abcSpec(), abcSpec({ alpha: SHARED_ALPHA })]) {+ const validated = validateAppSpec(spec, { profile: 'deploy' });+ assert.deepEqual({ ok: validated.ok, errors: validated.errors }, { ok: true, errors: [] });+ }+});++test('REAL BUNDLE: a changed-only apply of an edit to one page writes that page, and neither reads nor judges the binding of a navigation target that exists — though its reference is another connector\'s', async (t) => {+ const app = await builtApp(t);+ app.state.references = [OTHER_CONNECTOR];+ app.edit('Alpha.tsx');+ const run = await app.changedOnlyApply();+ assert.equal(run.error, undefined, run.error && run.error.stack);+ assert.equal(run.result.ok, true);+ assert.equal(run.result.changedOnly.decision, 'fast');+ assert.deepEqual(run.result.changedOnly.pageKeys, ['alpha']);+ assert.deepEqual(run.referenceReads, [], 'no request names the connection reference table: no page the run writes states a binding');+ assert.deepEqual(run.warnings.filter((w) => /contoso_msnweather|"Charlie"/.test(w)), [], 'and nothing is said of Charlie\'s binding');+ assert.equal(app.server.rowText(app.first.created.pages.alpha, 'src/pages/page.tsx'), `${SOURCES['Alpha.tsx']}// edited\n`, 'Alpha holds its edit');+ assert.equal(app.server.rowText(app.first.created.pages.charlie, 'src/pages/page.tsx'), SOURCES['Charlie.tsx'], 'Charlie is as it was');+ assert.equal(store.readSnapshot(app.dir).eligible, true, 'and the baseline is blessed again');+});++test('REAL BUNDLE: a changed-only apply of an edit to the page whose binding names that reference is refused before anything is written', async (t) => {+ const app = await builtApp(t);+ app.state.references = [OTHER_CONNECTOR];+ app.edit('Charlie.tsx');+ const run = await app.changedOnlyApply();+ assert.ok(conflict('Charlie')(run.error), String(run.error && run.error.stack));+ assert.equal(run.referenceReads.filter((c) => /^\/connectionreferences\?/.test(c.path)).length, 1, 'the references were read once');+ assert.deepEqual(run.orgWrites, [], 'nothing was written to the environment');+ assert.deepEqual(run.pageWrites, [], 'and no page');+ assert.equal(app.server.rowText(app.first.created.pages.charlie, 'src/pages/page.tsx'), SOURCES['Charlie.tsx']);+});++test('REAL BUNDLE: a changed-only apply after the navigation target was deleted in Maker makes it — so its binding is refused before anything is written, though the flow\'s record says it is there', async (t) => {+ const app = await builtApp(t);+ const charlie = app.first.created.pages.charlie;+ const removed = await app.server.http().delete(`${app.org.origin}/api/data/v9.0/uxagentprojects(${charlie})`);+ assert.ok(removed.status < 300, `the page service deleted the page: ${removed.status}`);+ app.org.pages.delete(charlie);+ app.state.references = [OTHER_CONNECTOR];+ app.edit('Alpha.tsx');+ const run = await app.changedOnlyApply();+ assert.ok(conflict('Charlie')(run.error), String(run.error && run.error.stack));+ assert.equal(run.referenceReads.filter((c) => /^\/connectionreferences\?/.test(c.path)).length, 1, 'the references were read once, when the run found it had to make the page');+ assert.deepEqual(run.orgWrites, [], 'nothing was written to the environment');+ assert.deepEqual(run.pageWrites, [], 'no page was made or written');+});++// Alpha and the deleted Charlie name the same reference. The check before writing reads it for Alpha (Alpha is fine); the pages phase, about to make Charlie, judges Charlie by that read: the+// name is read once in the attempt, so a second read — refused here — is never made, and the conflict it already proved stops the run before anything is written.+async function deletedCharlieSharingAlphasReference(t) {+ const app = await builtApp(t, { alpha: SHARED_ALPHA });+ const charlie = app.first.created.pages.charlie;+ const removed = await app.server.http().delete(`${app.org.origin}/api/data/v9.0/uxagentprojects(${charlie})`);+ assert.ok(removed.status < 300, `the page service deleted the page: ${removed.status}`);+ app.org.pages.delete(charlie);+ app.state.references = [OTHER_CONNECTOR];+ app.edit('Alpha.tsx');+ return app;+}++test('REAL BUNDLE: a deleted navigation target that names the edited page\'s reference is judged by the one read of it — a refused second read cannot let the target be made unchecked', async (t) => {+ const app = await deletedCharlieSharingAlphasReference(t);+ let rowReads = 0;+ app.state.answerReferences = () => {+ rowReads += 1;+ return rowReads === 1+ ? { status: 200, headers: {}, body: { value: app.state.references } }+ : { status: 403, headers: {}, body: { error: { code: '0x80040220', message: 'The user does not hold the privilege to read connection references.' } } };+ };+ const run = await app.changedOnlyApply();+ assert.ok(conflict('Charlie')(run.error), String(run.error && run.error.stack));+ assert.equal(rowReads, 1, 'the rows of the reference were read once in the attempt');+ assert.deepEqual(run.orgWrites, [], 'nothing was written to the environment');+ assert.deepEqual(run.pageWrites, [], 'no page was made or written');+});++test('REAL BUNDLE: a deleted navigation target that names the edited page\'s reference adds no read of it — one request for its rows in the attempt', async (t) => {+ const app = await deletedCharlieSharingAlphasReference(t);+ const run = await app.changedOnlyApply();+ assert.ok(conflict('Charlie')(run.error), String(run.error && run.error.stack));+ assert.equal(run.referenceReads.filter((c) => /^\/connectionreferences\?/.test(c.path)).length, 1);+ assert.deepEqual(run.orgWrites, []);+ assert.deepEqual(run.pageWrites, []);+});diff --git a/plugins/model-apps/scripts/tests/page-binding-targets.test.js b/plugins/model-apps/scripts/tests/page-binding-targets.test.jsindex 507f74100..2ebccc6f2 100644--- a/plugins/model-apps/scripts/tests/page-binding-targets.test.js+++ b/plugins/model-apps/scripts/tests/page-binding-targets.test.js@@ -6,7 +6,7 @@// exists for ANOTHER connector is refused — the page would call that connector under this name, and the name cannot tell them apart — and a name that is not there, or a Custom API of another kind, is said by name.const { test } = require('node:test');const assert = require('node:assert');-const { connectorKey, pagesStatingBindings, readBindingTargets, judgeBindingTargets, definedOperations } = require('../lib/page-binding-targets.js');+const { connectorKey, pagesStatingBindings, pagesMadeUnchecked, pagesLeftOutAsDeployed, bindingReads, readBindingTargets, judgeBindingTargets, definedOperations } = require('../lib/page-binding-targets.js');const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };const SHAREPOINT = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'] };@@ -60,6 +60,52 @@ test('pagesStatingBindings: a changed-only run writes the pages it selected, andassert.deepStrictEqual(keys({ resolvedAppId: 'x' }), ['a', 'b', 'c', 'd'], 'a changed-only run that selects nothing by key is not narrowed');});+// A changed-only run makes a navigation target only when the target is absent; one that exists is left as it is, so its bindings are not written and not checked. Whether it exists is known only to what the+// run is told (`deployedKeys`, the pages its last verified apply deployed): a target it is not told of may be absent, and is checked.+test('pagesStatingBindings: a changed-only run told which pages are deployed checks a navigation target only when it is absent — and every target it is not told of', () => {+ const spec = { pages: [+ pageOf('a', { connectorBindings: [WEATHER] }),+ pageOf('b', { connectorBindings: [SHAREPOINT], navigatesTo: [{ targetKey: 'c' }] }),+ pageOf('c', { actionBindings: [APPROVE] }),+ pageOf('d', { actionBindings: [SUMMARY] }),+ ] };+ const keys = (changedOnly) => pagesStatingBindings(spec, { changedOnly }).map((p) => p.key);+ const ALL = ['a', 'b', 'c', 'd'];+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ALL }), ['a'], 'c exists: the run leaves it as it is, so its bindings are not read');+ assert.deepStrictEqual(keys({ selectedKeys: ['b'], deployedKeys: ALL }), ['b'], 'nor when the page that navigates to it is the one written');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'd'] }), ['a', 'c'], 'c is not deployed: the run makes it, bindings and all');+ assert.deepStrictEqual(keys({ selectedKeys: ['c'], deployedKeys: ALL }), ['c'], 'a selected page is written whether or not it exists');+ assert.deepStrictEqual(keys({ selectedKeys: [], deployedKeys: ALL }), []);+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: [] }), ['a', 'c']);+ // Not told, or told in a form that says nothing: c may be absent, so it is checked, as before.+ assert.deepStrictEqual(keys({ selectedKeys: ['a'] }), ['a', 'c']);+ for (const deployedKeys of [undefined, null, 'c', { c: true }, 7]) assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys }), ['a', 'c'], JSON.stringify(deployedKeys));+ // A run that is not changed-only writes every page, whatever it is told.+ assert.deepStrictEqual(keys({ deployedKeys: ALL }), ALL);+ assert.deepStrictEqual(keys({ resolvedAppId: 'x', deployedKeys: ALL }), ALL);+});++// The pages phase settles which targets are absent, after the check before writing ran: a target the run was told of that it then finds absent (deleted in Maker since the last apply) is made from its spec+// entry, so it is handed back to be checked before it is made. Nothing else is: every other page the run writes was checked before it wrote anything.+test('pagesMadeUnchecked is the pages about to be made that the check before writing left out — the targets the run was told of and found absent — and nothing else', () => {+ const spec = { pages: [+ pageOf('a', { connectorBindings: [WEATHER] }),+ pageOf('b', { connectorBindings: [SHAREPOINT], navigatesTo: [{ targetKey: 'c' }, { targetKey: 'e' }] }),+ pageOf('c', { actionBindings: [APPROVE] }),+ pageOf('d', { actionBindings: [SUMMARY] }),+ pageOf('e'),+ ] };+ const keys = (changedOnly, made) => pagesMadeUnchecked(spec, { changedOnly, made: new Set(made) }).map((p) => p.key);+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'c', 'd', 'e'] }, ['c']), ['c'], 'c was said to be deployed, and is about to be made: it is checked now');+ assert.deepStrictEqual(pagesMadeUnchecked(spec, { changedOnly: { selectedKeys: ['a'], deployedKeys: ['a', 'b', 'c', 'd', 'e'] }, made: new Set(['c']) }), [{ key: 'c', name: 'C', actionBindings: [APPROVE] }], 'with the lists as the spec states them');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'c', 'd', 'e'] }, ['c', 'e']), ['c'], 'e states no binding: nothing to check');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'c', 'd', 'e'] }, []), [], 'nothing is about to be made');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'd', 'e'] }, ['c']), [], 'c was not said to be deployed: it was checked before anything was written');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'] }, ['c']), [], 'a run told nothing checked every target before anything was written');+ assert.deepStrictEqual(keys(undefined, ['c']), [], 'and a full build checked every page');+ assert.deepStrictEqual(keys({ selectedKeys: ['c'], deployedKeys: ['a', 'b', 'c', 'd', 'e'] }, ['c']), [], 'a selected page was checked before anything was written');+});+// ── reading the environment ──────────────────────────────────────────────────────────────────────────────────────────────────function readerOf(rows, { failOn } = {}) {@@ -126,6 +172,94 @@ test('readBindingTargets quotes a name into the filter as OData text, reads manyassert.match(cannot.problems.references, /cannot be read here/, 'a reader that cannot read is a read that failed');});+// One attempt of a build can check bindings twice: before it writes anything, and in its pages phase for a navigation target it finds it has to make (sdk-build.js). Both go through what the+// attempt has read (bindingReads): a name is read once per attempt, and what that read answered — a row, no row, a failure — stands for every check of the attempt.+test('readBindingTargets: an attempt reads a name once — a later check of the same attempt asks only for the names it has not read', async () => {+ const seen = bindingReads();+ const { provision, calls } = readerOf({ connectionreference: [reference('contoso_msnweather', 'shared_msnweather'), reference('contoso_sharepoint', 'shared_sharepointonline')] });+ const first = await readBindingTargets(provision, [{ key: 'a', name: 'A', connectorBindings: [WEATHER] }], seen);+ assert.deepStrictEqual([...first.references.keys()], ['contoso_msnweather']);+ const second = await readBindingTargets(provision, [{ key: 'c', name: 'C', connectorBindings: [{ ...WEATHER, logicalName: 'CONTOSO_MSNWEATHER' }, SHAREPOINT, { logicalName: 'contoso_absent' }] }], seen);+ assert.deepStrictEqual(calls.map((c) => c.options.filter), [+ "connectionreferencelogicalname eq 'contoso_msnweather'",+ "connectionreferencelogicalname eq 'contoso_sharepoint' or connectionreferencelogicalname eq 'contoso_absent'",+ ], 'the second check asks only for the names the first did not read, whatever their case');+ assert.deepStrictEqual(second.references, new Map([['contoso_msnweather', { connectorId: api('shared_msnweather') }], ['contoso_sharepoint', { connectorId: api('shared_sharepointonline') }]]));+ const third = await readBindingTargets(provision, [{ key: 'd', name: 'D', connectorBindings: [WEATHER, { logicalName: 'contoso_absent' }] }], seen);+ assert.strictEqual(calls.length, 2, 'a check whose names were all read asks nothing — a name that is not there is an answer too');+ assert.deepStrictEqual(third.references, new Map([['contoso_msnweather', { connectorId: api('shared_msnweather') }]]));+ assert.deepStrictEqual(judgeBindingTargets([{ key: 'd', name: 'D', connectorBindings: [{ logicalName: 'contoso_absent' }] }], third).findings.map((f) => f.kind), ['reference-missing']);+});++test('readBindingTargets: what an attempt has read stands — a later read that fails leaves a proven conflict a refusal, and says by name only what it could not read', async () => {+ const seen = bindingReads();+ const filters = [];+ let refuse = false;+ const provision = {+ queryRecords: async (entity, options) => {+ filters.push(options.filter);+ if (refuse) throw new Error('connectionreference: HTTP 403');+ return [reference('contoso_msnweather', 'shared_office365users')];+ },+ };+ await readBindingTargets(provision, [{ key: 'a', name: 'A', connectorBindings: [{ ...WEATHER, connectorId: api('shared_office365users') }] }], seen);+ refuse = true;+ const pages = [{ key: 'c', name: 'C', connectorBindings: [WEATHER, SHAREPOINT] }];+ const targets = await readBindingTargets(provision, pages, seen);+ assert.deepStrictEqual(filters, ["connectionreferencelogicalname eq 'contoso_msnweather'", "connectionreferencelogicalname eq 'contoso_sharepoint'"]);+ const verdict = judgeBindingTargets(pages, targets);+ assert.deepStrictEqual(verdict.findings.map((f) => [f.severity, f.kind, f.binding, f.found]), [['refuse', 'connector-conflict', 'contoso_msnweather', 'shared_office365users']], 'the first read proved the conflict, and the failed one does not undo it');+ assert.deepStrictEqual(verdict.unchecked.map((u) => [u.what, u.text]), [['connection references', 'could not read this environment\'s connection references (connectionreference: HTTP 403), so connector binding "contoso_sharepoint" of page "C" was not checked against them']]);+});++test('readBindingTargets: a read that failed stands for the attempt too — a later check asks nothing, and says, as the one read did, that the bindings were not checked', async () => {+ const seen = bindingReads();+ const denied = readerOf({}, { failOn: ['connectionreference'] });+ await readBindingTargets(denied.provision, [{ key: 'a', name: 'A', connectorBindings: [WEATHER] }], seen);+ const pages = [{ key: 'c', name: 'C', connectorBindings: [WEATHER] }];+ const targets = await readBindingTargets(denied.provision, pages, seen);+ assert.strictEqual(denied.calls.length, 1, 'not asked again');+ assert.strictEqual(targets.references, null);+ assert.deepStrictEqual(targets.problems, { references: 'connectionreference: HTTP 403' });+ assert.deepStrictEqual(judgeBindingTargets(pages, targets).unchecked.map((u) => u.text), ['could not read this environment\'s connection references (connectionreference: HTTP 403), so the connector bindings of page "C" were not checked against them']);+});++test('readBindingTargets: a Custom API, and the definition of a custom connector, are read once per attempt as well', async () => {+ const seen = bindingReads();+ const CONNECTOR_ID = 'c0000000-0000-4000-8000-0000000000a1';+ const WIDGETS = { logicalName: 'contoso_widgets', connectorId: api('shared_contoso-5fwidgets-5f6a8c'), dataset: '', operations: ['ListWidgets'] };+ const { provision, calls } = readerOf({+ connectionreference: [{ connectionreferencelogicalname: 'contoso_widgets', connectorid: api('shared_contoso-5fwidgets-5f6a8c'), connectionid: 'shared-widgets-0001', _customconnectorid_value: CONNECTOR_ID }],+ connector: [{ connectorid: CONNECTOR_ID, openapidefinition: JSON.stringify({ swagger: '2.0', paths: { '/widgets': { get: { operationId: 'ListWidgets' } } } }) }],+ customapi: [customApi('contoso_ApproveOrder', { boundentitylogicalname: 'contoso_item', bindingtype: 1 })],+ });+ const page = (key) => ({ key, name: key.toUpperCase(), connectorBindings: [WIDGETS], actionBindings: [APPROVE] });+ const first = await readBindingTargets(provision, [page('a')], seen);+ const second = await readBindingTargets(provision, [page('c')], seen);+ assert.deepStrictEqual(calls.map((c) => c.entity), ['connectionreference', 'connector', 'customapi'], 'each read once, in the first check');+ assert.deepStrictEqual(second, first, 'and the second check is answered with what it read');+ assert.deepStrictEqual(judgeBindingTargets([page('c')], second), { findings: [], unchecked: [] });+});++test('pagesLeftOutAsDeployed is the pages the check before writing leaves out because the run was told they are deployed — what a dry run asks the environment about', () => {+ const spec = { pages: [+ pageOf('a', { connectorBindings: [WEATHER] }),+ pageOf('b', { connectorBindings: [SHAREPOINT], navigatesTo: [{ targetKey: 'c' }, { targetKey: 'e' }] }),+ pageOf('c', { actionBindings: [APPROVE] }),+ pageOf('d', { actionBindings: [SUMMARY] }),+ pageOf('e'),+ ] };+ const ALL = ['a', 'b', 'c', 'd', 'e'];+ const keys = (changedOnly) => pagesLeftOutAsDeployed(spec, changedOnly).map((p) => p.key);+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ALL }), ['c'], 'e states no binding, so there is nothing to leave out');+ assert.deepStrictEqual(pagesLeftOutAsDeployed(spec, { selectedKeys: ['a'], deployedKeys: ALL }), [{ key: 'c', name: 'C', actionBindings: [APPROVE] }]);+ assert.deepStrictEqual(keys({ selectedKeys: ['a'], deployedKeys: ['a', 'b', 'd', 'e'] }), [], 'c was not said to be deployed: it is checked');+ assert.deepStrictEqual(keys({ selectedKeys: ['c'], deployedKeys: ALL }), [], 'a selected page is checked');+ assert.deepStrictEqual(keys({ selectedKeys: ['a'] }), []);+ assert.deepStrictEqual(keys({ deployedKeys: ALL }), [], 'a run that is not changed-only leaves out nothing');+ assert.deepStrictEqual(keys(undefined), []);+});+// ── judging what was read ────────────────────────────────────────────────────────────────────────────────────────────────────const pagesA = [{ key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] }];diff --git a/plugins/model-apps/scripts/tests/page-bindings.test.js b/plugins/model-apps/scripts/tests/page-bindings.test.jsindex 7d8ad2391..f6b5c9d01 100644--- a/plugins/model-apps/scripts/tests/page-bindings.test.js+++ b/plugins/model-apps/scripts/tests/page-bindings.test.js@@ -741,7 +741,8 @@ async function downloadThenRebuild({ edit } = {}) {const before = genpage.of('update').length;const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir, env: ENV, apply: true, phases: PHASES });assert.ok(rebuilt.ok);- assert.deepStrictEqual(rebuilt.created.pages, { weather: WEATHER_ID, detail: DETAIL_ID });+ // `created.pages` is a null-prototype map (lib/own-keys.js: a page's key can be `constructor`), so its entries are compared.+ assert.deepStrictEqual({ ...rebuilt.created.pages }, { weather: WEATHER_ID, detail: DETAIL_ID });const updates = genpage.of('update').slice(before);assert.strictEqual(updates.length, 2, 'one update per page');assert.strictEqual(genpage.of('create').length, 0, 'a downloaded page is updated, never created');diff --git a/plugins/model-apps/scripts/tests/page-download-rebuild.test.js b/plugins/model-apps/scripts/tests/page-download-rebuild.test.jsindex b7e20cb19..4e5ae2b20 100644--- a/plugins/model-apps/scripts/tests/page-download-rebuild.test.js+++ b/plugins/model-apps/scripts/tests/page-download-rebuild.test.js@@ -117,7 +117,8 @@ test('download-hydrate-rebuild preserves page identity name model and bindings',const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir, env: ENV, apply: true, phases: ['solution', 'data-model', 'app-shell', 'pages'] });assert.ok(rebuilt.ok);assert.strictEqual(rebuilt.created.app, APP_ID);- assert.deepStrictEqual(rebuilt.created.pages, { overview: OVERVIEW_ID, detail: DETAIL_ID });+ // `created.pages` is a null-prototype map (lib/own-keys.js: a page's key can be `constructor`), so its entries are compared.+ assert.deepStrictEqual({ ...rebuilt.created.pages }, { overview: OVERVIEW_ID, detail: DETAIL_ID });const updates = genpage.of('update').slice(start);assert.strictEqual(updates.length, 2, 'exactly one update per page');assert.strictEqual(genpage.of('create').length, 0, 'a downloaded page must be updated, never created');diff --git a/plugins/model-apps/scripts/tests/page-structure.test.js b/plugins/model-apps/scripts/tests/page-structure.test.jsindex 2dbd20739..b78fed301 100644--- a/plugins/model-apps/scripts/tests/page-structure.test.js+++ b/plugins/model-apps/scripts/tests/page-structure.test.js@@ -18,6 +18,12 @@ const CASES = [// A tilde fence needs no escaping inside a template literal, which is how a page embeds markdown help.['fence inside a template literal is data', 'const help = \u0060\n~~~md\nx\n~~~\n\u0060;\nexport default function P() { return <div>{help}</div>; }\n'],['elided body', 'export default function P() {\n // ... rest of the component\n return null;\n}\n'],+ // A generic arrow is a default export (its `<` opens type parameters by TypeScript's rule for .tsx); an element is not, and is no component the host can mount.+ ['generic-arrow default export', 'export default <T,>(props: { items: T[] }) => <div>{props.items.length}</div>;\n'],+ ['element for the default export', 'export default <div>ok</div>;\n'],+ // A return type that holds an `=>` of its own, read to its end: complete with the arrow after it, cut off without.+ ['generic arrow whose return type is a function type', 'export default <T,>(p: T): (x: T) => T => (x) => x;\n'],+ ['generic arrow cut off after a function-type return type', 'export default <T,>(p: T): (x: T) => T'],];for (const [name, code] of CASES) {@@ -35,4 +41,8 @@ test('a complete page passes and each failure is named', () => {assert.match(pageStructureProblems(CASES[6][1]).join('\n'), /markdown code fence/);assert.deepEqual(pageStructureProblems(CASES[7][1]), []);assert.match(pageStructureProblems(CASES[8][1]).join('\n'), /the page is incomplete/);+ assert.deepEqual(pageStructureProblems(CASES[9][1]), []);+ assert.deepEqual(pageStructureProblems(CASES[10][1]), [pageStructureProblems(CASES[2][1])[0]]);+ assert.deepEqual(pageStructureProblems(CASES[11][1]), []);+ assert.deepEqual(pageStructureProblems(CASES[12][1]), [pageStructureProblems(CASES[2][1])[0]]);});diff --git a/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js b/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.jsindex 2ad879c4d..0ae1a648d 100644--- a/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js+++ b/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js@@ -10,6 +10,7 @@ const os = require('node:os');const path = require('node:path');const { acquireAppPagesLease } = require('../lib/sdk-build.js');const { ownerStamp } = require('../lib/process-owner.js');+const { sha256 } = require('../lib/hash.js');const { startTarget, tempEnv, privateTempRoot, deadPid, removeWhenTestEnds } = require('./helpers/kill-target-client.js');const APP = 'contoso_app';@@ -20,6 +21,9 @@ const workspace = (t) => {return dir;};const lockFile = (dir, app = APP) => path.join(dir, `pages-${app}.lock`);+// The pages lock is two files (lib/app-operation-lease.js): the hashed one, keyed without regard to case, is taken first, so it is the one that refuses a+// second build of this release; the legacy one above is the one every earlier release takes, and refuses a build of this release while one of those holds it.+const canonicalFile = (dir, app = APP) => path.join(dir, `app-pages.${sha256(app.toLowerCase())}.lock`);// The refusal's words, as they have always been: a person and the skills read them, so they are pinned.const REFUSAL = (lock, app = APP) => `another build is deploying pages for '${app}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${lock} if it is stale.`;const refused = (lock, app = APP) => (e) => e && e.code === 'pages-locked' && e.phase === 'pages' && e.recoverable === true && e.message === REFUSAL(lock, app);@@ -30,9 +34,10 @@ test('REAL KILL: the lock a killed build left is released by the next build, whiawait holder.waitFor(/^held$/);const file = lockFile(dir);assert.ok(fs.existsSync(file), 'the build holds the lock');+ assert.ok(fs.existsSync(canonicalFile(dir)), 'both of its files');- // While the build is running its lock holds, in the words it has always had.- assert.throws(() => acquireAppPagesLease(dir, APP), refused(file));+ // While the build is running its lock holds, in the words it has always had — naming the file that refused, the hashed one a build of this release takes first.+ assert.throws(() => acquireAppPagesLease(dir, APP), refused(canonicalFile(dir)));await holder.kill();assert.ok(fs.existsSync(file), 'a killed process cannot release its lock: it is still there');@@ -42,10 +47,11 @@ test('REAL KILL: the lock a killed build left is released by the next build, whiconst lease = acquireAppPagesLease(dir, APP, { warn: (message) => warnings.push(message) });assert.notStrictEqual(fs.readFileSync(file, 'utf8'), killedLock, 'the lock is no longer the killed build\'s');assert.strictEqual(JSON.parse(fs.readFileSync(file, 'utf8')).pid, process.pid, 'it names this process');- assert.strictEqual(warnings.length, 1, `one warning, never silent: ${JSON.stringify(warnings)}`);+ assert.strictEqual(JSON.parse(fs.readFileSync(canonicalFile(dir), 'utf8')).pid, process.pid, 'and so does the hashed one');+ assert.strictEqual(warnings.length, 1, `one warning for the one build that held both files, never silent: ${JSON.stringify(warnings)}`);assert.ok(warnings[0].includes(`'${APP}'`) && warnings[0].includes(`pid ${holder.pid}`) && /no longer running/.test(warnings[0]), warnings[0]);// And it is a lock like any other: a third build is refused while this one holds it, and may take it once this one lets go.- assert.throws(() => acquireAppPagesLease(dir, APP), refused(file));+ assert.throws(() => acquireAppPagesLease(dir, APP), refused(canonicalFile(dir)));lease.release();assert.ok(!fs.existsSync(file), 'released');assert.deepStrictEqual(fs.readdirSync(dir), [], 'and nothing else is left in the workspace, a reclaim claim included');@@ -121,19 +127,23 @@ test('a lock whose recorded start is empty, truncated or malformed is not takenconst first = acquireAppPagesLease(dir, APP, { owner: here });const held = JSON.parse(fs.readFileSync(file, 'utf8'));assert.strictEqual(held.start, `${BOOT}:900`, 'control: the lock records the start it was taken with');- // Only the start is damaged: the lock is still JSON, and says whose it is.+ // Only the start is damaged, in both files the build holds: each is still JSON, and says whose it is.const damaged = JSON.stringify({ ...held, start });+ const damagedHashed = JSON.stringify({ ...JSON.parse(fs.readFileSync(canonicalFile(dir), 'utf8')), start });fs.writeFileSync(file, damaged);+ fs.writeFileSync(canonicalFile(dir), damagedHashed);const what = JSON.stringify(start);// The same process (a build that is running): a second lease before the first is released.- assert.throws(() => acquireAppPagesLease(dir, APP, { owner: here }), refused(file), `${what}: this process's own lock`);+ assert.throws(() => acquireAppPagesLease(dir, APP, { owner: here }), refused(canonicalFile(dir)), `${what}: this process's own lock`);// A process that is not found: an untrusted record is not a dead one's.const warnings = [];- assert.throws(() => acquireAppPagesLease(dir, APP, { owner: { ...here, pid: 100, probe: () => 'gone' }, warn: (message) => warnings.push(message) }), refused(file), `${what}: a pid that is not found`);+ assert.throws(() => acquireAppPagesLease(dir, APP, { owner: { ...here, pid: 100, probe: () => 'gone' }, warn: (message) => warnings.push(message) }), refused(canonicalFile(dir)), `${what}: a pid that is not found`);assert.strictEqual(fs.readFileSync(file, 'utf8'), damaged, `${what}: the lock is as it was`);+ assert.strictEqual(fs.readFileSync(canonicalFile(dir), 'utf8'), damagedHashed, `${what}: the hashed one too`);assert.deepStrictEqual(warnings, []);first.release();assert.strictEqual(fs.readFileSync(file, 'utf8'), damaged, `${what}: the first build's late release leaves a lock that is not its token alone`);+ assert.strictEqual(fs.readFileSync(canonicalFile(dir), 'utf8'), damagedHashed, `${what}: the hashed one too`);}});@@ -143,14 +153,16 @@ test('a lock held by a process that is running is never taken — however old itconst holder = startTarget(t, ['lock', dir, APP]);await holder.waitFor(/^held$/);// Much later, by the clock the function is given: a lock is never old enough to be taken from a process that is still running.- assert.throws(() => acquireAppPagesLease(dir, APP, { now: () => Date.now() + 10 * 24 * 3600 * 1000 }), refused(file));+ assert.throws(() => acquireAppPagesLease(dir, APP, { now: () => Date.now() + 10 * 24 * 3600 * 1000 }), refused(canonicalFile(dir)));assert.strictEqual(JSON.parse(fs.readFileSync(file, 'utf8')).pid, holder.pid, 'the holder\'s lock is untouched');+ assert.strictEqual(JSON.parse(fs.readFileSync(canonicalFile(dir), 'utf8')).pid, holder.pid, 'both of its files');await holder.kill();fs.rmSync(file);+ fs.rmSync(canonicalFile(dir));// This process's own lock: a second build in the same process is a second build, and is refused.const mine = acquireAppPagesLease(dir, APP);- assert.throws(() => acquireAppPagesLease(dir, APP), refused(file));+ assert.throws(() => acquireAppPagesLease(dir, APP), refused(canonicalFile(dir)));mine.release();});@@ -161,7 +173,7 @@ test('the lock is taken exclusively, and released only by the build that holds iconst record = JSON.parse(fs.readFileSync(file, 'utf8'));assert.strictEqual(record.pid, process.pid);assert.strictEqual(typeof record.at, 'number');- assert.throws(() => acquireAppPagesLease(dir, APP), refused(file));+ assert.throws(() => acquireAppPagesLease(dir, APP), refused(canonicalFile(dir)));// Another build now holds the lock (the file says so): this one's late release leaves it alone.const others = JSON.stringify({ ...record, pid: record.pid + 1, rnd: 'someone-else' });fs.writeFileSync(file, others);@@ -200,10 +212,11 @@ test('a lock whose owner is gone but that cannot be released — another build itest('a workspace that cannot be written is that error, as it always was — not a refusal that says another build is deploying pages', (t) => {const dir = workspace(t);- // The workspace's own path is a file: nothing can be created in it.+ // The workspace's own path is a file: nothing can be created in it. The folder is checked as every folder the plugin writes into is (lib/safe-fs.js),+ // so the error is that check's refusal of a path that is not a folder.const blocked = path.join(dir, 'not-a-folder');fs.writeFileSync(blocked, '');- assert.throws(() => acquireAppPagesLease(blocked, APP), (e) => !(e && e.code === 'pages-locked') && /ENOTDIR|EEXIST|ENOENT/.test(String(e && e.code)), 'the file system\'s own error');+ assert.throws(() => acquireAppPagesLease(blocked, APP), (e) => !(e && e.code === 'pages-locked') && e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-directory', 'the file system\'s own problem');});// Several builds that start at once, and each finds the lock: not there at all, or left by a build that was killed. Exactly one of them takes it.@@ -230,7 +243,8 @@ for (const [what, killedFirst] of [['no lock at all', false], ['the lock of a kiassert.strictEqual(winners.length, 1, `round ${round}: one winner, got ${JSON.stringify(answers)}`);assert.ok(answers.filter((a) => a !== 'held').every((a) => a === 'refused pages-locked'), `round ${round}: the others are refused: ${JSON.stringify(answers)}`);assert.strictEqual(JSON.parse(fs.readFileSync(lockFile(dir, app), 'utf8')).pid, winners[0].pid, `round ${round}: the lock names the winner`);- assert.deepStrictEqual(fs.readdirSync(dir), [`pages-${app}.lock`], `round ${round}: no claim or other file is left`);+ assert.strictEqual(JSON.parse(fs.readFileSync(canonicalFile(dir, app), 'utf8')).pid, winners[0].pid, `round ${round}: both of its files`);+ assert.deepStrictEqual(fs.readdirSync(dir).sort(), [path.basename(canonicalFile(dir, app)), `pages-${app}.lock`].sort(), `round ${round}: no claim or other file is left`);await Promise.all(racers.map((racer) => racer.kill()));}});diff --git a/plugins/model-apps/scripts/tests/post-create-lag.test.js b/plugins/model-apps/scripts/tests/post-create-lag.test.jsnew file mode 100644index 000000000..076210036--- /dev/null+++ b/plugins/model-apps/scripts/tests/post-create-lag.test.js@@ -0,0 +1,818 @@+'use strict';+// The lag of a table the build has just created (lib/entity-provision.js, "The lag of a table this attempt just created").+//+// Right after a table is created, a create of one of its columns — in the change set, or on its own — or the insert of one of its status reasons is+// intermittently refused with HTTP 400 and a generic code (`0x80040216` "An unexpected error occurred.", `0x80090457` "Component of type Entity …+// does not exist."), and a re-run succeeds. These tests drive the data-model phase (provisionDataModel) over the REAL vendored SDK, the plugin's own+// HTTP client and the strict stateful fake of helpers/fake-lifecycle-org.js, with a seam in front of the fake's transport that answers the requests a+// test names — the request-level fault a live check injects — so the environment holds exactly what it would after a real refusal. The clock, the+// waits and the jitter are the phase's seams: a wait records its length and moves the clock, and nothing sleeps.+//+// What is held: a refused create is sent again only after a read PROVES it absent, within the table's budget (60 s of the time the check itself+// waits, 8 reads, 4 resends of one create, 1 of the change set); a create the read shows is adopted; a read that proves nothing is read again; a+// budget spent stops the build with the original refusal and a halt that says the build may be run again — said only by the halt, never by the+// error the step reports; and nothing changes for a table that existed, for the other refusals, or for a build the lag never touches.+const { test } = require('node:test');+const assert = require('node:assert');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');+const { makeRunner, provisionDataModel, provisionSolution, BuildHalt } = require('../lib/entity-provision.js');+const { serviceCodeOf, retryPolicyFor } = require('../lib/retry-policy.js');+const { isTransientHalt, buildModelApp } = require('../build-model-app.js');+const { appFolder, command, settle } = require('./helpers/build-command-harness.js');++const SOLUTION = 'ContosoLag';+// A token long enough for the client's scrubber, never sent anywhere: the transport is the fake.+const TOKEN = 'post-create-lag-token-0123456789';+const SUFFIX = ' — the refusal persisted after the bounded check. The table was created. Run the build again to reconcile what is already there; a refusal that is not lag will persist';+const UNEXPECTED = 'An unexpected error occurred.';+const NOT_THERE = 'Component of type Entity with name and id 00000000-0000-4000-8000-000000000000 does not exist.';++// --- the platform's answers ------------------------------------------------------------------------------------------------------------------------------+// A refusal is an OData error: HTTP 400 { "error": { "code": "0x80040216", "message": "An unexpected error occurred." } }+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response+const odata = (statusCode, error) => ({ statusCode, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error }) });+const refused = (code = '0x80040216', message = UNEXPECTED) => odata(400, { code, message });+// A change set refused as a whole: HTTP 400, and the refusal in the part of the operation that failed (the first, here).+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#handling-errors+const batchRefused = (error) => ({+ statusCode: 400,+ headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_lag' },+ body: ['--batchresponse_lag', 'Content-Type: multipart/mixed; boundary=changesetresponse_lag', '',+ '--changesetresponse_lag', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 1', '',+ 'HTTP/1.1 400 Bad Request', 'OData-Version: 4.0', 'Content-Type: application/json; odata.metadata=minimal', '',+ JSON.stringify({ error }), '--changesetresponse_lag--', '--batchresponse_lag--', ''].join('\r\n'),+});+const list = (value) => ({ statusCode: 200, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ value }) });++// --- what the build sends --------------------------------------------------------------------------------------------------------------------------------+const PROBE = /^\/EntityDefinitions\([0-9a-f-]{36}\)\/Attributes\?\$select=MetadataId,LogicalName$/;+const STATUS_READ = /^\/EntityDefinitions\([0-9a-f-]{36}\)\/Attributes\/Microsoft\.Dynamics\.CRM\.StatusAttributeMetadata\?/;+const columnPost = (table, column) => (where, req) => where === `/EntityDefinitions(LogicalName='${table}')/Attributes` && JSON.parse(req.body).SchemaName === column;+const isBatch = (where) => where === '/$batch';+const isInsert = (where) => where === '/InsertStatusValue';+const isProbe = (where) => PROBE.test(where);++// One fake environment, with the solution made, and a seam in front of its transport: `fault(method, matches, answer)` answers what `answer(req, n)`+// returns for the n-th request it matches, and lets the request through to the fake when it returns nothing. `wire` is every request, in order.+async function lagEnv() {+ const org = createLifecycleOrg();+ const wire = [];+ const faults = [];+ const request = async (req) => {+ const url = new URL(req.url);+ const where = decodeURIComponent(url.pathname + url.search).replace(/^\/api\/data\/v9\.\d/, '');+ const entry = { method: req.method, path: where, body: req.body };+ wire.push(entry);+ for (const f of faults) {+ if (f.method !== req.method || !f.matches(where, req)) continue;+ f.hits += 1;+ const answer = await f.answer(req, f.hits);+ if (answer) { entry.faulted = true; return answer; }+ }+ return org.request(req);+ };+ const fault = (method, matches, answer) => {+ const f = { method, matches, answer, hits: 0 };+ faults.push(f);+ return { lift: () => faults.splice(faults.indexOf(f), 1), hits: () => f.hits };+ };+ const client = createAzHttpClient(org.origin, { getToken: () => TOKEN, request, sleep: async () => {} });+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('post-create-lag-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: SOLUTION });+ await sdk.initWorkspace();+ await provisionSolution({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 1 }), solution: { uniqueName: SOLUTION, publisherPrefix: 'contoso' } });+ // What a request answered by the fake itself does to the environment: a create that "committed and then failed" goes through, then fails.+ const through = (req) => org.request(req);+ return { org, wire, fault, sdk, through };+}++// The clock the phase is given: a wait records its length and moves the clock; `advance` is a read that takes time.+function clock() {+ let t = 1000000;+ const waits = [];+ return { now: () => t, sleep: async (ms) => { waits.push(ms); t += ms; }, advance: (ms) => { t += ms; }, waits };+}++const ticket = ({ columns = [{ schemaName: 'contoso_title', displayName: 'Title', type: 'Text' }, { schemaName: 'contoso_code', displayName: 'Code', type: 'Text' }], statusReasons, alternateKeys } = {}) => ({+ schemaName: 'contoso_ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns,+ ...(statusReasons ? { statusReasons } : {}), ...(alternateKeys ? { alternateKeys } : {}),+});+const lagSpec = (entities = [ticket()], relationships = []) => ({ solution: { uniqueName: SOLUTION, publisherPrefix: 'contoso' }, app: { name: 'Lag' }, relationships, entities });++// Runs the data-model phase once. Answers what it returned or threw, its events and warnings, the clock, and the requests it sent.+async function phase(env, spec, { clk = clock(), inlineColumns } = {}) {+ const events = [];+ const warnings = [];+ const mark = env.wire.length;+ let result = null;+ let error = null;+ try {+ result = await provisionDataModel({+ sdk: env.sdk, provision: env.sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033,+ provisionedLanguages: async () => [1033, 3082], sleep: clk.sleep, now: clk.now, random: () => 0, warn: (m) => warnings.push(String(m)),+ ...(inlineColumns === false ? { inlineColumns: false } : {}),+ });+ } catch (e) { error = e; }+ return { result, error, events, warnings, clk, wire: env.wire.slice(mark) };+}++const posts = (run, matches) => run.wire.filter((r) => r.method === 'POST' && matches(r.path, r));+const probes = (run) => run.wire.filter((r) => r.method === 'GET' && isProbe(r.path));+const steps = (run, prefix) => run.events.filter((e) => e.status !== 'start' && e.label.startsWith(prefix));+const lagWarnings = (run) => run.warnings.filter((w) => /was refused just after the table was created/.test(w));+const columnIds = (env, table) => {+ const t = [...env.org.metadata.tables.values()].find((x) => x.LogicalName === table);+ return Object.fromEntries((t ? [...t.Attributes.values()] : []).map((a) => [a.LogicalName, a.MetadataId]));+};+// The halt is the runner's, around the failure the step threw; its message is the step's failure and, for a refusal the check ran out on, more.+const haltOf = (run) => { assert.ok(run.error instanceof BuildHalt, `the phase halts: ${run.error && run.error.stack}`); return run.error; };++// The fake's own answer to a read of the table's columns, with its rows reworked by `rework(rows)` — the answer a platform could give that is a list,+// and that names the table's primary name column, and yet is not usable row by row.+const reworked = (env, rework) => async (req) => {+ const res = await env.through(req);+ const body = JSON.parse(res.body);+ return { ...res, body: JSON.stringify({ ...body, value: rework(body.value) }) };+};+// The row of the column `logical` without its id: the column is named, and nothing can be adopted from that row.+const withoutIdOf = (logical) => (rows) => rows.map((a) => (String(a.LogicalName).toLowerCase() === logical ? { LogicalName: a.LogicalName } : a));+// A change set refused with the lag every time it is sent.+const lagBatch = (env) => env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+// The halt of a change set's refusal, the check having run out.+const changeSetHalt = (run, what) => {+ assert.ok(run.error instanceof BuildHalt, `${what}: the phase halts: ${run.error && run.error.stack}`);+ const halt = run.error;+ assert.ok(halt.message.endsWith(SUFFIX), `${what}: ${halt.message}`);+ assert.strictEqual(halt.cause.statusCode, 400, `${what}: the change set's refusal`);+ assert.ok(String(halt.cause.cause).includes('{"error":{"code":"0x80040216"'), `${what}: its own answer, which holds the code in its first part`);+ assert.strictEqual(halt.retry, 'never', what);+ return halt;+};++// --- the change set ---------------------------------------------------------------------------------------------------------------------------------------++test('a change set refused with the lag of its new table is sent again once, after a read proves its columns absent — and its columns are the ones that read and the commit give', async () => {+ const env = await lagEnv();+ env.fault('POST', isBatch, (req, n) => (n === 1 ? batchRefused({ code: '0x80040216', message: UNEXPECTED }) : undefined));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ const batches = posts(run, isBatch);+ assert.strictEqual(batches.length, 2, 'the change set is sent again, once');+ const between = run.wire.slice(run.wire.indexOf(batches[0]) + 1, run.wire.indexOf(batches[1]));+ assert.deepStrictEqual(between.map((r) => `${r.method} ${isProbe(r.path) ? 'probe' : r.path}`), ['GET probe'], 'one read between them, and nothing else');+ assert.deepStrictEqual(run.clk.waits, [1000], 'one wait before the resend');+ assert.deepStrictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 0, 'no column is sent on its own');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.').map((e) => e.status), ['ok', 'ok']);+ const ids = columnIds(env, 'contoso_ticket');+ assert.deepStrictEqual(run.result.columns.contoso_ticket.map((c) => [c.logicalName, c.metadataId]), [['contoso_title', ids.contoso_title], ['contoso_code', ids.contoso_code]]);+ assert.deepStrictEqual(lagWarnings(run), ['creating the 2 ordinary column(s) of table contoso_ticket in one request was refused just after the table was created (HTTP 400 0x80040216) — checking whether it exists before a bounded retry']);+});++test('the code of a refused change set is read from its first part: a part that names no code does not qualify, whatever its words quote', async () => {+ // Control: the code in the part qualifies (the check reads, and sends the change set again).+ const qualified = await lagEnv();+ qualified.fault('POST', isBatch, (req, n) => (n === 1 ? batchRefused({ code: '0x80040216', message: UNEXPECTED }) : undefined));+ const one = await phase(qualified, lagSpec());+ assert.ifError(one.error);+ assert.strictEqual(posts(one, isBatch).length, 2);+ // The same refusal with the code taken out of the part, its message quoting it (as a display name a maker wrote could): the refusal every other+ // refused change set is — the columns go one by one, with no read of the lag kind and no resend.+ const env = await lagEnv();+ env.fault('POST', isBatch, (req, n) => (n === 1 ? batchRefused({ message: 'The column 0x80040216 Title could not be created.' }) : undefined));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.strictEqual(posts(run, isBatch).length, 1, 'not sent again');+ assert.deepStrictEqual(probes(run).length, 0, 'no read');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'created on its own, as any refused change set is');+ assert.deepStrictEqual(lagWarnings(run), []);+ assert.ok(run.warnings.some((w) => /could not create the 2 ordinary column\(s\) of table contoso_ticket in one request .* — creating them one by one/.test(w)), JSON.stringify(run.warnings));+});++test('a change set refused with the lag whose reads never prove anything stops the build at the end of its budget — no column is sent on its own, the first missing one stops it, and the halt says the build may be run again', async () => {+ const env = await lagEnv();+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+ // Every read answers that the table is not there yet; one of them takes time of its own (a slow answer, 33 s), with no wait around it.+ const clk = clock();+ env.fault('GET', isProbe, (req, n) => { if (n === 2) clk.advance(33000); return odata(404, { code: '0x80060888', message: 'Resource not found for the segment.' }); });+ const run = await phase(env, lagSpec(), { clk });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, isBatch).length, 1, 'the change set is not sent again');+ assert.strictEqual(posts(run, (w) => /\/Attributes$/.test(w)).length, 0, 'and no column is sent on its own');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.').map((e) => `${e.label} ${e.status}`), ['column contoso_ticket.contoso_title (Text) error'], 'the first column the check did not confirm stops the phase');+ assert.ok(halt.message.endsWith(SUFFIX), halt.message);+ assert.strictEqual(halt.retry, 'never', 'a 400 is final: the build does not run again by itself');+ assert.ok(run.clk.now() - 1000000 >= 60000 - 8000, 'the budget was spent: the next wait would have run past it');+ assert.strictEqual(probes(run).length, 6, 'six reads — the slow one among them — and no seventh: the time, not the reads\' cap, ended it');+});++test('a read that shows some columns and not the table\'s own name column proves nothing of the others: none of them is sent until a read proves it absent — and only while the budget has room', async () => {+ const A = 'contoso_title';+ const B = 'contoso_code';+ const someId = '11111111-2222-4333-8444-555555555555';+ // A read with A and nothing else: no proof about B.+ const onlyA = list([{ LogicalName: A, MetadataId: someId }]);+ // (1) That read until the budget is spent: A is adopted, B is never sent, and the build stops at B.+ {+ const env = await lagEnv();+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+ env.fault('GET', isProbe, () => onlyA);+ const run = await phase(env, lagSpec());+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', B)).length, 0, 'B is never sent while nothing proves it absent');+ assert.strictEqual(posts(run, isBatch).length, 1);+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.').map((e) => `${e.label} ${e.status}`), ['column contoso_ticket.contoso_title (Text) ok', 'column contoso_ticket.contoso_code (Text) error']);+ assert.ok(halt.message.endsWith(SUFFIX));+ }+ // (2) A later read that holds the name column and not B proves B absent: B is sent once, A is not sent.+ {+ const env = await lagEnv();+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+ env.fault('GET', isProbe, (req, n) => (n === 1 ? onlyA : (n === 2 ? list([{ LogicalName: A, MetadataId: someId }, { LogicalName: 'contoso_name', MetadataId: '22222222-2222-4333-8444-555555555555' }]) : undefined)));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', B)).length, 1, 'B is sent once, once a read proves it absent');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', A)).length, 0, 'A is adopted, not sent');+ assert.strictEqual(run.result.columns.contoso_ticket.find((c) => c.logicalName === A).metadataId, someId);+ }+ // (3) The first read holds the name column and A, not B: B is proved absent at once, and is the only column sent.+ {+ const env = await lagEnv();+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+ env.fault('GET', isProbe, (req, n) => (n === 1 ? list([{ LogicalName: A, MetadataId: someId }, { LogicalName: 'contoso_name', MetadataId: '22222222-2222-4333-8444-555555555555' }]) : undefined));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.deepStrictEqual(posts(run, (w) => /\/Attributes$/.test(w)).map((r) => JSON.parse(r.body).SchemaName), [B], 'only B is sent');+ assert.strictEqual(posts(run, isBatch).length, 1, 'and the change set is not sent again: part of it is there');+ }+});++test('a proof of absence that comes when the budget is spent sends nothing: not the change set again, not a column on its own — and the halt is the original refusal', async () => {+ const sentinel = { LogicalName: 'contoso_name', MetadataId: '22222222-2222-4333-8444-555555555555' };+ const A = 'contoso_title';+ const cases = [+ // The read that proves every column absent takes the rest of the time.+ ['the proof comes on the read that spends the time', (clk) => (req, n) => (n < 2 ? odata(404, { code: '0x80060888', message: 'not yet' }) : (clk.advance(61000), list([sentinel])))],+ // Eight reads that prove nothing but the last: the eighth is the last the budget has, with time left.+ ['the proof comes on the eighth read', () => (req, n) => (n < 8 ? list([]) : list([sentinel]))],+ // A found, B proved absent, on the read that spends the time.+ ['a part found and the rest proved absent on the read that spends the time', (clk) => (req, n) => (n < 2 ? odata(404, { code: '0x80060888', message: 'not yet' }) : (clk.advance(61000), list([sentinel, { LogicalName: A, MetadataId: '11111111-2222-4333-8444-555555555555' }])))],+ ];+ for (const [what, reads] of cases) {+ const env = await lagEnv();+ const clk = clock();+ // The eighth read comes before the time is spent only when the reads in between are quick: the waits are, here, short enough.+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80040216', message: UNEXPECTED }));+ env.fault('GET', isProbe, reads(clk));+ const run = await phase(env, lagSpec(), { clk: what.includes('eighth') ? { ...clk, sleep: async (ms) => { clk.waits.push(ms); clk.advance(1); } } : clk });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, isBatch).length, 1, `${what}: not sent again`);+ assert.strictEqual(posts(run, (w) => /\/Attributes$/.test(w)).length, 0, `${what}: no column sent on its own`);+ assert.ok(halt.message.endsWith(SUFFIX), `${what}: ${halt.message}`);+ assert.strictEqual(halt.cause.statusCode, 400, `${what}: the original refusal`);+ assert.ok(String(halt.cause.cause).includes('{"error":{"code":"0x80040216"'), `${what}: the change set's own answer, which holds the code in its first part`);+ assert.strictEqual(halt.retry, 'never', what);+ if (what.includes('part found')) {+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.').map((e) => `${e.label} ${e.status}`), ['column contoso_ticket.contoso_title (Text) ok', 'column contoso_ticket.contoso_code (Text) error'], `${what}: the column found is adopted, the missing one stops the phase`);+ }+ if (what.includes('eighth')) assert.strictEqual(probes(run).length, 8, `${what}: eight reads, and no ninth`);+ }+});++test('the columns of a refused change set that a read proved absent are created one by one only while the table\'s budget has room: once it is spent — by a read, by the reads\' cap or by those creates themselves — the phase stops at the next column, with the change set\'s refusal, and sends nothing more', async () => {+ const titleSteps = (run) => steps(run, 'column contoso_ticket.').map((e) => `${e.label} ${e.status}`);+ const stopped = ['column contoso_ticket.contoso_title (Text) ok', 'column contoso_ticket.contoso_code (Text) error'];+ // (1) The time: the read that finds the first column — its own create committed, and its answer was the lag's refusal — takes what is left.+ {+ const env = await lagEnv();+ const clk = clock();+ lagBatch(env);+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), async (req, n) => (n === 1 ? (await env.through(req), refused('0x80040216')) : undefined));+ env.fault('GET', isProbe, (req, n) => { if (n === 3) clk.advance(59000); });+ const run = await phase(env, lagSpec(), { clk });+ changeSetHalt(run, 'the time');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_code')).length, 0, 'the time: the second column is never sent');+ assert.deepStrictEqual(titleSteps(run), stopped, 'the time: the first column is adopted, the second stops the phase');+ assert.strictEqual(probes(run).length, 3);+ }+ // (2) The reads: the third to the seventh prove nothing, and the eighth — the last the budget has — finds the first column.+ {+ const env = await lagEnv();+ const clk = clock();+ lagBatch(env);+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), async (req, n) => (n === 1 ? (await env.through(req), refused('0x80040216')) : undefined));+ env.fault('GET', isProbe, (req, n) => (n >= 3 && n <= 7 ? list([]) : undefined));+ const run = await phase(env, lagSpec(), { clk: { ...clk, sleep: async (ms) => { clk.waits.push(ms); clk.advance(1); } } });+ changeSetHalt(run, 'the reads');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_code')).length, 0, 'the reads: the second column is never sent');+ assert.deepStrictEqual(titleSteps(run), stopped);+ assert.strictEqual(probes(run).length, 8, 'eight reads, and no ninth');+ }+ // (3) The creates: they are the check's own sends, and their time is the budget's. The first read takes 57 s and the first column's create 2 s.+ {+ const env = await lagEnv();+ const clk = clock();+ lagBatch(env);+ env.fault('GET', isProbe, (req, n) => { if (n === 1) clk.advance(57000); });+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => { clk.advance(2000); });+ const run = await phase(env, lagSpec(), { clk });+ changeSetHalt(run, 'the creates');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'the creates: the first column was created');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_code')).length, 0, 'the creates: the second, started when the budget was spent, was not');+ assert.deepStrictEqual(titleSteps(run), stopped);+ }+ // Control: the same fallback, with the budget to spare, creates each column once.+ {+ const env = await lagEnv();+ lagBatch(env);+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.deepStrictEqual(posts(run, (w) => /\/Attributes$/.test(w)).map((r) => JSON.parse(r.body).SchemaName), ['contoso_title', 'contoso_code']);+ const ids = columnIds(env, 'contoso_ticket');+ assert.deepStrictEqual(run.result.columns.contoso_ticket.map((c) => [c.logicalName, c.metadataId !== undefined]), [['contoso_title', true], ['contoso_code', true]]);+ assert.ok(ids.contoso_title && ids.contoso_code);+ }+});++// --- one column on its own -------------------------------------------------------------------------------------------------------------------------------++test('a column refused with the lag of its new table is sent again only after a read proves it absent — and its step is ok, with its id', async () => {+ const env = await lagEnv();+ const answers = [];+ const createColumn = env.sdk.createColumn.bind(env.sdk);+ env.sdk.createColumn = async (...a) => { const answer = await createColumn(...a); answers.push(answer); return answer; };+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), (req, n) => (n === 1 ? refused('0x80040216') : undefined));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(run.error);+ const sent = posts(run, columnPost('contoso_ticket', 'contoso_title'));+ assert.strictEqual(sent.length, 2, 'sent again, once');+ const between = run.wire.slice(run.wire.indexOf(sent[0]) + 1, run.wire.indexOf(sent[1]));+ assert.deepStrictEqual(between.map((r) => `${r.method} ${isProbe(r.path) ? 'probe' : r.path}`), ['GET probe'], 'after one read, and nothing else');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['ok']);+ assert.strictEqual(answers.length, 2, 'the refused create answered nothing; the resend and the other column did');+ assert.strictEqual(run.result.columns.contoso_ticket.find((c) => c.logicalName === 'contoso_title').metadataId, answers[0].metadataId, 'the id the resend\'s create answered');+ assert.deepStrictEqual(lagWarnings(run), ['creating column contoso_ticket.contoso_title was refused just after the table was created (HTTP 400 0x80040216) — checking whether it exists before a bounded retry']);+});++test('a column the read shows after its refusal is adopted with the id the read gives — not sent again', async () => {+ const env = await lagEnv();+ // The create committed, and its answer was the refusal.+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), async (req, n) => (n === 1 ? (await env.through(req), refused('0x80040216')) : undefined));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(run.error);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'not sent again');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['ok']);+ assert.strictEqual(run.result.columns.contoso_ticket.find((c) => c.logicalName === 'contoso_title').metadataId, columnIds(env, 'contoso_ticket').contoso_title);+ assert.ok(run.warnings.includes('column contoso_ticket.contoso_title was refused (HTTP 400 0x80040216) and then found on the table, so it is reused'), JSON.stringify(run.warnings));+});++test('a different refusal of the column sent again is not sent again: it is the failure, final as any 400', async () => {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), (req, n) => (n === 1 ? refused('0x80040216') : refused('0x80040203', 'Invalid argument.')));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 2, 'the original, and one resend');+ assert.strictEqual(serviceCodeOf(halt.cause), '0x80040203', 'the halt is the second answer');+ assert.strictEqual(halt.retry, 'never');+ assert.ok(!halt.message.endsWith(SUFFIX), 'and it is not the refusal the check ran out on');+});++test('a column whose reads answer 404 until the budget is spent is not sent again — the halt says the build may be run again; the error the step reports does not', async () => {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80090457', NOT_THERE));+ env.fault('GET', isProbe, () => odata(404, { code: '0x80060888', message: 'Resource not found for the segment.' }));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'no second create');+ assert.ok(halt.message.endsWith(SUFFIX), halt.message);+ assert.ok(halt.message.includes(NOT_THERE), 'the halt quotes the refusal');+ assert.strictEqual(serviceCodeOf(halt.cause), '0x80090457', 'and carries it');+ assert.ok(!halt.cause.message.includes('persisted'), 'the SDK\'s error is as the SDK made it');+ const failed = run.events.find((e) => e.status === 'error');+ assert.ok(failed && failed.detail === halt.cause.message, 'the step reports the SDK\'s error as it is');+ assert.ok(!failed.detail.includes('persisted'), 'with nothing added');+ assert.strictEqual(halt.retry, 'never', 'the original refusal decides: a 400 is final');+ assert.strictEqual(retryPolicyFor(halt.cause), 'never');+ assert.strictEqual(isTransientHalt(halt), false);+ assert.deepStrictEqual(run.clk.waits, [1000, 2000, 4000, 8000, 8000, 8000, 8000], 'the reads were spaced — 1, 2, 4 and then 8 s — until the eighth, the last the budget allows');+ assert.strictEqual(probes(run).length, 8);+});++test('a column whose reads prove it absent, refused with the lag every time, is sent again four times and then stops the build — not a skip', async () => {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80040216'));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 5, 'the original and four resends');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['error'], 'an error, not a skip');+ assert.ok(halt.message.endsWith(SUFFIX));+ assert.strictEqual(halt.retry, 'never');+});++test('a read of the columns that fails — a 403, a 400 that is not the lag, a 503, a timeout of the transport — sends nothing more, and the halt is that failure', async () => {+ const cases = [+ ['a 403', () => odata(403, { code: '0x80040220', message: 'Principal user is missing prvReadEntity privilege.' }), (h) => h.cause.statusCode === 403 && h.retry === 'never'],+ ['a 400 that is not the lag', () => odata(400, { code: '0x80040203', message: 'Invalid argument.' }), (h) => h.cause.statusCode === 400 && h.retry === 'never'],+ // A 503 keeps its status, so the build's own retry runs the build again for it, as for any 503.+ ['a 503', () => ({ statusCode: 503, headers: { 'content-type': 'text/plain' }, body: 'Service Unavailable' }), (h) => h.cause.statusCode === 503 && h.retry === 'service'],+ ['a timeout of the transport', () => ({ error: 'connect ETIMEDOUT', code: 'ETIMEDOUT' }), (h) => /ETIMEDOUT/.test(h.cause.message) && h.retry === 'service'],+ ];+ for (const [what, answer, check] of cases) {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80040216'));+ env.fault('GET', isProbe, answer);+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, `${what}: nothing sent again`);+ assert.notStrictEqual(serviceCodeOf(halt.cause), '0x80040216', `${what}: the halt is not the refusal`);+ assert.ok(check(halt), `${what}: ${halt.message} (${halt.retry})`);+ assert.ok(!halt.message.endsWith(SUFFIX), what);+ }+});++test('a read that names the column without its id proves nothing — the column is neither adopted nor sent again: a later read with its id adopts it, and a budget spent without one stops the build with the original refusal', async () => {+ // (1) Its own create committed and was answered with the lag's refusal; the first read names it without an id, the second with one.+ {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), async (req, n) => (n === 1 ? (await env.through(req), refused('0x80040216')) : undefined));+ env.fault('GET', isProbe, (req, n) => (n === 1 ? reworked(env, withoutIdOf('contoso_title'))(req) : undefined));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(run.error);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'never sent again');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['ok']);+ assert.strictEqual(run.result.columns.contoso_ticket.find((c) => c.logicalName === 'contoso_title').metadataId, columnIds(env, 'contoso_ticket').contoso_title, 'with the id the second read gave');+ assert.strictEqual(probes(run).length, 2);+ }+ // (2) Every read names it without an id: nothing is sent again, and the budget's end stops the build.+ {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), async (req, n) => (n === 1 ? (await env.through(req), refused('0x80040216')) : undefined));+ env.fault('GET', isProbe, (req) => reworked(env, withoutIdOf('contoso_title'))(req));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'never sent again');+ assert.ok(halt.message.endsWith(SUFFIX), halt.message);+ assert.strictEqual(serviceCodeOf(halt.cause), '0x80040216');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['error']);+ }+ // (3) A row that names no column at all could be this column: the read proves nothing, and the create is sent again only after a read that does.+ {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), (req, n) => (n === 1 ? refused('0x80040216') : undefined));+ env.fault('GET', isProbe, (req, n) => (n === 1 ? reworked(env, (rows) => [...rows, { MetadataId: '44444444-0000-4000-8000-000000000001' }])(req) : undefined));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(run.error);+ const sent = posts(run, columnPost('contoso_ticket', 'contoso_title'));+ assert.strictEqual(sent.length, 2, 'sent again, once');+ const between = run.wire.slice(run.wire.indexOf(sent[0]) + 1, run.wire.indexOf(sent[1]));+ assert.deepStrictEqual(between.map((r) => `${r.method} ${isProbe(r.path) ? 'probe' : r.path}`), ['GET probe', 'GET probe'], 'after the read that proved it absent, not the one before it');+ }+});++test('a change set\'s column that a read names without its id is neither created on its own nor sent again in the change set: a later read with its id adopts it, and a budget spent without one stops the phase at it', async () => {+ // The change set committed, and its answer was the lag's refusal.+ const committed = (env) => env.fault('POST', isBatch, async (req, n) => (n === 1 ? (await env.through(req), batchRefused({ code: '0x80040216', message: UNEXPECTED })) : undefined));+ // (1) The first read names the first column without an id, and shows the second; the next read shows both.+ {+ const env = await lagEnv();+ committed(env);+ env.fault('GET', isProbe, (req, n) => (n === 1 ? reworked(env, withoutIdOf('contoso_title'))(req) : undefined));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.strictEqual(posts(run, isBatch).length, 1, 'the change set is not sent again');+ assert.strictEqual(posts(run, (w) => /\/Attributes$/.test(w)).length, 0, 'and no column is sent on its own');+ const ids = columnIds(env, 'contoso_ticket');+ assert.deepStrictEqual(run.result.columns.contoso_ticket.map((c) => [c.logicalName, c.metadataId]), [['contoso_title', ids.contoso_title], ['contoso_code', ids.contoso_code]]);+ }+ // (2) Every read names the first column without an id: the second is adopted, nothing is sent, and the budget's end stops the phase at the first.+ {+ const env = await lagEnv();+ committed(env);+ env.fault('GET', isProbe, (req) => reworked(env, withoutIdOf('contoso_title'))(req));+ const run = await phase(env, lagSpec());+ changeSetHalt(run, 'never an id');+ assert.strictEqual(posts(run, isBatch).length, 1);+ assert.strictEqual(posts(run, (w) => /\/Attributes$/.test(w)).length, 0, 'no column is sent on its own');+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.').map((e) => `${e.label} ${e.status}`), ['column contoso_ticket.contoso_title (Text) error']);+ }+});++// --- the status reasons ------------------------------------------------------------------------------------------------------------------------------------++// The table the status reason waits for, and after it in the phase: a table whose column and key are labelled in two languages, and a relationship whose+// lookup is too — the creates a label-bearing read must not come before.+const statusSpec = (reason = { label: 'In Review', state: 'Active' }) => lagSpec([+ ticket({ statusReasons: [reason] }),+ {+ schemaName: 'contoso_task', displayName: 'Task', pluralName: 'Tasks', primaryAttribute: { schemaName: 'contoso_title', displayName: 'Title' },+ columns: [{ schemaName: 'contoso_code', displayName: { 1033: 'Code', 3082: 'Código' }, type: 'Text' }],+ alternateKeys: [{ schemaName: 'contoso_codekey', displayName: { 1033: 'Code Key', 3082: 'Clave' }, columns: ['contoso_code'] }],+ },+], [{ type: 'OneToMany', referenced: 'contoso_ticket', referencing: 'contoso_task', lookup: { schemaName: 'contoso_TicketId', displayName: { 1033: 'Ticket', 3082: 'Entrada' } } }]);++test('a status reason refused with the lag of its new table is read and inserted again only after every other labelled create of the phase', async () => {+ const env = await lagEnv();+ env.fault('POST', isInsert, (req, n) => (n === 1 ? refused('0x80090457', NOT_THERE) : undefined));+ const run = await phase(env, statusSpec());+ assert.ifError(run.error);+ const reads = run.wire.filter((r) => r.method === 'GET' && STATUS_READ.test(r.path));+ assert.strictEqual(reads.length, 1, 'one read of the status reasons');+ const inserts = posts(run, isInsert);+ const labelled = run.wire.slice(run.wire.indexOf(inserts[0]) + 1).filter((r) => r.method === 'POST' && (r.path === '/EntityDefinitions' || isBatch(r.path) || /\/(Attributes|Keys)$/.test(r.path) || r.path === '/RelationshipDefinitions'));+ assert.deepStrictEqual([...new Set(labelled.map((r) => (/\/Keys$/.test(r.path) ? 'key' : r.path === '/RelationshipDefinitions' ? 'relationship' : isBatch(r.path) ? 'columns' : r.path === '/EntityDefinitions' ? 'table' : 'column')))].sort(), ['columns', 'key', 'relationship', 'table'], 'the later labelled creates were sent after the refusal');+ assert.ok(run.wire.indexOf(reads[0]) > run.wire.indexOf(labelled[labelled.length - 1]), 'the read comes after every one of them');+ assert.ok(!run.wire.slice(0, run.wire.indexOf(labelled[labelled.length - 1])).some((r) => r.method === 'GET' && /StatusAttributeMetadata/.test(r.path)), 'and no read of the status options before them');+ assert.strictEqual(inserts.length, 2, 'the original and one insert after the read');+ assert.ok(run.wire.indexOf(inserts[1]) > run.wire.indexOf(reads[0]));+ assert.deepStrictEqual(steps(run, 'status reason contoso_ticket: In Review').map((e) => `${e.label} ${e.status}`), [+ 'status reason contoso_ticket: In Review (refused just after the table was created — retrying after the other schema creates) skip',+ 'status reason contoso_ticket: In Review (retried after the other schema creates) ok',+ ]);+ assert.deepStrictEqual(run.result.statusReasonValues.contoso_ticket['In Review'], { value: 100000000, stateCode: 0 });+ // The later creates kept both of their languages: the column, the key and the relationship's lookup.+ const task = [...env.org.metadata.tables.values()].find((t) => t.LogicalName === 'contoso_task');+ const languages = (component) => component.DisplayName.LocalizedLabels.map((l) => l.LanguageCode).sort();+ assert.deepStrictEqual(languages(task.Attributes.get('contoso_code')), [1033, 3082], 'the column');+ assert.deepStrictEqual(languages(task.Keys.get('contoso_codekey')), [1033, 3082], 'the key');+ assert.deepStrictEqual(languages(task.Attributes.get('contoso_ticketid')), [1033, 3082], 'the lookup');+});++test('a status reason the read shows is adopted when its value, state, label and declared colour are the spec\'s — and a declared colour that differs stops the build, with nothing inserted, adopted or changed', async () => {+ const option = (color) => ({ Value: 100000000, State: 0, Label: { LocalizedLabels: [{ Label: 'In Review', LanguageCode: 1033 }] }, Color: color });+ const stock = { Value: 1, State: 0, Label: { LocalizedLabels: [{ Label: 'Active', LanguageCode: 1033 }] }, Color: null };+ const statusList = (opt) => list([{ LogicalName: 'statuscode', OptionSet: { Options: [stock, opt] } }]);+ for (const [what, reason, held, adopted] of [+ ['the declared colour', { label: 'In Review', state: 'Active', color: '#336699' }, '#336699', true],+ ['another colour than the declared one', { label: 'In Review', state: 'Active', color: '#336699' }, '#ff0000', false],+ ['no declared colour', { label: 'In Review', state: 'Active' }, '#ff0000', true],+ ]) {+ const env = await lagEnv();+ env.fault('POST', isInsert, () => refused('0x80090457', NOT_THERE));+ env.fault('GET', (w) => STATUS_READ.test(w), () => statusList(option(held)));+ const run = await phase(env, lagSpec([ticket({ statusReasons: [reason] })]));+ assert.strictEqual(posts(run, isInsert).length, 1, `${what}: no second insert`);+ if (adopted) {+ assert.ifError(run.error);+ assert.ok(run.warnings.includes('status reason contoso_ticket: In Review was refused (HTTP 400 0x80090457) and then found, so it is reused'), `${what}: ${JSON.stringify(run.warnings)}`);+ } else {+ const halt = haltOf(run);+ assert.strictEqual(serviceCodeOf(halt.cause), '0x80090457', `${what}: the original refusal`);+ assert.ok(!halt.message.endsWith(SUFFIX), `${what}: the option there is another reason's, not a refusal that ran out`);+ assert.ok(!run.warnings.some((w) => /then found/.test(w)), `${what}: not adopted`);+ }+ assert.strictEqual(run.wire.filter((r) => ['PUT', 'PATCH', 'DELETE'].includes(r.method)).length, 0, `${what}: nothing changed`);+ }+});++test('a read of the status reasons proves the reason absent only when every option carries its value once: an option without one, or the pinned value held twice, proves nothing, and the insert is sent again only after a read that does', async () => {+ const stock = { Value: 1, State: 0, Label: { LocalizedLabels: [{ Label: 'Active', LanguageCode: 1033 }] }, Color: null };+ const inReview = (label) => ({ Value: 100000000, State: 0, Label: { LocalizedLabels: [{ Label: label, LanguageCode: 1033 }] }, Color: null });+ for (const [what, options] of [+ ['an option whose value is not a number', [stock, { ...inReview('In Review'), Value: '100000000' }]],+ ['the pinned value held twice', [stock, inReview('In Review'), inReview('Another')]],+ ]) {+ const env = await lagEnv();+ env.fault('POST', isInsert, (req, n) => (n === 1 ? refused('0x80090457', NOT_THERE) : undefined));+ env.fault('GET', (w) => STATUS_READ.test(w), (req, n) => (n === 1 ? list([{ LogicalName: 'statuscode', OptionSet: { Options: options } }]) : undefined));+ const run = await phase(env, lagSpec([ticket({ statusReasons: [{ label: 'In Review', state: 'Active' }] })]));+ assert.ifError(run.error);+ const reads = run.wire.filter((r) => r.method === 'GET' && STATUS_READ.test(r.path));+ const inserts = posts(run, isInsert);+ assert.strictEqual(reads.length, 2, `${what}: read again`);+ assert.strictEqual(inserts.length, 2, `${what}: the original, and one insert`);+ assert.ok(run.wire.indexOf(inserts[1]) > run.wire.indexOf(reads[1]), `${what}: after the read that proved it absent`);+ assert.ok(!run.warnings.some((w) => /then found/.test(w)), `${what}: nothing adopted`);+ }+});++test('the status reason taken up again at the end of the phase keeps the number it was deferred under: every step is numbered within the total, and the summary counts that step once, by the outcome it ended with', async () => {+ const spec = lagSpec([ticket({ statusReasons: [{ label: 'In Review', state: 'Active' }] })]);+ // The phase over the fake environment as the command runs it — its steps numbered against `total` and printed by the command's own printer+ // (buildModelApp's), which also prints the summary.+ const build = async (env, total) => {+ const lines = [];+ const r = await buildModelApp(spec, { apply: true, workspaceDir: makeTempDir('post-create-lag-steps-') }, {+ log: (m) => lines.push(String(m)),+ runBuild: async (s, o) => {+ await provisionDataModel({+ sdk: env.sdk, provision: env.sdk, runner: makeRunner({ emit: o.emit, total }), spec: s, apply: true, preResolvedLanguageCode: 1033,+ provisionedLanguages: async () => [1033], sleep: async () => {}, now: () => 0, random: () => 0, warn: () => {},+ });+ return { ok: true, dryRun: false, created: {} };+ },+ });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ const stepLines = lines.filter((l) => /^ {2}\[\d+\/\d+\] /.test(l));+ return { stepLines, numbers: stepLines.map((l) => Number(/^ {2}\[(\d+)\//.exec(l)[1])), summary: lines.find((l) => l.includes('build complete')) };+ };+ // The phase with nothing refused: the steps the plan counts for it.+ const plain = await build(await lagEnv(), 0);+ const total = plain.stepLines.length;+ // The same phase on a new environment whose platform refuses the status reason's first insert with the table's lag.+ const env = await lagEnv();+ env.fault('POST', isInsert, (req, n) => (n === 1 ? refused('0x80090457', NOT_THERE) : undefined));+ const lag = await build(env, total);+ const deferred = lag.stepLines.find((l) => l.includes('status reason contoso_ticket: In Review (refused just after the table was created'));+ const retried = lag.stepLines.find((l) => l.includes('status reason contoso_ticket: In Review (retried after the other schema creates)'));+ assert.ok(deferred && retried, lag.stepLines.join('\n'));+ const numberOf = (line) => /^ {2}\[(\d+\/\d+)\]/.exec(line)[1];+ assert.strictEqual(numberOf(retried), numberOf(deferred), 'the retried step keeps the number it was deferred under');+ assert.ok(lag.numbers.every((n) => n >= 1 && n <= total), `every step within the total ${total}: ${lag.numbers}`);+ assert.deepStrictEqual([...new Set(lag.numbers)].sort((a, b) => a - b), Array.from({ length: total }, (_, i) => i + 1), 'each step of the plan, once');+ assert.ok(lag.stepLines.every((l) => l.includes(`/${total}] `)), 'against the plan\'s total');+ assert.strictEqual(lag.summary, plain.summary, 'the summary counts the status reason once, as created — as when nothing was refused');+ assert.ok(retried.startsWith(` [${numberOf(deferred)}] ✓ status reason contoso_ticket: In Review (retried after the other schema creates)`), retried);+});++// --- one budget per table ----------------------------------------------------------------------------------------------------------------------------------++test('one table\'s budget has room for the recoveries a first build meets on it — its change set\'s and a File column\'s, whose resends take 8 s and 25 s, as measured live — and still reads and recovers its status reason at the end of the phase', async () => {+ const env = await lagEnv();+ const clk = clock();+ const fileColumn = { schemaName: 'contoso_doc', displayName: 'Document', type: 'File', maxSizeKb: 1024 };+ // The change set is refused once; sent again, it takes 8 s and commits.+ env.fault('POST', isBatch, (req, n) => (n === 1 ? batchRefused({ code: '0x80040216', message: UNEXPECTED }) : (clk.advance(8000), undefined)));+ // The File column, created on its own, is refused once; sent again, it takes 25 s and is created.+ env.fault('POST', columnPost('contoso_ticket', 'contoso_doc'), (req, n) => (n === 1 ? refused('0x80040216') : (clk.advance(25000), undefined)));+ // The status reason's insert is refused once, as the platform answers one for a table it has just created.+ env.fault('POST', isInsert, (req, n) => (n === 1 ? refused('0x80090457', NOT_THERE) : undefined));+ const run = await phase(env, lagSpec([ticket({ columns: [...ticket().columns, fileColumn], statusReasons: [{ label: 'In Review', state: 'Active' }] })]), { clk });+ assert.ifError(run.error);+ assert.strictEqual(posts(run, isBatch).length, 2, 'the change set was sent again once');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_doc')).length, 2, 'the File column was sent again once');+ assert.strictEqual(run.wire.filter((r) => r.method === 'GET' && STATUS_READ.test(r.path)).length, 1, 'the status reason was read at the end of the phase');+ assert.strictEqual(posts(run, isInsert).length, 2, 'and inserted again once');+ assert.deepStrictEqual(steps(run, 'status reason contoso_ticket: In Review').map((e) => e.status), ['skip', 'ok']);+ assert.ok(run.clk.now() - 1000000 > 35000, `control: the two recoveries spent more than 35 s of the table's budget (${run.clk.now() - 1000000} ms)`);+});++test('one table\'s change set, its columns on their own and its status reasons share one budget; another table has its own; and a throttle the HTTP client waits out is not one of the check\'s resends', async () => {+ // The change set's check spends 55 seconds: three reads that prove nothing — the first of which takes 40 s — and waits of 1, 2 and 4 s between+ // them, then a proof, a wait of 8 s and the resend that commits it.+ const spendOnBatch = (env, clk) => {+ env.fault('POST', isBatch, (req, n) => (n === 1 ? batchRefused({ code: '0x80040216', message: UNEXPECTED }) : undefined));+ let reads = 0;+ env.fault('GET', isProbe, () => { reads += 1; if (reads === 1) clk.advance(40000); return reads <= 3 ? odata(404, { code: '0x80060888', message: 'not yet' }) : undefined; });+ };+ const fileColumn = { schemaName: 'contoso_doc', displayName: 'Document', type: 'File', maxSizeKb: 1024 };+ // The same table's File column, created on its own after the change set and refused with the lag every time, reads only what is left: 5 seconds —+ // two reads, after waits of 1 s and 2 s; the next wait (4 s) would run past the budget.+ {+ const env = await lagEnv();+ const clk = clock();+ spendOnBatch(env, clk);+ let docRefused = false;+ env.fault('POST', columnPost('contoso_ticket', 'contoso_doc'), () => { docRefused = true; return refused('0x80040216'); });+ env.fault('GET', isProbe, () => (docRefused ? odata(404, { code: '0x80060888', message: 'not yet' }) : undefined));+ const run = await phase(env, lagSpec([ticket({ columns: [...ticket().columns, fileColumn] })]), { clk });+ const halt = haltOf(run);+ assert.ok(halt.message.endsWith(SUFFIX));+ assert.deepStrictEqual(run.clk.waits, [1000, 2000, 4000, 8000, 1000, 2000], 'the File column\'s check waited only what the change set\'s left');+ }+ // Another table's File column has a budget of its own: four waits before it stops.+ {+ const env = await lagEnv();+ const clk = clock();+ spendOnBatch(env, clk);+ const other = { schemaName: 'contoso_note', displayName: 'Note', pluralName: 'Notes', primaryAttribute: { schemaName: 'contoso_subject', displayName: 'Subject' }, columns: [fileColumn] };+ env.fault('POST', columnPost('contoso_note', 'contoso_doc'), () => refused('0x80040216'));+ const run = await phase(env, lagSpec([ticket(), other]), { clk });+ const halt = haltOf(run);+ assert.ok(halt.message.endsWith(SUFFIX));+ assert.deepStrictEqual(run.clk.waits, [1000, 2000, 4000, 8000, 1000, 2000, 4000, 8000], 'the other table waited a whole budget of its own');+ }+ // The status reason of the table whose change set spent 55 seconds: its read at the end of the phase has the same 5 seconds left.+ {+ const env = await lagEnv();+ const clk = clock();+ spendOnBatch(env, clk);+ env.fault('POST', isInsert, () => refused('0x80090457', NOT_THERE));+ env.fault('GET', (w) => STATUS_READ.test(w), () => odata(404, { code: '0x80060888', message: 'not yet' }));+ const run = await phase(env, lagSpec([ticket({ statusReasons: [{ label: 'In Review', state: 'Active' }] })]), { clk });+ haltOf(run);+ assert.strictEqual(run.wire.filter((r) => r.method === 'GET' && STATUS_READ.test(r.path)).length, 3, 'three reads of the status reasons: what the shared budget had left room for');+ }+ // A throttle (429) the HTTP client waits out inside one resend: one resend of the check's, two requests on the wire.+ {+ const env = await lagEnv();+ let calls = 0;+ const createColumn = env.sdk.createColumn.bind(env.sdk);+ env.sdk.createColumn = (logical, options, ...rest) => { if (options && options.schemaName === 'contoso_title') calls += 1; return createColumn(logical, options, ...rest); };+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), (req, n) => (n === 1 ? refused('0x80040216') : (n === 2 ? odata(429, { code: '0x80072322', message: 'Number of requests exceeded the limit.' }) : undefined)));+ const run = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(run.error);+ assert.strictEqual(calls, 2, 'the refused create and one resend by the check');+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_title')).length, 3, 'three requests: the refusal, the throttled one and the one the client sent again');+ }+});++test('a first run whose check runs out stops the build; the next run finds the table and creates the column, with no check and no word of the lag', async () => {+ const env = await lagEnv();+ const lagged = env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80040216'));+ const first = await phase(env, lagSpec(), { inlineColumns: false });+ haltOf(first);+ assert.strictEqual(posts(first, columnPost('contoso_ticket', 'contoso_title')).length, 5, 'the first run read and sent it again until its budget allowed no more');+ assert.ok(probes(first).length >= 5, 'reading before each resend');+ assert.strictEqual(lagWarnings(first).length, 1);+ lagged.lift();+ const rerun = await phase(env, lagSpec(), { inlineColumns: false });+ assert.ifError(rerun.error);+ assert.strictEqual(posts(rerun, columnPost('contoso_ticket', 'contoso_title')).length, 1, 'the rerun creates it once');+ assert.deepStrictEqual(lagWarnings(rerun), [], 'and says nothing of the lag: the table existed');+ assert.deepStrictEqual(rerun.clk.waits, []);+});++// --- what does not change -------------------------------------------------------------------------------------------------------------------------------++test('the same refusal of a column on a table that already existed stops the build at once, as it always did: one create, no read, no wait, no word of the lag', async () => {+ const env = await lagEnv();+ assert.ifError((await phase(env, lagSpec())).error);+ const grown = lagSpec([ticket({ columns: [...ticket().columns, { schemaName: 'contoso_more', displayName: 'More', type: 'Text' }] })]);+ env.fault('POST', columnPost('contoso_ticket', 'contoso_more'), () => refused('0x80040216'));+ const run = await phase(env, grown);+ const halt = haltOf(run);+ assert.strictEqual(posts(run, columnPost('contoso_ticket', 'contoso_more')).length, 1);+ assert.strictEqual(probes(run).length, 0);+ assert.deepStrictEqual(run.clk.waits, []);+ assert.deepStrictEqual(lagWarnings(run), []);+ assert.ok(!halt.message.endsWith(SUFFIX));+});++test('an "already exists" answer is still the skip it was — for a column and for a status reason of a new table — with no read and no wait', async () => {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80047013', 'An attribute with the specified name contoso_title already exists for entity contoso_ticket.'));+ env.fault('POST', isInsert, () => refused('0x80044310', 'The picklist value already exists.'));+ const run = await phase(env, lagSpec([ticket({ statusReasons: [{ label: 'In Review', state: 'Active' }] })]), { inlineColumns: false });+ assert.ifError(run.error);+ assert.deepStrictEqual(steps(run, 'column contoso_ticket.contoso_title').map((e) => e.status), ['skip']);+ assert.deepStrictEqual(steps(run, 'status reason contoso_ticket: In Review').map((e) => `${e.label} ${e.status}`), ['status reason contoso_ticket: In Review (exists) skip']);+ assert.strictEqual(probes(run).length, 0);+ assert.strictEqual(run.wire.filter((r) => STATUS_READ.test(r.path)).length, 0);+ assert.deepStrictEqual(run.clk.waits, []);+ assert.deepStrictEqual(lagWarnings(run), []);+});++test('a build the lag never touches sends what it always did: one read of the columns after the change set, no read of the status reasons before the insert, no wait, no warning', async () => {+ const env = await lagEnv();+ const run = await phase(env, lagSpec([ticket({ statusReasons: [{ label: 'In Review', state: 'Active' }] })]));+ assert.ifError(run.error);+ assert.strictEqual(posts(run, isBatch).length, 1);+ assert.strictEqual(probes(run).length, 1, 'the read that confirms the change set');+ assert.strictEqual(run.wire.filter((r) => /StatusAttributeMetadata/.test(r.path)).length, 0);+ assert.strictEqual(posts(run, isInsert).length, 1);+ assert.deepStrictEqual(run.clk.waits, []);+ assert.deepStrictEqual(run.warnings, []);+});++test('a change set refused with any other 400 is sent once by the HTTP client and created one by one, as before', async () => {+ const env = await lagEnv();+ env.fault('POST', isBatch, () => batchRefused({ code: '0x80060304', message: 'Attribute contoso_title already exists for entity contoso_ticket.' }));+ const run = await phase(env, lagSpec());+ assert.ifError(run.error);+ assert.strictEqual(posts(run, isBatch).length, 1);+ assert.strictEqual(probes(run).length, 0, 'no read of the lag kind');+ assert.deepStrictEqual(posts(run, (w) => /\/Attributes$/.test(w)).map((r) => JSON.parse(r.body).SchemaName), ['contoso_title', 'contoso_code']);+});++// --- what is printed, and when ----------------------------------------------------------------------------------------------------------------------------++test('a refusal the check ran out on says the build may be run again only in the halt the command prints after its build lease is let go — the step printed the SDK\'s error, with nothing added, while the lease was held', async () => {+ const env = await lagEnv();+ env.fault('POST', columnPost('contoso_ticket', 'contoso_title'), () => refused('0x80090457', NOT_THERE));+ env.fault('GET', isProbe, () => odata(404, { code: '0x80060888', message: 'Resource not found for the segment.' }));+ const spec = lagSpec();+ const folder = appFolder(spec);+ const clk = clock();+ let atError = null;+ // The build command over its real modules (helpers/build-command-harness.js), its engine the data-model phase over the fake environment, whose steps+ // the command's own printer prints (the `emit` buildModelApp hands the engine).+ const run = command(folder, {+ engine: async (held, o) => {+ const emit = (e) => { o.emit(e); if (e.status === 'error') atError = { held: held(), stderr: run.cli.stderrText() }; };+ await provisionDataModel({+ sdk: env.sdk, provision: env.sdk, runner: makeRunner({ emit, total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033,+ provisionedLanguages: async () => [1033], sleep: clk.sleep, now: clk.now, random: () => 0, warn: o.warn, inlineColumns: false,+ });+ return { ok: true, dryRun: false, created: {} };+ },+ });+ const outcome = await settle(run);+ const halt = outcome.thrown;+ assert.ok(halt instanceof BuildHalt, JSON.stringify(outcome));+ // While the lease was held: the step's failure, printed as the SDK made it.+ assert.ok(atError && atError.held, 'the step failed while the lease was held');+ assert.ok(atError.stderr.includes(`✗ column contoso_ticket.contoso_title (Text) — ${halt.cause.message}\n`), atError.stderr);+ assert.ok(!run.cli.stderrText().includes('persisted') && !run.cli.stdoutText().includes('persisted'), 'nothing the command printed under the lease says more');+ // After it: the halt main().catch prints, which does.+ assert.strictEqual(outcome.heldThen, false, 'the lease was let go before the halt reached main().catch');+ assert.ok(halt.message.endsWith(SUFFIX), halt.message);+ assert.throws(() => run.authCli.exports.emitResult(false, halt), (e) => e.exitCode === 1);+ assert.strictEqual(run.authCli.stderrText(), `${halt.message}\n`);+ assert.strictEqual(run.authCli.stdoutText(), '');+ // And the refusal decides what the build does about it: a 400 is final, so the command did not run the build again.+ assert.strictEqual(serviceCodeOf(halt.cause), '0x80090457');+ assert.strictEqual(halt.retry, 'never');+ assert.strictEqual(isTransientHalt(halt), false);+ assert.deepStrictEqual(run.calls.filter((c) => c === 'engine'), ['engine'], 'one run of the phases');+});diff --git a/plugins/model-apps/scripts/tests/prototype-member-names-real-bundle.test.js b/plugins/model-apps/scripts/tests/prototype-member-names-real-bundle.test.jsnew file mode 100644index 000000000..d54651ca3--- /dev/null+++ b/plugins/model-apps/scripts/tests/prototype-member-names-real-bundle.test.js@@ -0,0 +1,171 @@+'use strict';+// The names of prototype-member-names.test.js — `__proto__`, `constructor`, `toString`, `hasOwnProperty` — through a whole build, its verify and+// its teardown: over the REAL vendored SDK, the plugin's own HTTP client and the strict stateful fake of helpers/fake-lifecycle-org.js, as+// lifecycle-matrix-real-bundle.test.js runs the kitchen-sink spec. A name the platform takes is a name the build must take: these are a maker's+// dashboards, a page's key and a table's status reasons, and nothing here is refused for its name.+//+// 1. four dashboards so named, each opened from the app's navigation+// 2. a new app whose navigation holds a table and a page keyed `constructor`: the app is created before its pages, so its first navigation+// leaves the page out, and the pages step adds it+// 3. status reasons so labelled, and the values the data-model phase captures for them+const test = require('node:test');+const assert = require('node:assert/strict');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');+const { makeRunner, provisionDataModel } = require('../lib/entity-provision.js');++const NAMES = ['__proto__', 'constructor', 'toString', 'hasOwnProperty'];+const SOLUTION = 'ContosoNames';+const APP = 'contoso_names';+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+// A map holding each of `names` as its OWN key, as JSON.parse makes it (a plain object literal or assignment cannot hold `__proto__`).+const ownMap = (names, valueOf) => JSON.parse(`{${names.map((name) => `${JSON.stringify(name)}:${JSON.stringify(valueOf(name))}`).join(',')}}`);++function environment() {+ const org = createLifecycleOrg();+ return { org, harness: createLifecycleHarness(org, makeTempDir('proto-names-')) };+}++// A measured step ran: it did not throw, and every request it sent is one the fake models.+function ran(step, label) {+ assert.ok(step, `${label} ran`);+ if (step.error) throw step.error;+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);+ return step;+}+function built(step, label) {+ const { result } = ran(step, label).value;+ assert.equal(result.ok, true, `${label}: ${JSON.stringify(result.errors || result.error)}`);+ assert.deepEqual(result.verify && { ok: result.verify.ok, missing: result.verify.missing }, { ok: true, missing: [] }, `${label}: its own verify finds every artifact`);+ return result;+}++const app = (subAreas, more) => ({+ schemaVersion: 2,+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Names', publisherPrefix: 'contoso' },+ app: { name: 'Names', uniqueName: APP },+ entities: [{ schemaName: 'contact', displayName: 'Contact', existing: true, primaryAttribute: { schemaName: 'fullname', displayName: 'Full Name' }, columns: [] }],+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Work', subAreas: [{ entity: 'contact', title: 'Contacts' }, ...subAreas] }] }] },+ ...more,+});++// The app's navigation as the environment holds it: the attributes of each SubArea, in order. A sitemap's XML, e.g.+// <SiteMap …><Area Id="area_0" …><Group Id="group_0_0" …><SubArea Id="sub_0_0_1" DefaultDashboard="{…}" Url="/main.aspx?pagetype=dashboard…" …>+// Only the SubArea start tags are read, and only the attributes the build writes.+const subAreasOf = (xml) => (String(xml).match(/<SubArea\b[^>]*>/g) || []).map((tag) => Object.fromEntries([...tag.matchAll(/\s([A-Za-z]+)="([^"]*)"/g)].map(([, k, v]) => [k, v])));+const navigation = (org) => {+ const [sitemap] = org.find('sitemaps', (s) => s.sitemapnameunique === APP);+ return sitemap ? subAreasOf(sitemap.sitemapxml) : null;+};+const bare = (id) => String(id || '').replace(/[{}]/g, '').toLowerCase();+const dashboardsNamed = (org, name) => org.find('systemforms', (f) => Number(f.type) === 0 && f.name === name).map((f) => bare(f.formid));+const allDashboards = (org) => org.find('systemforms', (f) => Number(f.type) === 0).map((f) => bare(f.formid));++// --- 1. dashboards ----------------------------------------------------------------------------------------------------------------------------------------++const boards = () => app(NAMES.map((name) => ({ dashboard: name, title: `Board ${name}` })), {+ dashboards: NAMES.map((name) => ({ name, tiles: [{ type: 'iframe', url: 'https://contoso.example/status', name: 'Status' }] })),+});++test('dashboards called __proto__, constructor, toString and hasOwnProperty are built, each opened from the navigation, reused by a rebuild, verified and torn down', async () => {+ const env = environment();+ const result = built(await env.harness.measure(() => env.harness.build(boards())), 'the build');+ const ids = NAMES.map((name) => {+ const rows = dashboardsNamed(env.org, name);+ assert.equal(rows.length, 1, `${name}: one dashboard of this name`);+ return rows[0];+ });+ assert.deepEqual(navigation(env.org).filter((s) => s.DefaultDashboard !== undefined).map((s) => bare(s.DefaultDashboard)), ids, 'each nav entry opens the dashboard of its name, in the spec\'s order');+ assert.equal(JSON.stringify(result.created.dashboards), JSON.stringify(ownMap(NAMES, (name) => ids[NAMES.indexOf(name)])), 'the build result names every dashboard by its name');++ const again = built(await env.harness.measure(() => env.harness.build(boards())), 'the rebuild');+ assert.deepEqual(NAMES.map((name) => dashboardsNamed(env.org, name)), ids.map((id) => [id]), 'the rebuild created no dashboard: each is reused by its name');+ assert.equal(JSON.stringify(again.created.dashboards), JSON.stringify(result.created.dashboards));++ const teardown = ran(await env.harness.measure(() => env.harness.teardown(boards())), 'the teardown');+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));+ assert.deepEqual(allDashboards(env.org), [], 'ALL ABSENT: every dashboard the build made is deleted');+});++// --- 2. a page keyed constructor ------------------------------------------------------------------------------------------------------------------------++// The lifecycle harness writes KitchenPage.tsx into the app folder; the page is built from it.+const withPage = () => app([{ page: 'constructor', title: 'Constructor' }], {+ pages: [{ key: 'constructor', name: 'Constructor', source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }],+});+const sitemapsWritten = (org, mark) => org.since(mark).filter((r) => r.body && typeof r.body === 'object' && typeof r.body.sitemapxml === 'string').map((r) => subAreasOf(r.body.sitemapxml));++test('a new app whose navigation holds a table and a page keyed constructor: its first navigation leaves the page out, the pages step adds it, and verify and teardown find it', async () => {+ const env = environment();+ const step = await env.harness.measure(() => env.harness.build(withPage()));+ const result = built(step, 'the build');+ const pageId = bare(result.created.pages.constructor);+ assert.match(pageId, GUID, 'the page was built, under its key');+ assert.deepEqual(Object.keys(result.created.pages), ['constructor']);+ const written = sitemapsWritten(env.org, step.mark);+ assert.ok(written.length >= 1, 'the build wrote the app\'s navigation');+ assert.deepEqual(written[0].map((s) => (s.Entity ? `Entity ${s.Entity}` : `GenPage ${s.GenPageId}`)), ['Entity contact'], 'the app\'s first navigation leaves out the page it does not have yet — never an entry with no page');+ for (const sitemap of written) for (const s of sitemap) if (s.GenPageId !== undefined) assert.match(s.GenPageId, GUID, 'no navigation the build writes names a page by anything but its id');+ assert.deepEqual(navigation(env.org).map((s) => (s.Entity ? `Entity ${s.Entity}` : `GenPage ${bare(s.GenPageId)}`)), ['Entity contact', `GenPage ${pageId}`], 'the pages step put the page in the navigation');++ const teardown = ran(await env.harness.measure(() => env.harness.teardown(withPage())), 'the teardown');+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));+ assert.equal(navigation(env.org), null, 'ALL ABSENT: the app\'s navigation is gone with the app');+ assert.deepEqual(env.org.find('uxagentprojects', (p) => bare(p.uxagentprojectid) === pageId), [], 'and so is the page');+});++// --- 3. status reasons ----------------------------------------------------------------------------------------------------------------------------------++// The data-model phase alone, over the real SDK and a transport that answers only what this test models: a table that exists, whose status+// reasons cannot be read, so each is inserted. The value an insert is answered with is the one it asked for (the build pins each), as+// POST /InsertStatusValue { "EntityLogicalName": "contoso_project", "AttributeLogicalName": "statuscode", "Value": 100000000, … } -> { "NewOptionValue": 100000000 }+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/insertstatusvalue+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const ORG = 'https://contoso.crm.dynamics.com';+const PROBE = "/EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName";+const COLUMN_LIST = "/EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,RequiredLevel";+const STATUS_READ = "/EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)";+async function dataModel(spec) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const unmodelled = [];+ const inserted = [];+ const send = async (method, url, body) => {+ const asked = decodeURIComponent(String(url)).replace(/^https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d+/, '');+ const reply = (() => {+ if (method === 'GET' && asked === PROBE) return { status: 200, body: { LogicalName: 'contoso_project', EntitySetName: 'contoso_projects' } };+ if (method === 'GET' && asked === COLUMN_LIST) return { status: 200, body: { value: [{ LogicalName: 'contoso_name', RequiredLevel: { Value: 'None' } }] } };+ if (method === 'GET' && asked === STATUS_READ) return { status: 500, body: { error: { code: '0x80040216', message: 'An unexpected error occurred.' } } };+ if (method === 'POST' && asked === '/InsertStatusValue') { inserted.push(body.Label); return { status: 200, body: { NewOptionValue: body.Value } }; }+ return null;+ })();+ if (!reply) {+ unmodelled.push(`${method} ${asked}`);+ throw new Error(`the test does not model ${method} ${asked}`);+ }+ return { status: reply.status, headers: {}, body: reply.body };+ };+ const httpClient = { get: (url) => send('GET', url), post: (url, body) => send('POST', url, body), put: (url, body) => send('PUT', url, body), patch: (url, body) => send('PATCH', url, body), delete: (url) => send('DELETE', url) };+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('proto-names-sdk-')), instanceUrl: ORG, httpClient });+ await sdk.initWorkspace();+ const result = await provisionDataModel({+ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true,+ preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {},+ });+ return { result, unmodelled, inserted };+}++test('status reasons labelled __proto__, constructor, toString and hasOwnProperty are each inserted, and the value of each is kept under its label for the sample data', async () => {+ const spec = {+ solution: { uniqueName: SOLUTION, publisherPrefix: 'contoso' },+ relationships: [],+ entities: [{ schemaName: 'contoso_Project', displayName: 'Project', pluralName: 'Projects', primaryAttribute: { schemaName: 'contoso_Name' }, columns: [], statusReasons: [...NAMES, 'In Review'].map((label) => ({ label, state: 'Active' })) }],+ };+ const { result, unmodelled, inserted } = await dataModel(spec);+ assert.deepEqual(unmodelled, [], 'every request was one the test models');+ assert.deepEqual(inserted.map((label) => label.LocalizedLabels[0].Label), [...NAMES, 'In Review'], 'each reason inserted once, in the spec\'s order');+ const values = result.statusReasonValues.contoso_project;+ assert.deepEqual(Object.keys(values), [...NAMES, 'In Review'], 'each value kept under its own label');+ assert.equal(JSON.stringify(values), JSON.stringify(ownMap([...NAMES, 'In Review'], (label) => ({ value: 100000000 + [...NAMES, 'In Review'].indexOf(label), stateCode: 0 }))));+});diff --git a/plugins/model-apps/scripts/tests/prototype-member-names.test.js b/plugins/model-apps/scripts/tests/prototype-member-names.test.jsnew file mode 100644index 000000000..5b3f48756--- /dev/null+++ b/plugins/model-apps/scripts/tests/prototype-member-names.test.js@@ -0,0 +1,313 @@+'use strict';+// A name a maker writes freely can be exactly a member of Object.prototype: a dashboard, a persona (its security role), a business process+// flow and a status reason called `__proto__`, `constructor`, `toString` or `hasOwnProperty`, a page whose key is `constructor`, a Custom API+// parameter called `constructor` or `toString` (Dataverse refuses a parameter called `__proto__`: its name must begin with a letter). Each is a+// legal name, and the plugin must treat it as one more name.+//+// A plain object `{}` used as a map gets both directions wrong for such a name:+// - a READ of a name nobody stored answers the inherited member — the Object function, a function, the prototype itself — and each is+// truthy, so "was it built?" answers yes and the member is used as the id;+// - a WRITE of `__proto__` calls the inherited prototype setter: the entry is never stored (JSON.stringify leaves it out), and an object+// value becomes the map's prototype.+// These tests hold the maps the plugin builds from such names, and the reads of them, to the plain-name contract: every name is an own+// entry, a name that was not stored reads as absent, and what is written for ordinary names is byte for byte what it was. The same+// tests over the real bundle and a fake environment are in prototype-member-names-real-bundle.test.js.+const test = require('node:test');+const assert = require('node:assert/strict');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { appDef, commandsByEntity, runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);+const { indexArtifacts } = require('../lib/apply-snapshot-index.js');+const flow = require('../lib/changed-only-flow.js');+const snap = require('../lib/apply-snapshot.js');+const { buildSeedGroup, statusReasonTargets } = require('../lib/entity-provision.js');+const { validateAppSpec } = require('../lib/app-spec.js');+const { validateProvisionInput } = require('../lib/provision-input.js');+const { parameterKindsFromRows, toCustomApiEntry } = require('../list-custom-apis.js');++const NAMES = ['__proto__', 'constructor', 'toString', 'hasOwnProperty'];+// A map holding each of `names` as its OWN key, as JSON.parse makes it: a plain object literal cannot (`{ __proto__: x }` and+// `{ '__proto__': x }` both mean the prototype, not an entry), and assigning to a plain object calls the setter.+const ownMap = (names, valueOf) => JSON.parse(`{${names.map((name) => `${JSON.stringify(name)}:${JSON.stringify(valueOf(name))}`).join(',')}}`);+const GUIDS = ['11111111-aaaa-4aaa-8aaa-111111111111', '22222222-bbbb-4bbb-8bbb-222222222222', '33333333-cccc-4ccc-8ccc-333333333333', '44444444-dddd-4ddd-8ddd-444444444444'];+const ID = ownMap(NAMES, (name) => GUIDS[NAMES.indexOf(name)]);+// The JSON a map writes — the bytes a result, a snapshot or a record holds.+const json = (value) => JSON.stringify(value);++// --- the shared reader -------------------------------------------------------------------------------------------------------------------------------------++test('ownValue answers only an entry a map holds: an inherited member is absent, and an own __proto__ key is an entry like any other', () => {+ // Loaded here, so that the other tests of this file fail on their own assertions when the module is not there.+ const { ownValue } = require('../lib/own-keys.js');+ const held = ownMap([...NAMES, 'Ops Overview'], (name) => `id of ${name}`);+ for (const name of [...NAMES, 'Ops Overview']) assert.equal(ownValue(held, name), `id of ${name}`, `${name}: the entry held`);+ for (const name of NAMES) {+ assert.equal(ownValue({}, name), undefined, `${name}: a plain object holds no such entry`);+ assert.equal(ownValue(Object.create(null), name), undefined, `${name}: nor does a null-prototype one`);+ }+ for (const notAMap of [undefined, null, 0, '', 'constructor', true]) assert.equal(ownValue(notAMap, 'constructor'), undefined, `${JSON.stringify(notAMap)} is no map`);+ assert.equal(ownValue(['a'], 0), 'a', 'an array is read by its own indices, as before');+ assert.equal(Object.getPrototypeOf(held), Object.prototype, 'reading changes no prototype');+});++// --- the app's navigation (sdk-build.js appDef) ------------------------------------------------------------------------------------------------------------++const appSpec = (subAreas) => ({+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoBoards', publisherPrefix: 'contoso' },+ app: { name: 'Boards', uniqueName: 'contoso_boards' },+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Boards', subAreas }] }] },+});+const entriesOf = (def) => def.siteMap.areas[0].groups[0].subAreas;++test('a navigation entry opens the dashboard of its name when that name is a member of Object.prototype, and is refused when no such dashboard was built', () => {+ const spec = appSpec(NAMES.map((name) => ({ dashboard: name, title: `Board ${name}` })));+ const built = entriesOf(appDef(spec, { dashboards: ownMap(NAMES, (name) => ID[name]) }));+ assert.deepEqual(built.map((s) => [s.type, s.dashboardId]), NAMES.map((name) => ['DashBoard', ID[name]]), 'each entry opens the dashboard built under its name');+ for (const name of NAMES) {+ const one = appSpec([{ dashboard: name, title: 'Board' }]);+ for (const [what, result] of [['none was built', { dashboards: {} }], ['no dashboard map at all', {}], ['the build wrote a null-prototype map', { dashboards: Object.create(null) }]]) {+ assert.throws(() => appDef(one, result), (e) => e.message.includes(`references dashboard '${name}' which wasn't built`), `${name}, ${what}: refused, never opened as the inherited member`);+ }+ }+});++test('a navigation entry of a page keyed or named like a member of Object.prototype is left out of an app\'s first create while its page is not built, and refused at the finalize', () => {+ for (const name of NAMES) {+ const spec = appSpec([{ entity: 'contact', title: 'Contacts' }, { page: name, title: 'The page' }]);+ for (const pages of [{}, Object.create(null)]) {+ const first = entriesOf(appDef(spec, { pages }, { omitUnbuiltPages: true }));+ assert.deepEqual(first.map((s) => s.type), ['Entity'], `${name}: the page entry waits for its page, as any unbuilt page's does`);+ assert.throws(() => appDef(spec, { pages }), (e) => e.message.includes(`references page '${name}' which wasn't built`), `${name}: at the finalize, an unbuilt page is refused`);+ }+ const built = entriesOf(appDef(spec, { pages: ownMap([name], () => ID.constructor) }));+ assert.deepEqual(built.map((s) => [s.type, s.genPageId || s.entity]), [['Entity', 'contact'], ['GenPage', ID.constructor]], `${name}: once built, the entry opens that page`);+ }+});++test('navigation entries of ordinary dashboard and page names are built, left out or refused exactly as before', () => {+ const spec = appSpec([{ dashboard: 'Ops Overview', title: 'Ops' }, { entity: 'contact', title: 'Contacts' }, { page: 'overview', title: 'Overview' }]);+ const result = { dashboards: { 'Ops Overview': ID.toString }, pages: { overview: ID.hasOwnProperty } };+ assert.deepEqual(entriesOf(appDef(spec, result)).map((s) => [s.type, s.dashboardId || s.genPageId || s.entity]),+ [['DashBoard', ID.toString], ['Entity', 'contact'], ['GenPage', ID.hasOwnProperty]]);+ assert.deepEqual(entriesOf(appDef(spec, { dashboards: result.dashboards, pages: {} }, { omitUnbuiltPages: true })).map((s) => s.type), ['DashBoard', 'Entity']);+ assert.throws(() => appDef(spec, { dashboards: {}, pages: result.pages }), /references dashboard 'Ops Overview' which wasn't built/);+ assert.throws(() => appDef(spec, { dashboards: result.dashboards, pages: {} }), /references page 'overview' which wasn't built/);+});++// --- grouping by a table the spec names (sdk-build.js commandsByEntity, app-spec.js validateAppSpec) ----------------------------------------------------------++test('commands are grouped by the table they name, whatever that name is, and nothing throws', () => {+ const spec = { commands: NAMES.map((name, i) => ({ entity: name, label: `Go ${i}` })).concat([{ entity: 'contoso_item', label: 'Approve' }, { entity: 'CONTOSO_ITEM', label: 'Reject' }]) };+ const grouped = commandsByEntity(spec);+ assert.deepEqual(Object.keys(grouped), ['__proto__', 'constructor', 'tostring', 'hasownproperty', 'contoso_item'], 'one group per table, lower-cased, in the spec\'s order');+ assert.deepEqual(Object.values(grouped).map((cmds) => cmds.map((c) => c.label)), [['Go 0'], ['Go 1'], ['Go 2'], ['Go 3'], ['Approve', 'Reject']]);+});++test('the spec gate reports a form whose table is called like a member of Object.prototype, and never throws on it', () => {+ for (const name of ['__proto__', 'constructor']) {+ let report;+ assert.doesNotThrow(() => { report = validateAppSpec({ ...appSpec([]), forms: [{ entity: name, name: 'Main', isDefault: true }] }); }, `${name}: isDefault`);+ assert.ok(report.errors.includes(`form references unknown entity '${name}'`), `${name}: ${JSON.stringify(report.errors)}`);+ // Two Main forms that each deactivate the other are refused for any table, as for a table the spec declares.+ const both = validateAppSpec({ ...appSpec([]), forms: [{ entity: name, name: 'A', deactivateOtherMainForms: true }, { entity: name, name: 'B', deactivateOtherMainForms: true }] });+ assert.ok(both.errors.includes(`entity '${name}': 2 Main forms set deactivateOtherMainForms — at most one may (two would deactivate each other)`), `${name}: ${JSON.stringify(both.errors)}`);+ }+ // The same rules for an ordinary table, unchanged.+ const ordinary = validateAppSpec({ ...appSpec([]), forms: [{ entity: 'contoso_ghost', name: 'A', deactivateOtherMainForms: true }, { entity: 'contoso_ghost', name: 'B', deactivateOtherMainForms: true }] });+ assert.ok(ordinary.errors.includes("entity 'contoso_ghost': 2 Main forms set deactivateOtherMainForms — at most one may (two would deactivate each other)"), JSON.stringify(ordinary.errors));+});++test('a column type called like a member of Object.prototype is an unknown type, at both gates', () => {+ const entity = (type) => ({ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [{ schemaName: 'contoso_note', displayName: 'Note', type }] });+ for (const type of NAMES) {+ const spec = validateAppSpec({ ...appSpec([{ entity: 'contoso_item', title: 'Items' }]), entities: [entity(type)] });+ assert.ok(spec.errors.includes(`entity contoso_item: column contoso_note has unknown type '${type}'`), `${type}: the App Spec gate — ${JSON.stringify(spec.errors)}`);+ const input = validateProvisionInput({ solution: { uniqueName: 'S', publisherPrefix: 'contoso' }, entities: [entity(type)] });+ assert.ok(input.errors.includes(`entity 'contoso_item': column 'contoso_note' has unknown type '${type}'`), `${type}: the provisioning input gate — ${JSON.stringify(input.errors)}`);+ }+ for (const type of ['Text', 'Memo', 'Choice', 'Lookup']) {+ const spec = validateAppSpec({ ...appSpec([{ entity: 'contoso_item', title: 'Items' }]), entities: [entity(type)] });+ assert.ok(!spec.errors.some((e) => e.includes('unknown type')), `${type} is still a type: ${JSON.stringify(spec.errors)}`);+ }+});++test('names that are members of Object.prototype are valid names: the spec gate accepts them for dashboards, pages, personas, flows and status reasons', () => {+ const spec = {+ ...appSpec(NAMES.map((name) => ({ dashboard: name, title: `Board ${name}` })).concat([{ page: 'constructor', title: 'Constructor' }, { entity: 'contoso_ticket', title: 'Tickets' }])),+ entities: [{+ schemaName: 'contoso_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },+ statusReasons: NAMES.map((label) => ({ label, state: 'Active' })),+ columns: [{ schemaName: 'contoso_notes', displayName: 'Notes', type: 'Text' }],+ }],+ dashboards: NAMES.map((name) => ({ name, tiles: [{ type: 'iframe', url: 'https://contoso.example/status', name: 'Status' }] })),+ pages: [{ key: 'constructor', name: 'Constructor', source: { kind: 'intent' } }],+ personas: NAMES.map((persona) => ({ persona, jobs: [{ name: 'Work', privileges: [{ entity: 'contoso_ticket', access: ['read'] }] }] })),+ businessProcessFlows: [{ name: '__proto__', entity: 'contoso_ticket', status: 'Active', stages: [{ name: 'Triage', steps: [{ name: 'Notes', field: 'contoso_notes' }] }], securityRoles: { personas: NAMES } }],+ sampleData: { contoso_ticket: NAMES.map((statusReason, i) => ({ contoso_name: `T${i}`, statusReason })) },+ };+ assert.deepEqual(validateAppSpec(spec, { profile: 'plan' }).errors, []);+});++// --- the changed-only snapshot (apply-snapshot-index.js, changed-only-flow.js) -------------------------------------------------------------------------------++test('the snapshot index records a dashboard of each of these names under its own name, and none that was not built', () => {+ const spec = { dashboards: NAMES.map((name) => ({ name })) };+ const built = indexArtifacts(spec, { dashboards: ownMap(NAMES, (name) => ID[name]) });+ assert.equal(json(built.dashboards), json(ownMap(NAMES, (name) => ({ id: ID[name] }))), 'every dashboard, in the spec\'s order');+ for (const created of [{ dashboards: {} }, {}, { dashboards: Object.create(null) }]) {+ const none = indexArtifacts(spec, created);+ assert.deepEqual(Object.keys(none.dashboards), [], `nothing built, nothing recorded (${json(created)})`);+ assert.equal(json(none.dashboards), '{}');+ }+});++test('the snapshot index records a page keyed constructor only when it was deployed, with its source hash standing for the deployed one', () => {+ const spec = { pages: [{ key: 'constructor', name: 'Constructor', __contentSha: 'sha-constructor' }] };+ const deployed = indexArtifacts(spec, { pages: ownMap(['constructor'], () => ID.constructor) });+ assert.deepEqual({ ...deployed.pages.constructor }, { pageId: ID.constructor, sourceSha: 'sha-constructor', deployedSha: 'sha-constructor' });+ assert.equal(json(deployed.pages), `{"constructor":{"pageId":"${ID.constructor}","sourceSha":"sha-constructor","deployedSha":"sha-constructor"}}`);+ const staged = indexArtifacts(spec, { pages: ownMap(['constructor'], () => ID.constructor) }, { pageDeployedShas: ownMap(['constructor'], () => 'sha-deployed') });+ assert.equal(staged.pages.constructor.deployedSha, 'sha-deployed', 'a staged deployed hash still wins');+ for (const pages of [{}, Object.create(null)]) assert.equal(json(indexArtifacts(spec, { pages }).pages), '{}', 'an undeployed page is not recorded');+});++test('the snapshot index of ordinary names is byte for byte what it was', () => {+ const spec = {+ entities: [{ schemaName: 'new_x', primaryAttribute: { schemaName: 'new_name' } }],+ views: [{ entity: 'new_x', name: 'Active X', columns: ['new_name'] }],+ forms: [{ entity: 'new_x', name: 'Main', formType: 'Main', layout: 'auto' }],+ charts: [{ entity: 'new_x', name: 'By Status' }],+ commands: [{ entity: 'new_x', name: 'Approve' }],+ dashboards: [{ name: 'Ops' }, { name: 'Sales Overview' }],+ webResources: [{ name: 'wr_a', __contentSha: 'wsha1' }],+ pages: [{ key: 'overview', name: 'Overview', __contentSha: 'psha1' }, { key: 'detail', name: 'Detail', __contentSha: 'psha2' }],+ };+ const created = { entities: { new_x: 'ent-1' }, views: { 'new_x|Active X': 'view-1' }, forms: { new_x: 'form-1' }, charts: { 'new_x|By Status': 'chart-1' }, commands: { new_x: 'cmd-1' }, dashboards: { Ops: 'dash-1', 'Sales Overview': 'dash-2' }, webResources: { wr_a: 'wr-1' }, app: 'app-1', pages: { overview: 'page-1', detail: 'page-2' } };+ assert.equal(json(indexArtifacts(spec, created, { pageDeployedShas: { detail: 'deployed-2' }, sitemapSha: 'smap' })),+ '{"pages":{"overview":{"pageId":"page-1","sourceSha":"psha1","deployedSha":"psha1"},"detail":{"pageId":"page-2","sourceSha":"psha2","deployedSha":"deployed-2"}},'+ + '"forms":{"new_x|Main|Main":{"formId":"form-1"}},"views":{"new_x|Active X":{"viewId":"view-1"}},"app":{"appId":"app-1","sitemapSha":"smap"},'+ + '"webResources":{"wr_a":{"id":"wr-1","sourceSha":"wsha1"}},"entities":{"new_x":{"id":"ent-1"}},"charts":{"new_x|By Status":{"id":"chart-1"}},'+ + '"commands":{"new_x|Approve":{"id":"cmd-1"}},"dashboards":{"Ops":{"id":"dash-1"},"Sales Overview":{"id":"dash-2"}}}');+});++const LIVE = { orgId: 'org-1', envUrl: 'https://contoso.crm.dynamics.com', appUniqueName: 'contoso_boards', appId: 'app-1' };+// An eligible snapshot of an app with one page keyed constructor — recorded or not — refreshed after a fast apply that re-uploaded it.+function fastSnapshot({ recorded, created }) {+ const annotatedSpec = { pages: [{ key: 'constructor', name: 'Constructor', source: { kind: 'tsx', codeFile: 'constructor.tsx' }, __contentSha: 'sha-v2' }] };+ const snapshot = snap.makeEnvelope(LIVE, { generation: 'g0' });+ snapshot.priorSpec = annotatedSpec;+ snapshot.artifacts = { pages: recorded ? ownMap(['constructor'], () => ({ pageId: ID.constructor, sourceSha: 'sha-v1', deployedSha: 'sha-v1' })) : {} };+ snap.markEligible(snapshot);+ return flow.assembleFastSnapshot({ snapshot, annotatedSpec, created, pageKeys: ['constructor'], generation: 'g1' });+}++test('a fast apply of a page keyed constructor records its hashes and id, and takes the source hash when no deployed one was measured', () => {+ for (const [what, recorded, created, pageId] of [+ ['the build answered its id', false, { pages: ownMap(['constructor'], () => ID.constructor) }, ID.constructor],+ ['the build answered no id, the snapshot holds it', true, { pages: {} }, ID.constructor],+ ['no id anywhere', false, { pages: {} }, null],+ ['a result with no page maps', false, {}, null],+ ]) {+ const env = fastSnapshot({ recorded, created });+ const entry = { pageId, sourceSha: 'sha-v2', deployedSha: 'sha-v2' };+ assert.deepEqual({ ...env.artifacts.pages.constructor }, entry, what);+ assert.deepEqual(snap.parseEnvelope(snap.serializeEnvelope(env)).artifacts.pages.constructor, entry, `${what}: and so does the snapshot written to disk`);+ }+ const measured = fastSnapshot({ recorded: true, created: { pages: ownMap(['constructor'], () => ID.constructor), pageDeployedShas: ownMap(['constructor'], () => 'sha-deployed') } });+ assert.equal(measured.artifacts.pages.constructor.deployedSha, 'sha-deployed', 'a measured deployed hash still wins');+});++// --- status reasons (entity-provision.js) ---------------------------------------------------------------------------------------------------------------------++const ticketSpec = () => ({+ solution: { uniqueName: 'S', publisherPrefix: 'contoso' },+ entities: [{ schemaName: 'contoso_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'contoso_name' }, statusReasons: NAMES.map((label) => ({ label, state: 'Active' })), columns: [] }],+ sampleData: { contoso_ticket: NAMES.map((statusReason, i) => ({ contoso_name: `T${i}`, statusReason })) },+});++test('a sample record whose status reason is called like a member of Object.prototype halts when its value was not captured, as any status reason does', () => {+ const spec = ticketSpec();+ for (const [i, name] of NAMES.entries()) {+ for (const statusReasonValues of [{}, { contoso_ticket: {} }, { contoso_ticket: Object.create(null) }]) {+ assert.throws(() => buildSeedGroup({ spec, e: spec.entities[0], records: [spec.sampleData.contoso_ticket[i]], statusReasonValues }),+ (e) => e.message.includes(`record sets statusReason '${name}' on contoso_ticket, but its status value wasn't captured`), `${name}: ${json(statusReasonValues)}`);+ }+ }+});++test('a sample record whose status reason is called like a member of Object.prototype gets the value captured for it', () => {+ const spec = ticketSpec();+ const captured = { contoso_ticket: ownMap(NAMES, (name) => ({ value: 100000000 + NAMES.indexOf(name), stateCode: 0 })) };+ const group = buildSeedGroup({ spec, e: spec.entities[0], records: spec.sampleData.contoso_ticket, statusReasonValues: captured });+ assert.deepEqual(group.records.map((r) => [r.body.statuscode, r.body.statecode]), NAMES.map((name, i) => [100000000 + i, 0]));+});++test('a status reason whose state is a member of Object.prototype is placed in the state a reason of an unknown state is placed in', () => {+ const targets = statusReasonTargets({ statusReasons: [...NAMES, 'Pending', 'Inactive', 'Active'].map((state, i) => ({ label: `R${i}`, state })) });+ assert.deepEqual(targets.map((t) => t.stateCode), [0, 0, 0, 0, 0, 1, 0], 'Active (0) as for any state it does not know; Inactive is still 1');+});++// --- Custom API parameters (list-custom-apis.js) -------------------------------------------------------------------------------------------------------------++// `__proto__` cannot name a parameter (Dataverse requires a letter first); it stays in NAMES because the maps are null-prototype as a defence,+// and must hold it all the same.+test('a Custom API parameter called like a member of Object.prototype is listed with its kind, and a lookup one with its table', () => {+ const primitives = NAMES.map((uniquename, i) => ({ uniquename, type: [10, 7, 0, 12][i], isoptional: false }));+ const kinds = parameterKindsFromRows(primitives);+ assert.deepEqual(Object.keys(kinds), NAMES, 'every parameter, in the order read');+ assert.equal(json(kinds), json(ownMap(NAMES, (name) => ['String', 'Integer', 'Boolean', 'Guid'][NAMES.indexOf(name)])));+ // A lookup (type 5) declares no kind; it is listed with its table and whether it is optional.+ const lookups = NAMES.map((uniquename) => ({ uniquename, type: 5, isoptional: uniquename === 'toString', logicalentityname: 'account' }));+ const entry = toCustomApiEntry({ uniquename: 'contoso_Approve', bindingtype: 0, CustomAPIRequestParameters: lookups }, parameterKindsFromRows(lookups));+ assert.deepEqual(Object.keys(entry.lookupParameters || {}), NAMES, 'every lookup, in the order read');+ assert.equal(json(entry.lookupParameters), json(ownMap(NAMES, (name) => ({ isOptional: name === 'toString', logicalEntityName: 'account' }))));+ assert.equal(json(entry.parameterKinds), '{}', 'a lookup declares no kind, as before');+});++// --- the persona roles and flow role grants of a build (sdk-build.js security phase) -------------------------------------------------------------------------++const ROLE_ID = '55555555-5555-4555-8555-555555555555';+function securityFlowSdk() {+ const calls = { addEntityPrivilegesToRole: [] };+ return {+ calls,+ queryRecords: async (entity) => (entity === 'businessunit' ? [{ businessunitid: '66666666-6666-4666-8666-666666666666' }] : []),+ createPersonaRole: async (s) => ({ roleId: ROLE_ID, name: s.name, reused: false, appliedPrivileges: [] }),+ addEntityPrivilegesToRole: async (roleId, privileges) => { calls.addEntityPrivilegesToRole.push({ roleId, privileges }); return []; },+ addSolutionComponent: async () => ({}),+ associateRecords: async () => ({}),+ disassociateRecords: async () => ({}),+ createArtifact: (type, def) => ({ id: '77777777-7777-4777-8777-777777777777', type, def }),+ pushArtifact: async (type, id) => ({ ok: true, id }),+ activateArtifact: async () => ({ ok: true }),+ updateRecord: async () => ({}),+ };+}+const flowSpec = (persona, flowName) => ({+ schemaVersion: 2,+ solution: { uniqueName: 'contoso', publisherPrefix: 'contoso' },+ app: { name: 'Contoso' },+ entities: [{ schemaName: 'contoso_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_notes', type: 'Text' }] }],+ personas: [{ persona, jobs: [{ name: 'Dispatch', privileges: [{ entity: 'contoso_ticket', access: ['read'] }] }] }],+ businessProcessFlows: [{ name: flowName, entity: 'contoso_ticket', status: 'Active', stages: [{ name: 'Triage', steps: [{ name: 'Notes', field: 'contoso_notes' }] }], securityRoles: { personas: [persona] } }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [] }] }] },+});++test('a persona and a business process flow called like members of Object.prototype: the role is recorded under the persona\'s name, the flow grants it, and the grant is recorded under the flow\'s name', async () => {+ for (const name of NAMES) {+ const spec = flowSpec(name, name);+ assert.deepEqual(validateAppSpec(spec, { profile: 'plan' }).errors, [], `${name}: a valid spec`);+ const sdk = securityFlowSdk();+ const r = await runSdkBuild(spec, { sdk, provisionSdk: sdk, apply: true, phases: ['business-process-flows', 'security'], emit: () => undefined });+ assert.equal(r.ok, true, `${name}: ${json(r).slice(0, 400)}`);+ assert.deepEqual(sdk.calls.addEntityPrivilegesToRole.map((c) => c.roleId), [ROLE_ID], `${name}: the flow's backing table is granted to the persona's role`);+ assert.deepEqual(Object.keys(r.created.roles), [name], `${name}: the role, under the persona's name`);+ assert.equal(r.created.roles[name].roleId, ROLE_ID);+ assert.deepEqual(Object.keys(r.created.bpfRoleGrants), [name], `${name}: the grant, under the flow's name`);+ const written = JSON.parse(json(r.created));+ assert.equal(written.roles[name].roleId, ROLE_ID, `${name}: and the result's JSON holds both`);+ assert.deepEqual(written.bpfRoleGrants[name].personas, [name]);+ }+});diff --git a/plugins/model-apps/scripts/tests/publish-by-name-sdk-state.test.js b/plugins/model-apps/scripts/tests/publish-by-name-sdk-state.test.jsindex 22044ed43..8d0023a76 100644--- a/plugins/model-apps/scripts/tests/publish-by-name-sdk-state.test.js+++ b/plugins/model-apps/scripts/tests/publish-by-name-sdk-state.test.js@@ -11,7 +11,10 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { createFakeDataverse } = require('./helpers/fake-dataverse.js');const dirs = [];diff --git a/plugins/model-apps/scripts/tests/publish-halt-warning.test.js b/plugins/model-apps/scripts/tests/publish-halt-warning.test.jsindex 268d88d20..e680265bc 100644--- a/plugins/model-apps/scripts/tests/publish-halt-warning.test.js+++ b/plugins/model-apps/scripts/tests/publish-halt-warning.test.js@@ -16,10 +16,15 @@ const os = require('node:os');const path = require('node:path');const { randomUUID } = require('node:crypto');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');-const { runSdkBuild, settleOwedPublishes } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets a workspace of its own, which holds its build lease (helpers/own-app-folder.js): its specs name+// page source that is not on disk, which an app folder would make the build check.+const { inOwnWorkspace } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, settleOwedPublishes } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnWorkspace(runSdkBuildInPlace);const { validateAppSpec } = require('../lib/app-spec.js');const { STAGES } = require('../lib/stages.js');-const { buildModelApp } = require('../build-model-app.js');+const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+const buildModelApp = inOwnWorkspace(buildModelAppInPlace);const { createFakeDataverse } = require('./helpers/fake-dataverse.js');const dirs = [];diff --git a/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.jsindex 3307fc067..7681c79b5 100644--- a/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js@@ -22,7 +22,10 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');-const { runSdkBuild, settleOwedPublishes } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, settleOwedPublishes } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { createFakeDataverse } = require('./helpers/fake-dataverse.js');const COMPONENT = { view: 26, chart: 59, form: 60 };diff --git a/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js b/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.jsindex afa0ca985..c5713a9d9 100644--- a/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js+++ b/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js@@ -5,7 +5,10 @@// behaviour in rebuild-writes-real-bundle.test.js.const test = require('node:test');const assert = require('node:assert/strict');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');const SOLUTION_ID = '5011c0de-0000-4000-8000-000000000002';diff --git a/plugins/model-apps/scripts/tests/role-grants-localized-labels-and-inventory-reads.test.js b/plugins/model-apps/scripts/tests/role-grants-localized-labels-and-inventory-reads.test.jsindex 2bc8c0d2e..0ec29325c 100644--- a/plugins/model-apps/scripts/tests/role-grants-localized-labels-and-inventory-reads.test.js+++ b/plugins/model-apps/scripts/tests/role-grants-localized-labels-and-inventory-reads.test.js@@ -10,7 +10,10 @@ const assert = require('node:assert');const { validateAppSpec, choiceValueMap, labelText, resolveSampleRecords } = require('../lib/app-spec.js');const { validateProvisionInput } = require('../lib/provision-input.js');const { phaseInputs } = (() => { const m = require('../lib/phase-diff.js'); return { phaseInputs: m.PHASE_INPUTS || m.phaseInputs }; })();-const { runSdkBuild, subgridLabel, viewDef } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, subgridLabel, viewDef } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { notRoundTrippedSummary, notRoundTrippedWarning } = require('../download-model-app.js');const { currentReadSdk } = require('./helpers/app-membership-sdk.js');diff --git a/plugins/model-apps/scripts/tests/role-grants.test.js b/plugins/model-apps/scripts/tests/role-grants.test.jsindex 411b3bba9..cf15dfc59 100644--- a/plugins/model-apps/scripts/tests/role-grants.test.js+++ b/plugins/model-apps/scripts/tests/role-grants.test.js@@ -13,7 +13,10 @@const test = require('node:test');const assert = require('node:assert');const { validateAppSpec } = require('../lib/app-spec.js');-const { planFor, runSdkBuild, roleGrantLabel, resolveRoleGrantTarget } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { planFor, runSdkBuild: runSdkBuildInPlace, roleGrantLabel, resolveRoleGrantTarget } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);function base() {return {diff --git a/plugins/model-apps/scripts/tests/run-cleanup.test.js b/plugins/model-apps/scripts/tests/run-cleanup.test.jsindex da63714c8..9bebd9e08 100644--- a/plugins/model-apps/scripts/tests/run-cleanup.test.js+++ b/plugins/model-apps/scripts/tests/run-cleanup.test.js@@ -4,7 +4,10 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { isTransientHalt } = require('../build-model-app.js');const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');diff --git a/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.js b/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.jsindex b768c2389..f5b42293f 100644--- a/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-layout-default.test.js@@ -1,7 +1,10 @@'use strict';const test = require('node:test');const assert = require('node:assert');-const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { validateAppSpec } = require('../lib/app-spec.js');const { fitsGrid } = require('../lib/form-occupancy.js');diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.jsindex 5bac7cd8b..a8feb35a8 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js@@ -1424,13 +1424,14 @@ test('deploy: the pages phase records the hash of the source it read for each paconst genpageCli = mockGenpageCli();const r = await runSdkBuild(spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });const source = (file) => sha256(fs.readFileSync(path.join(appDir, file)));- assert.deepStrictEqual(r.created.pageSourceShas, { overview: source('overview.tsx'), detail: source('detail.tsx') });+ // The result's page maps are null-prototype objects (lib/own-keys.js: a page's key can be `constructor`), so their entries are compared.+ assert.deepStrictEqual({ ...r.created.pageSourceShas }, { overview: source('overview.tsx'), detail: source('detail.tsx') });assert.notStrictEqual(r.created.pageDeployedShas.overview, r.created.pageSourceShas.overview, 'the copy that is uploaded has the target\'s id where the source has PAGEREF_: it is another hash');// Only a page that is sent is recorded: a changed-only run that selects one page records that page.const selected = await runSdkBuild(spec, { sdk: mockSdk({ pageManifest: Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64'), liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: [{ uxagentprojectid: OVERVIEW_ID, name: 'Overview' }, { uxagentprojectid: DETAIL_ID, name: 'Detail' }] }).sdk,apply: true, env: 'https://x', appDir, genpageCli: mockGenpageCli([{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }]), phases: PAGES_ONLY,changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys: ['detail'] } });- assert.deepStrictEqual(selected.created.pageSourceShas, { detail: source('detail.tsx') });+ assert.deepStrictEqual({ ...selected.created.pageSourceShas }, { detail: source('detail.tsx') });} finally { fs.rmSync(appDir, { recursive: true, force: true }); }});@@ -2525,7 +2526,8 @@ test('deploy: an UNCHANGED rebuild of an app with two pages sends no change set// Nothing changed.let from = server.requests.length;const again = await rebuildPages(spec, appDir, server, ids);- assert.deepStrictEqual(again.created.pages, ids, 'the same two pages');+ // `created.pages` is a null-prototype map (lib/own-keys.js), so its entries are compared with the plain copy `ids`.+ assert.deepStrictEqual({ ...again.created.pages }, ids, 'the same two pages');const unchanged = requestsOf(server, from);assert.deepStrictEqual([unchanged.changeSets, unchanged.publishes, unchanged.otherWrites], [0, 0, 0], 'an unchanged page costs no change set, no publish and no other write');assert.ok(unchanged.reads > 0, 'only reads: each page is read to see that it holds what the spec asks for');@@ -2562,7 +2564,7 @@ test('deploy: pages that link to each other are published once and then left aloconst from = server.requests.length;const again = await rebuildPages(spec, appDir, server, ids);- assert.deepStrictEqual(again.created.pages, ids);+ assert.deepStrictEqual({ ...again.created.pages }, ids);const unchanged = requestsOf(server, from);assert.deepStrictEqual([unchanged.changeSets, unchanged.publishes, unchanged.otherWrites], [0, 0, 0], 'an unchanged rebuild of linked pages writes and publishes nothing either');assert.ok(unchanged.reads > 0);@@ -2854,6 +2856,278 @@ test('changed-only: a binding whose reference is another connector\'s stops a ru} finally { fs.rmSync(appDir, { recursive: true, force: true }); }});+// ── a changed-only run leaves alone the bindings of a navigation target that exists ─────────────────────────────────────────────────────────+// Three pages: Alpha, Bravo — which navigates to Charlie — and Charlie, whose connector binding goes through `contoso_msnweather`, a connection reference this environment holds for ANOTHER connector. A+// changed-only run writes the pages it selected, and makes a navigation target only when the target is ABSENT (from its spec entry, bindings and all); one that exists it leaves as it is. Which targets exist+// is settled by the pages phase, after the check before writing, so the changed-only flow tells the build the pages its last verified apply deployed (`deployedKeys`): such a target is not checked, and one+// the pages phase then finds absent after all is checked there, before it is made. A run told nothing, a run that writes before its pages phase, and a full build check every target, as they always did.+const ABC_IDS = { alpha: 'a1a1a1a1-0000-4000-8000-00000000000a', bravo: 'b2b2b2b2-0000-4000-8000-00000000000b', charlie: 'c3c3c3c3-0000-4000-8000-00000000000c' };+const ABC_NAMES = { alpha: 'Alpha', bravo: 'Bravo', charlie: 'Charlie' };+const ABC_KEYS = Object.keys(ABC_IDS);+const reference = (logicalName, connector) => ({ connectionreferencelogicalname: logicalName, connectorid: `/providers/Microsoft.PowerApps/apis/${connector}`, connectionid: `${connector}-0001`, _customconnectorid_value: null });+// Charlie's reference, as the environment holds it: for another connector than Charlie's binding says.+const CHARLIE_REFERENCE = reference('contoso_msnweather', 'shared_office365users');+const SHAREPOINT_BINDING = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'] };++// `present`: the pages the environment holds — the rest are absent, as a page deleted in Maker since the last apply is. `recorded`: the pages the app's manifest and navigation still name (by default+// the present ones; a page deleted in Maker stays in both). `alpha`: what Alpha states besides its source.+function abcApp({ present = ABC_KEYS, recorded = present, alpha = {} } = {}) {+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abc-bindings-'));+ fs.writeFileSync(path.join(appDir, 'alpha.tsx'), 'export default function A(){ return null; }', 'utf8');+ fs.writeFileSync(path.join(appDir, 'bravo.tsx'), `export default function B(){ ${NAV('charlie')} return null; }`, 'utf8');+ fs.writeFileSync(path.join(appDir, 'charlie.tsx'), 'export default function C(){ return null; }', 'utf8');+ const spec = {+ schemaVersion: 2,+ solution: { uniqueName: 'AbcBindings', displayName: 'Abc', publisherPrefix: 'contoso' },+ app: { name: 'Abc Bindings App' },+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],+ pages: [+ { key: 'alpha', name: 'Alpha', source: { kind: 'tsx', codeFile: 'alpha.tsx' }, ...alpha },+ { key: 'bravo', name: 'Bravo', navigatesTo: [{ targetKey: 'charlie' }], source: { kind: 'tsx', codeFile: 'bravo.tsx' } },+ { key: 'charlie', name: 'Charlie', source: { kind: 'tsx', codeFile: 'charlie.tsx' }, connectorBindings: [HELD_WEATHER] },+ ],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'G', subAreas: [...ABC_KEYS.map((key) => ({ page: key, title: ABC_NAMES[key] })), TABLE_ENTRY] }] }] },+ };+ const live = present.map((key) => ({ pageId: ABC_IDS[key], name: ABC_NAMES[key] }));+ const manifest = { schemaVersion: 1, pages: recorded.map((key) => ({ key, name: ABC_NAMES[key], pageId: ABC_IDS[key] })) };+ // Every read of what the bindings name, every read of the generative pages in the saved layer, and every write to the SDK, whatever the run.+ const reads = [];+ const pageReads = [];+ const writes = [];+ // `references`: the rows the environment answers for connection references — or a function of the read's number (1, 2, …) that answers them, or throws as a refused read does.+ // `failPageRows`: the read of the generative pages in the saved layer is refused.+ const run = (options, references = [CHARLIE_REFERENCE], { failPageRows = false } = {}) => {+ const { sdk } = mockSdk({ pageManifest: Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64'), liveSitemapXml: pageSitemap(recorded.map((key) => ABC_IDS[key])), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });+ const answer = sdk.queryRecords;+ sdk.queryRecords = async (entity, query) => {+ if (!['connectionreference', 'customapi', 'connector'].includes(entity)) return answer(entity, query);+ reads.push({ entity, filter: query && query.filter });+ if (typeof references === 'function') return references(entity, reads.length);+ return entity === 'connectionreference' ? references : [];+ };+ // The generative pages in the SAVED layer, by id (lib/app-components.js savedPageRows), as the environment holds them:+ // GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid,name,componentstate&$filter=uxagentprojectid eq <id> or uxagentprojectid eq <id>+ const get = sdk.dataverse.get;+ sdk.dataverse.get = async (url) => {+ if (!url.startsWith('/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) return get(url);+ pageReads.push(url);+ if (failPageRows) return { status: 503, body: { error: { message: 'Service Unavailable' } } };+ const asked = [...url.matchAll(/uxagentprojectid eq ([0-9a-f-]{36})/gi)].map((m) => m[1].toLowerCase());+ return { status: 200, body: { value: live.filter((p) => asked.includes(p.pageId.toLowerCase())).map((p) => ({ uxagentprojectid: p.pageId, name: p.name, componentstate: 0 })) } };+ };+ for (const method of Object.keys(sdk).filter((name) => /^(create|update|push|publish|add|remove|set|enrich|seed)/.test(name))) {+ const original = sdk[method];+ sdk[method] = (...args) => { writes.push(method); return original(...args); };+ }+ const genpage = abcGenpage(live);+ return { genpage, built: runSdkBuild(spec, { sdk, env: 'https://x', appDir, genpageCli: genpage, apply: true, phases: PAGES_ONLY, ...options }) };+ };+ return { appDir, spec, reads, pageReads, writes, run };+}++// The page backend of the three pages: the environment's pages are `live`, and a create makes the page under its own id.+function abcGenpage(live) {+ const uploads = [];+ const answer = (o, pageId) => ({ pageId, name: o.name, publish: { kind: 'verified', detail: '' }, warnings: [] });+ return {+ uploads,+ enumerateEnv: async () => ({ ok: true, ids: live.map((p) => p.pageId.toLowerCase()), pages: live }),+ create: async (o) => {+ const key = ABC_KEYS.find((k) => ABC_NAMES[k] === o.name);+ uploads.push(`create ${o.name}`);+ return answer(o, ABC_IDS[key]);+ },+ update: async (id, o) => { uploads.push(`update ${o.name}`); return answer(o, id); },+ placeInApp: async () => ({ added: [], alreadyPlaced: [], pinnedViews: [], warnings: [], appEdited: false }),+ };+}+const fastApply = (selectedKeys, extra = {}) => ({ changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys, ...extra } });+const conflictOn = (page) => (e) => e.code === 'pages-binding-reference-conflict' && e.phase === 'preflight' && e.recoverable === false && e.transient === false+ && new RegExp(`page "${page}": connector binding "[a-z_]+" is for connector shared_[a-z0-9]+, but the connection reference of that name in this environment is for connector shared_[a-z0-9]+`).test(e.message)+ && /The build stopped before writing anything\./.test(e.message);++test('changed-only: an edit of one page leaves alone the bindings of a navigation target that exists — not read, not refused, not said — though its reference is another connector\'s', async () => {+ const app = abcApp();+ try {+ const warnings = [];+ const { genpage, built } = app.run({ ...fastApply(['alpha'], { deployedKeys: ABC_KEYS }), warn: (m) => warnings.push(String(m)) });+ const result = await built;+ assert.ok(result.ok, JSON.stringify(result));+ assert.deepStrictEqual(genpage.uploads, ['update Alpha'], 'Alpha alone is written: Charlie exists, so it is not made, and Bravo is not selected');+ assert.deepStrictEqual(app.reads, [], 'no page the run writes states a binding, so nothing is read of what bindings name');+ assert.deepStrictEqual(warnings.filter((w) => /contoso_msnweather|"Charlie"/.test(w)), [], 'and nothing is said of Charlie\'s binding');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: the read is for the bindings of the pages the run writes — a target that exists adds no name to it', async () => {+ const app = abcApp({ alpha: { connectorBindings: [SHAREPOINT_BINDING] } });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], { deployedKeys: ABC_KEYS }), [CHARLIE_REFERENCE, reference('contoso_sharepoint', 'shared_sharepointonline')]);+ assert.ok((await built).ok);+ assert.deepStrictEqual(genpage.uploads, ['update Alpha']);+ assert.deepStrictEqual(app.reads.map((r) => r.entity), ['connectionreference'], 'one read of the references, as for any page that states a connector binding');+ assert.strictEqual(app.reads[0].filter, "connectionreferencelogicalname eq 'contoso_sharepoint'", 'for Alpha\'s reference alone');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: a page the run writes is still refused for a reference that is another connector\'s — before anything is written', async () => {+ const app = abcApp({ alpha: { connectorBindings: [SHAREPOINT_BINDING] } });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], { deployedKeys: ABC_KEYS }), [CHARLIE_REFERENCE, reference('contoso_sharepoint', 'shared_office365users')]);+ await assert.rejects(built, conflictOn('Alpha'));+ assert.deepStrictEqual(genpage.uploads, [], 'nothing was uploaded');+ assert.deepStrictEqual(app.writes, [], 'and nothing else was written');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: an ABSENT navigation target is made by the run, bindings and all, so it is refused before anything is written — told of the pages that exist, or told nothing', async () => {+ for (const extra of [{ deployedKeys: ['alpha', 'bravo'] }, {}]) {+ const app = abcApp({ present: ['alpha', 'bravo'] });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], extra));+ await assert.rejects(built, conflictOn('Charlie'), JSON.stringify(extra));+ assert.deepStrictEqual(genpage.uploads, [], 'Charlie was not made, and Alpha not written');+ assert.deepStrictEqual(app.writes, []);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+ }+});++// The flow's record is of its last verified apply, and a maker can delete a page in Maker after it. The run is then told Charlie exists, and the pages phase finds it absent and makes it from its spec entry:+// its bindings are checked there, before the first page is written, with the same halt — never left unchecked because the record said the page was there.+test('changed-only: a target the run was told exists, and finds absent, is checked before it is made — the same halt, and nothing written', async () => {+ const app = abcApp({ present: ['alpha', 'bravo'] });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], { deployedKeys: ABC_KEYS }));+ await assert.rejects(built, (e) => conflictOn('Charlie')(e) && /^1 connector binding\(s\) name a connection reference this environment already has for ANOTHER connector: /.test(e.message));+ assert.deepStrictEqual(genpage.uploads, [], 'Charlie was not made, and Alpha not written');+ assert.deepStrictEqual(app.writes, [], 'and nothing else was written');+ assert.deepStrictEqual(app.reads, [{ entity: 'connectionreference', filter: "connectionreferencelogicalname eq 'contoso_msnweather'" }], 'Charlie\'s reference was read once, when the run found it was to make the page');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: a run that is told nothing of which pages exist checks every navigation target before it writes anything, as before', async () => {+ const app = abcApp();+ try {+ const { genpage, built } = app.run(fastApply(['alpha']));+ await assert.rejects(built, conflictOn('Charlie'));+ assert.deepStrictEqual(genpage.uploads, []);+ assert.deepStrictEqual(app.writes, []);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('a full build writes every page, so a target\'s binding is refused before anything is written — and so is it in a changed-only run that writes before its pages phase, whatever it is told', async () => {+ for (const extra of [{}, { changedOnly: { selectedKeys: ['alpha'], deployedKeys: ABC_KEYS } }]) {+ const app = abcApp();+ try {+ const { genpage, built } = app.run({ phases: PHASES, ...extra });+ await assert.rejects(built, conflictOn('Charlie'), JSON.stringify(extra));+ assert.deepStrictEqual(genpage.uploads, []);+ assert.deepStrictEqual(app.writes, [], 'no solution, table, app or page');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+ }+});++test('changed-only: a dry run marks the pages an apply would stop at, and no other — by the same rule', async () => {+ const marked = async (options, present) => {+ const app = abcApp(present ? { present, alpha: options.alpha } : { alpha: options.alpha });+ try {+ const { built } = app.run({ ...fastApply(['alpha'], options.extra), apply: false }, options.references);+ const planned = await built;+ assert.strictEqual(planned.dryRun, true);+ return { halts: planned.planItems.filter((item) => item.wouldHalt).map((item) => item.label), reads: app.reads.length };+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+ };+ assert.deepStrictEqual(await marked({ extra: { deployedKeys: ABC_KEYS } }), { halts: [], reads: 0 }, 'Charlie exists: an apply writes Alpha alone');+ assert.deepStrictEqual(await marked({ extra: { deployedKeys: ['alpha', 'bravo'] } }, ['alpha', 'bravo']), { halts: ['page "Charlie"'], reads: 1 }, 'Charlie is absent: an apply makes it, and stops');+ assert.deepStrictEqual(await marked({ extra: {} }), { halts: ['page "Charlie"'], reads: 1 }, 'told nothing, the plan checks every target, as the apply does');+ const alphaConflict = { alpha: { connectorBindings: [SHAREPOINT_BINDING] }, references: [CHARLIE_REFERENCE, reference('contoso_sharepoint', 'shared_office365users')] };+ assert.deepStrictEqual(await marked({ ...alphaConflict, extra: { deployedKeys: ABC_KEYS } }), { halts: ['page "Alpha"'], reads: 1 }, 'the page an apply writes is marked');+});++// Alpha and Charlie name the same connection reference. Alpha's binding states the connector the environment's reference is for, so Alpha is fine; Charlie's states another, so Charlie's+// conflicts. Charlie was deleted in Maker since the last apply, while the run is told it is deployed: the check before writing reads the reference for Alpha, and the pages phase, about to+// make Charlie, judges Charlie by what that read answered. A name is read once per attempt — so a second read cannot be refused and turn the proven conflict into "not checked".+const SHARED_NAME_ALPHA = { connectorBindings: [{ ...HELD_WEATHER, connectorId: CHARLIE_REFERENCE.connectorid, operations: [] }] };++test('changed-only: a target found absent is judged by what the attempt already read of a name it shares — a later read that would fail cannot let it be made unchecked', async () => {+ const app = abcApp({ present: ['alpha', 'bravo'], recorded: ABC_KEYS, alpha: SHARED_NAME_ALPHA });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], { deployedKeys: ABC_KEYS }), (entity, number) => {+ if (number === 1) return [CHARLIE_REFERENCE];+ throw new Error('connectionreference: HTTP 403');+ });+ await assert.rejects(built, conflictOn('Charlie'));+ assert.deepStrictEqual(genpage.uploads, [], 'Charlie was not made, and Alpha not written');+ assert.deepStrictEqual(app.writes, [], 'and nothing else was written');+ assert.deepStrictEqual(app.reads, [{ entity: 'connectionreference', filter: "connectionreferencelogicalname eq 'contoso_msnweather'" }], 'the shared name was read once, before anything was written');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: a name the check before writing read is not read again for a target found absent — one read of it in the attempt, as before the fix', async () => {+ const app = abcApp({ present: ['alpha', 'bravo'], recorded: ABC_KEYS, alpha: SHARED_NAME_ALPHA });+ try {+ const { genpage, built } = app.run(fastApply(['alpha'], { deployedKeys: ABC_KEYS }));+ await assert.rejects(built, conflictOn('Charlie'));+ assert.deepStrictEqual(genpage.uploads, []);+ assert.strictEqual(app.reads.length, 1, 'the reference is read once in the attempt');+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++// A dry run has no pages phase to find a target absent, so for each target it was told is deployed it asks the environment, read only, whether the page is still there — and checks the one that is+// not, as the apply will. Plan and apply are run here with the SAME options against the SAME environment.+test('changed-only: a dry run finds a target it was told is deployed absent, and marks it — as the apply with the same options and environment stops on it', async () => {+ const app = abcApp({ present: ['alpha', 'bravo'], recorded: ABC_KEYS });+ try {+ const options = fastApply(['alpha'], { deployedKeys: ABC_KEYS });+ const planned = await app.run({ ...options, apply: false }).built;+ assert.strictEqual(planned.dryRun, true);+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt).map((item) => item.label), ['page "Charlie"']);+ assert.strictEqual(app.pageReads.length, 1, 'one read of the pages, for the target it was told is deployed');+ assert.strictEqual(app.reads.length, 1, 'and Charlie\'s reference, which the apply reads too');+ const { genpage, built } = app.run(options);+ await assert.rejects(built, conflictOn('Charlie'));+ assert.deepStrictEqual(genpage.uploads, []);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: a dry run that finds the target it was told is deployed still there leaves its binding unread — one read of the pages, none of references', async () => {+ const app = abcApp();+ try {+ const planned = await app.run({ ...fastApply(['alpha'], { deployedKeys: ABC_KEYS }), apply: false }).built;+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt), []);+ assert.strictEqual(app.pageReads.length, 1);+ assert.deepStrictEqual(app.reads, []);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++test('changed-only: a dry run told a target is deployed that neither the spec nor the manifest gives an id checks it — there is no page to ask the environment about', async () => {+ const app = abcApp({ present: ['alpha', 'bravo'] });+ try {+ const planned = await app.run({ ...fastApply(['alpha'], { deployedKeys: ABC_KEYS }), apply: false }).built;+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt).map((item) => item.label), ['page "Charlie"']);+ assert.strictEqual(app.pageReads.length, 0);+ assert.strictEqual(app.reads.length, 1);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});++// A dry run that cannot tell whether such a target is still there checks it, as if the apply will make it — never the record of an earlier apply taken as proof. It says so: the mark may be one+// the apply does not make (Charlie IS there, so the apply below writes Alpha alone).+test('changed-only: a dry run that cannot read whether a target it was told is deployed is there checks it, and says why — fail closed', async () => {+ const app = abcApp();+ try {+ const options = fastApply(['alpha'], { deployedKeys: ABC_KEYS });+ const warnings = [];+ const planned = await app.run({ ...options, apply: false, warn: (m) => warnings.push(String(m)) }, undefined, { failPageRows: true }).built;+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt).map((item) => item.label), ['page "Charlie"']);+ const said = warnings.filter((w) => /recorded as deployed/.test(w));+ assert.strictEqual(said.length, 1, warnings.join('\n'));+ assert.match(said[0], /^could not tell whether page "Charlie", recorded as deployed, is still in this environment \(the pages recorded as deployed: HTTP 503 .*\), so its bindings are checked as if the build will make it$/);+ const { genpage, built } = app.run(options);+ assert.ok((await built).ok);+ assert.deepStrictEqual(genpage.uploads, ['update Alpha']);+ } finally { fs.rmSync(app.appDir, { recursive: true, force: true }); }+});+test('deploy: the record keeps only the pages the spec still binds — a page it no longer names is dropped when the next is written', async () => {const { appDir, spec } = twoPageApp();const server = new FakeGenPageServer();@@ -3343,6 +3617,28 @@ test('deploy: a build whose pages read no table makes no app operation; a change} finally { app.cleanup(); }});+// A page key is a lowercase slug, so a page can be keyed `constructor` — a member of Object.prototype. The pages this run wrote are the ones+// `created.pages` holds, and a page it left alone must read as not written whatever its key is.+test('deploy: a changed-only run pins only the tables of the pages it wrote when the page it left alone is keyed constructor', async () => {+ const { appDir, spec } = makeTwoPageApp();+ try {+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), 'export default function Overview(){ return null; }', 'utf8');+ spec.pages[0].navigatesTo = undefined;+ spec.pages[1].key = 'constructor';+ spec.appShell.areas[0].groups[0].subAreas[1].page = 'constructor';+ spec.pages[0].dataSources = ['contoso_item'];+ spec.pages[1].dataSources = ['contoso_note'];+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'constructor', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');+ const { sdk } = mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });+ const genpageCli = mockGenpageCli(live);+ const r = await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PAGES_ONLY, changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys: ['overview'] } });+ assert.deepStrictEqual(genpageCli.uploads.map((u) => u.name), ['Overview'], 'only the selected page was written');+ assert.deepStrictEqual(Object.keys(r.created.pages), ['overview'], 'and only it is in the result');+ assert.deepStrictEqual(genpageCli.placements, [{ appId: APP_ID, pages: [], dataSources: ['contoso_item'] }], 'so only its table is pinned, not the table of the page keyed constructor');+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }+});+test('deploy: the pin carries the request to send before the app is written — a function the placement awaits, which sends nothing without --publish — and what it is asked to pin is still only data', async () => {const { appDir, spec } = makeTwoPageApp();try {@@ -3833,7 +4129,8 @@ async function driveBuild(spec, appDir, { genpage, engine = runBuild, runOpts =let halt = null;let result = null;try {- result = await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, retryDelayMs: 0, ...opts }, {+ // A workspace the engine is given is the build's too, as the CLI passes one to both: the build's lease is taken in it, and each attempt borrows it there.+ result = await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, retryDelayMs: 0, ...(runOpts.workspaceDir ? { workspaceDir: runOpts.workspaceDir } : {}), ...opts }, {sdk, provisionSdk: sdk, genpage, sleep: async () => {}, log: (m) => lines.push(m), warn: () => {}, verify: async () => ({ ok: true }),discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),runBuild: async (s, o) => { attempts += 1; return engine(s, { ...o, phases: PHASES, ...runOpts }); },diff --git a/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.jsindex 1eb9dd495..7f66a6207 100644--- a/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js@@ -11,7 +11,10 @@// retry follows (settleOwedPublishes; the CLI side is pinned in build-model-app.test.js).const { test } = require('node:test');const assert = require('node:assert/strict');-const { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, BuildHalt } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, BuildHalt } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');// Two tables: Project (with a form, so phase 8 already names it) and Task (no form, view or chart,diff --git a/plugins/model-apps/scripts/tests/second-app-bugs.test.js b/plugins/model-apps/scripts/tests/second-app-bugs.test.jsindex 94b850053..502863636 100644--- a/plugins/model-apps/scripts/tests/second-app-bugs.test.js+++ b/plugins/model-apps/scripts/tests/second-app-bugs.test.js@@ -210,7 +210,10 @@ test('AB#6688906: a platform icon PATH ending .svg is not flagged', () => {// --- AB#6688905: the workspace-metadata race must retry, not halt UNKNOWN -------------------------const { runSdkBuild } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');const eventSpec = () => ({diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.jsindex 2a52e9034..53cdd222a 100644--- a/plugins/model-apps/scripts/tests/source-literals.test.js+++ b/plugins/model-apps/scripts/tests/source-literals.test.js@@ -543,6 +543,445 @@ test('hasDefaultExport requires the export itself to be complete', () => {}});+// A default export may be a generic arrow. In a .tsx file TypeScript reads the `<` after `export default` by its rule for a `<` where an assignment expression starts+// (parser.ts, isParenthesizedArrowFunctionExpressionWorker, the JSX branch, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts; opensTypeParameters in+// source-literals.js): type parameters when, after an optional `const`, the first name is followed by a `,`, an `=`, or `extends` and a token that is not `=`, `>` or `/`, and+// an element otherwise. The export pattern took no `<` after `default`, so a complete page whose default export is a generic arrow was refused as having no default export.+// [what, page]+const GENERIC_ARROW_EXPORTS = [+ ['a trailing comma and a block body', 'type Props<T> = { items: T[] };\nexport default <T,>(props: Props<T>) => {\n return <div>{props.items.length}</div>;\n};\n'],+ ['a constraint and an element body', 'export default <T extends object>(p: T) => <div/>;\n'],+ ['a const modifier', 'export default <const T,>(p: T) => <div/>;\n'],+ ['a const modifier and a constraint', 'export default <const T extends readonly unknown[]>(p: T) => <div>{p.length}</div>;\n'],+ ['a default and a trailing comma', 'export default <T = string,>(p: T) => null;\n'],+ ['a default', 'export default <T = string>(p: T) => null;\n'],+ ['a constraint and a default', 'export default <T extends object = {}>(p: T) => null;\n'],+ ['two type parameters', 'export default <T, U extends T>(p: T, q: U) => null;\n'],+ ['a return type', 'export default <T,>(p: T): JSX.Element => <div/>;\n'],+ ['an object return type', 'export default <T,>(p: T): { a: T; b: string } => ({ a: p, b: "" });\n'],+ ['a generic return type', 'export default <T,>(p: T): Promise<Array<T>> => Promise.resolve([p]);\n'],+ ['a parenthesised function type for the return type', 'export default <T,>(p: T): ((x: T) => T) => (x) => x;\n'],+ ['a function type for the return type', 'export default <T,>(p: T): (x: T) => T => (x) => x;\n'],+ ['a type predicate for the return type', 'export default <T,>(p: unknown): p is T => p !== null;\n'],+ ['a conditional return type', 'export default <T,>(p: T): T extends string ? "s" : "o" => null as never;\n'],+ ['a constraint that is a function type', 'export default <T extends (a: string) => void>(cb: T) => null;\n'],+ ['a constraint that is an object type', 'export default <T extends { id: string; name: string }>(row: T) => <div>{row.id}</div>;\n'],+ ['nested type arguments', 'export default <T extends Record<string, Array<number>>>(p: T) => null;\n'],+ ['type parameters across lines, with a comment', 'export default <\n T extends object, // the row\n>(p: T) => null;\n'],+ ['a destructured parameter', 'export default <T,>({ items }: { items: T[] }) => <ul>{items.length}</ul>;\n'],+ ['a rest parameter', 'export default <T,>(...args: T[]) => null;\n'],+ ['no parameters', 'export default <T,>() => null;\n'],+ ['a default value that is an element with a parenthesis in its text', 'export default <T,>(p = <b>(</b>) => p;\n'],+ ['a comment before the "<"', 'export default /* the page */ <T,>(p: T) => null;\n'],+ ['a line break before the "<"', 'export default\n<T,>(p: T) => null;\n'],+ ['no semicolon at the end of the file', 'export default <T,>(p: T) => null'],+ ['a name beyond ASCII', 'export default <Τύπος,>(p: Τύπος) => null;\n'],+ ['an async arrow with a block body', 'export default async <T,>(p: T) => {\n await Promise.resolve(p);\n return null;\n};\n'],+ ['an async arrow with a return type', 'export default async <T extends object>(p: T): Promise<null> => null;\n'],+ ['an import, and a string that holds the same head', 'import * as React from "react";\nconst label = "<T,>";\nexport default <T,>(p: T) => <p>{label}</p>;\n'],+ // A `>` in a string or template type is no end of the type parameters, nor of a return type.+ ['a string type and a template type that hold ">"', 'export default <T extends "a>b" | `c${string}>`>(p: T): "x>y" => "x>y";\n'],+ ['a mapped return type', 'export default <T,>(p: T): { [K in keyof T]: T[K] } => p;\n'],+ ['an assertion for the return type', 'export default <T,>(p: unknown): asserts p is T => {};\n'],+ ['a return type named like a statement word, through a qualified name', 'export default <T,>(p: T): Schema.module => null as never;\n'],+ ['a name written with an escape', 'export default <\\u0054,>(p: \\u0054) => p;\n'],+ ['CRLF line endings', 'import * as React from "react";\r\nexport default <T extends object>(props: T): JSX.Element => {\r\n return <div>ok</div>;\r\n};\r\n'],+];+// A line break before the arrow is an error that TypeScript's checker reports (TS1200), not its parser, so the page compiles; Babel's parser refuses it.+const GENERIC_ARROW_EXPORT_LINE_BREAK = 'export default <T,>(p: T)\n=> null;\n';+// What stays refused: a generic arrow cut off before its body (its brackets balance, so no other check sees the cut), a `<` that TypeScript reads as an element (no+// component the host can mount, or no page that parses at all), and prose. [what, page]+const GENERIC_ARROW_REFUSALS = [+ ['cut after the parameter list', 'import * as React from "react";\nexport default <T,>(props: P<T>)'],+ ['cut before the arrow, after a return type', 'export default <T,>(props: P<T>): JSX.Element'],+ ['cut inside the return type', 'export default <T,>(props: P<T>): Promise<'],+ ['cut at the arrow', 'export default <T,>(props: P<T>) =>'],+ ['cut after the arrow and a space', 'export default <T,>(props: P<T>) => '],+ ['cut after the arrow and a line break', 'export default <T,>(props: P<T>) =>\n'],+ ['cut after the type parameters', 'export default <T extends object>'],+ ['cut after the type parameters and their trailing comma', 'export default <T,>'],+ ['cut inside the type parameters', 'export default <T,'],+ ['cut inside a constraint that holds an arrow', 'export default <T extends (a: string) => void'],+ ['cut right after the "<"', 'export default <'],+ ['cut inside the parameter list', 'export default <T,>(props: P<T>'],+ ['a parameter list, then another statement', 'export default <T,>(props: P<T>)\nconst f = () => 1;\n'],+ ['a return type, then another statement', 'export default <T,>(props: P<T>): X\nconst f = () => 1;\n'],+ ['a return type and a semicolon', 'export default <T,>(props: P<T>): X;\nf(() => 1);\n'],+ ['a body cut at an operator', 'export default <T,>(p: T) => p +'],+ ['a body cut at a cast', 'export default <T,>(p: T) => p as'],+ ['an async arrow cut after the parameter list', 'export default async <T,>(props: P<T>)'],+ ['an async arrow cut at the arrow', 'export default async <T,>(p: T) =>'],+ ['an async arrow cut inside a constraint that holds an arrow', 'export default async <T extends (a: string) => void'],+ ['an element', 'export default <div/>;\n'],+ ['an element with text', 'export default <div>Hello</div>;\n'],+ ['a fragment', 'export default <></>;\n'],+ ['one type parameter and no comma: an element in .tsx', 'export default <T>(x) => x;\n'],+ ['one type parameter and no comma, with a typed parameter', 'export default <T>(x: T) => x;\n'],+ ['`extends` and then `>`: an element', 'export default <T extends>x</T>;\n'],+ ['a constraint and no parameter list', 'export default <T extends X>text</T>;\n'],+ ['a variance modifier, which the rule reads as an element', 'export default <in T,>(x: T) => x;\n'],+ ['`await` for the name, which is no identifier in an export', 'export default <await,>(x) => x;\n'],+ ['prose that writes a generic arrow', 'The page says export default <T,>(props: P<T>) => null is required.\n'],+ ['a generic arrow in a string', 'const s = "export default <T,>(p: T) => null";\n'],+ ['a generic arrow in a comment', '// export default <T,>(p: T) => null\nconst x = 1;\n'],+ ['a generic arrow in a template', 'const t = `\nexport default <T,>(p: T) => null\n`;\n'],+];+// `yield` for the name: TypeScript's parser takes it for an identifier outside a generator (its strict-mode error is the binder's), but whether it is one takes the+// function around it, which the lexer does not track, so the rule's answer is the guess `generic` and the element is read (opensTypeParameters). Refused, as before.+const GENERIC_ARROW_GUESSED = 'export default <yield,>(x) => x;\n';++test('hasDefaultExport accepts a complete generic-arrow default export, sync and async', () => {+ for (const [what, code] of [...GENERIC_ARROW_EXPORTS, ['a line break before the arrow', GENERIC_ARROW_EXPORT_LINE_BREAK]]) {+ assert.equal(hasDefaultExport(code), true, what);+ // The whole gate accepts the page: the brackets balance and nothing is cut off.+ assert.deepStrictEqual(pageStructureProblems(code), [], what);+ }+});++test('hasDefaultExport still refuses a generic arrow cut off before its body, an element and prose', () => {+ for (const [what, code] of [...GENERIC_ARROW_REFUSALS, ['`yield` for the name', GENERIC_ARROW_GUESSED]]) {+ assert.equal(hasDefaultExport(code), false, what);+ assert.match(pageStructureProblems(code).join('\n'), /no complete default export/, what);+ }+ // Unchanged around it: an async arrow whose `<` the rule reads as an element is no generic arrow (TypeScript reads `async<T>(x: T)` as a call, and the page compile+ // refuses the arrow after it), so it is judged as it always was — an `=>` and something after it — and an async arrow with no type parameters too.+ assert.equal(hasDefaultExport('export default async <T>(x: T) => x;\n'), true);+ assert.equal(hasDefaultExport('export default async (x) => x;\n'), true);+ assert.equal(hasDefaultExport('export default async (x) =>'), false);+ // `async` and a line break: `async` is an exported name, and what follows is another statement.+ assert.equal(hasDefaultExport('export default async\n<T,>(x: T) => x;\n'), false);+ // A complete export elsewhere in the page still counts, whatever the generic arrow before it is.+ assert.equal(hasDefaultExport('export default <T,>(p: T)\nexport default function Page() { return null; }\n'), true);+});++// The return type of a generic arrow is read to its end as TypeScript reads a type, and the arrow's `=>` must come right after it. A return type may hold an `=>` of its+// own — a function or constructor type, `(p): (x: T) => T => …` — so the first `=>` after the colon is not always the arrow's, and a write cut off right after such a type+// has no arrow and no body. And any word may name a type (TypeScript reads a type's name as an identifier name): `module`, `namespace` and `declare` are names in a type,+// not the start of a statement. [what, page]+const GENERIC_ARROW_RETURN_TYPES = [+ ['a type alias named `module`, async', 'type module<T> = Promise<T>;\nexport default async <T,>(p: T): module<T> => p;\n'],+ ['a type alias named `namespace`, async', 'type namespace<T> = Promise<T>;\nexport default async <T,>(p: T): namespace<T> => p;\n'],+ ['a type alias named `declare`', 'type declare = string;\nexport default <T,>(p: T): declare => "";\n'],+ ['an assertion about a parameter named `module`', 'export default <T,>(module: unknown): asserts module is T => {};\n'],+ ['a type predicate about a parameter named `module`', 'export default <T,>(module: unknown): module is T => true;\n'],+ ['a union of names that are keywords elsewhere', 'type type = 1; type async = 2; type of = 3;\nexport default <T,>(p: T): type | async | of => 1;\n'],+ ['a function type whose one parameter is a name, then the arrow', 'export default <T,>(p: T): (A) => T => p as never;\n'],+ ['a parenthesised union, then the arrow', 'export default <T,>(p: T): (A | B) => p as never;\n'],+ ['a parenthesised object type with members, then the arrow', 'export default <T,>(p: T): ({ a: T; b: string }) => ({ a: p, b: "" });\n'],+ ['a parenthesised tuple type that is no binding pattern, then the arrow', 'export default <T,>(p: T): ([T, T][]) => [[p, p]];\n'],+ ['a constructor type for the return type', 'export default <T,>(p: T): new () => T => null as never;\n'],+ ['an abstract constructor type for the return type', 'export default <T,>(p: T): abstract new () => T => null as never;\n'],+ ['a generic function type for the return type', 'export default <T,>(p: T): <U>(x: U) => U => (x) => x;\n'],+ ['a function type that returns a function type', 'export default <T,>(p: T): (x: T) => (y: T) => T => (x) => (y) => y;\n'],+ ['a function type in a branch of a conditional type', 'export default <T,>(p: T): T extends string ? (x: T) => T : never => null as never;\n'],+ ['type arguments on a dotted name, and an array', 'export default <T,>(p: T): A.B.C<D>[] => [];\n'],+ ['a leading "|"', 'export default <T,>(p: T): | "a" | "b" => "a";\n'],+ ['an async function type for the return type', 'export default async <T,>(p: T): Promise<(x: T) => T> => (x) => x;\n'],+ // A parenthesised object type whose key is an index signature's or a mapped type's: no binding pattern (the key holds no expression), so the parentheses hold a type and+ // the arrow follows them.+ ['a parenthesised index signature', 'export default <T,>(p: T): ({ [key: string]: T }) => ({ item: p });\n'],+ ['a parenthesised index signature, async', 'export default async <T,>(p: T): ({ [key: string]: T }) => ({ item: p });\n'],+ ['a parenthesised index signature with a number key', 'export default <T,>(p: T): ({ [index: number]: T }) => [p];\n'],+ ['a parenthesised index signature with a symbol key', 'export default <T,>(p: T): ({ [key: symbol]: T }) => ({});\n'],+ ['a parenthesised index signature with a template key', 'export default <T,>(p: T): ({ [key: `data-${string}`]: T }) => ({});\n'],+ ['a parenthesised mapped type', 'export default <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n'],+ ['a parenthesised mapped type, async', 'export default async <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n'],+ ['a parenthesised mapped type with its keys remapped', 'export default <T extends object>(p: T): ({ [K in keyof T as `get${string & K}`]: () => T[K] }) => null as never;\n'],+ ['a parenthesised optional mapped type', 'export default <T extends object>(p: T): ({ [K in keyof T]?: T[K] }) => ({});\n'],+ // A binding pattern with a computed key is a function type's parameter: the arrow follows the function type.+ ['a function type whose parameter has a computed key', 'export default <T,>(p: T): ({ [key]: value }: Record<string, T>) => void => () => {};\n'],+];+// [what, page]: cut off right after a type that holds an `=>`, or a return type that takes the arrow for its own, or no body after the arrow.+const GENERIC_ARROW_RETURN_TYPE_REFUSALS = [+ ['cut after a function type for the return type', 'export default <T,>(p: T): (x: T) => T'],+ ['cut after a constructor type', 'export default <T,>(p: T): new () => T'],+ ['cut after an abstract constructor type', 'export default <T,>(p: T): abstract new () => T'],+ ['cut after a generic function type', 'export default <T,>(p: T): <U>(x: U) => U'],+ ['cut after a function type that returns an object type', 'export default <T,>(p: T): (x: T) => { a: T }'],+ ['cut after a function type that returns a tuple', 'export default <T,>(p: T): (x: T) => [T, T]'],+ ['cut after a function type whose one parameter is a name', 'export default <T,>(p: T): (A) => T'],+ ['cut after a function type in a branch of a conditional type', 'export default <T,>(p: T): T extends string ? (x: T) => T : never'],+ ['an async arrow cut after a function type for the return type', 'export default async <T,>(p: T): (x: T) => T'],+ // TypeScript reads these return types as function types, which take the `=>` that was meant for the arrow.+ ['one name in parentheses, which is a function type', 'export default <T,>(p: T): (A) => p;\n'],+ ['a binding pattern in parentheses, which is a function type', 'export default <T,>(p: T): ({ a: T }) => p;\n'],+ // A computed key that holds an expression is a binding pattern's — `K in T` is an expression, unlike `K in keyof T` — so these are function types too.+ ['a binding pattern with a computed key in parentheses', 'export default <T,>(p: T): ({ [key]: value }) => p;\n'],+ ['a binding pattern whose computed key is an `in` expression', 'export default <T,>(p: T): ({ [K in T]: boolean }) => p;\n'],+ ['a binding pattern whose computed key has a cast', 'export default <T,>(p: T): ({ [K in Keys as X]: boolean }) => p;\n'],+ ['cut after a function type whose parameter has a computed key', 'export default <T,>(p: T): ({ [key]: value }: Record<string, T>) => void'],+ // A function type after a `|` must be parenthesised (TS1385).+ ['a function type after "|"', 'export default <T,>(p: T): A | (x: T) => B => p;\n'],+ // No body after the arrow: TypeScript reports `Expression expected`.+ ['a semicolon for the body', 'export default <T,>() => ;\n'],+ ['a declaration after the arrow', 'export default <T,>() =>\nconst x = 1;\n'],+ ['a statement word after the arrow', 'export default <T,>() => return 1;\n'],+ ['an operator after the arrow', 'export default <T,>() => * 2;\n'],+ ['an async arrow with a semicolon for the body', 'export default async <T,>() => ;\n'],+];+// [what, body]: what may follow the arrow — a block, or anything that begins an expression, a word that is a keyword elsewhere included.+const GENERIC_ARROW_BODIES = [+ ['an empty block', '{}'], ['a number', '0'], ['a name that is a keyword elsewhere', 'module'], ['`type`', 'type'], ['`let`, a name to the parser', 'let'],+ ['`this`', 'this'], ['`new`', 'new Map()'], ['`typeof`', 'typeof p'], ['a class', 'class {}'], ['a function', 'function () {}'], ['`void`', 'void 0'],+ ['a dynamic import', 'import("./x")'], ['a prefix increment', '++n'], ['a negative number', '-1'], ['a negation', '!p'], ['an array', '[p]'],+ ['a parenthesised expression', '(p)'], ['a regular expression', '/re/.test("s")'], ['a template', '`t`'], ['a string', '"s"'], ['an element', '<div/>'],+ ['a generic arrow', '<U,>(u: U) => u'], ['a fraction', '.5'],+];++test('hasDefaultExport reads a generic arrow\'s return type to its end, and wants a body after the arrow', () => {+ for (const [what, code] of GENERIC_ARROW_RETURN_TYPES) {+ assert.equal(hasDefaultExport(code), true, what);+ assert.deepStrictEqual(pageStructureProblems(code), [], what);+ }+ for (const [what, code] of GENERIC_ARROW_RETURN_TYPE_REFUSALS) {+ assert.equal(hasDefaultExport(code), false, what);+ assert.match(pageStructureProblems(code).join('\n'), /no complete default export/, what);+ }+ for (const [what, body] of GENERIC_ARROW_BODIES) {+ const code = `let n = 0;\nexport default <T,>(p: T) => ${body};\n`;+ assert.equal(hasDefaultExport(code), true, what);+ assert.deepStrictEqual(pageStructureProblems(code), [], what);+ }+});++// A known limit, pinned as it is: a default value in a binding pattern of a function type's parameter is passed over to the next `,` or closing bracket at its own level,+// and the comma between a generic call's type arguments (`f<T, U>()`) is taken for one. The pattern then reads as none, the parentheses as a parenthesised type, and the+// function type's own `=>` as the arrow, so a write cut right after such a function type — no arrow, no body — is accepted here. The page compile refuses it (TypeScript:+// `'=>' expected`). The page it was cut from is accepted, as it should be.+test('known limit: a generic call with two type arguments in a default value of a function type\'s parameter', () => {+ assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = f<T,T>() }) => T'), true, 'the cut is accepted: the known limit');+ assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = f<T,T>() }) => T => null as never;\n'), true);+ // With the call in parentheses the default value is passed over whole, the pattern is read, and the cut is refused.+ assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = (f<T,T>()) }) => T'), false);+ assert.equal(hasDefaultExport('export default <T,>(p: T): ({ a = (f<T,T>()) }) => T => null as never;\n'), true);+});++// Known limits, pinned as they are: two rare return types that TypeScript parses and the gate refuses (2.18.0 refused every synchronous generic-arrow default+// export, and admitted the async forms of both, which are now refused too). A binding+// pattern's computed key is read as an expression only as far as telling an index signature's or a mapped type's key from one needs, and any group in parentheses counts+// as an operand: `K in (keyof T)` reads as an expression, so `({ [K in (keyof T)]: boolean })` reads as a function type's parameters, which take the arrow. And a key the+// reading does not know — one that starts with a regular expression — is taken for no expression: the parentheses around a function type's parameters then read as a+// parenthesised type, the function type's `=>` as the arrow, and a leading `|` of its own return type as no body. The workarounds (AGENTS.md, "TSX source lexer — known+// limits") are accepted.+test('known limits: a mapped type with its key type in parentheses, and a computed key the reading does not know', () => {+ const refused = [];+ for (const key of ['(keyof T)', '((keyof T))', '(keyof T) as K', '(T extends object ? keyof T : never)']) {+ for (const modifier of ['', 'async ']) refused.push(`export default ${modifier}<T extends object>(p: T): ({ [K in ${key}]: boolean }) => null as never;\n`);+ }+ const regexKey = '<T,>(p: T): ({ [/key/.source]: value }: Record<string, T>) =>';+ refused.push(`export default ${regexKey} | typeof value | null => () => null;\n`, `export default async ${regexKey} | typeof value | null => () => null;\n`);+ for (const code of refused) assert.equal(hasDefaultExport(code), false, `refused, a known limit: ${JSON.stringify(code)}`);+ // The workarounds: no parentheses around the key's type, none around the return type, a type alias; no leading `|`, a key written as a string. And an arrow+ // without type parameters keeps its reading.+ for (const code of [+ 'export default <T extends object>(p: T): ({ [K in keyof T]: boolean }) => null as never;\n',+ 'export default <T extends object>(p: T): { [K in (keyof T)]: boolean } => null as never;\n',+ 'type Flags<T> = { [K in (keyof T)]: boolean };\nexport default <T extends object>(p: T): Flags<T> => null as never;\n',+ `export default ${regexKey} typeof value | null => () => null;\n`,+ 'export default <T,>(p: T): ({ ["key"]: value }: Record<string, T>) => | typeof value | null => () => null;\n',+ 'type Pick1<T> = (pair: Record<string, T>) => | T | null;\nexport default <T,>(p: T): Pick1<T> => () => null;\n',+ 'export default (p: T): ({ [/key/.source]: value }: Record<string, T>) => | typeof value | null => () => null;\n',+ ]) assert.deepStrictEqual(pageStructureProblems(code), [], code);+ // A group that holds an expression is one, as TypeScript reads it: these are function types that take the arrow, refused here and by TypeScript.+ const grouped = ['(a + b)', 'keyof(T)'].map((key) => `export default <T,>(p: T): ({ [${key}]: v }) => p;\n`);+ for (const code of grouped) assert.equal(hasDefaultExport(code), false, code);+ // With the TypeScript parser oracle set: TypeScript parses every page refused above — a known limit, not a cut — and none of the grouped expressions.+ const ts = loadTypescriptOracle();+ if (!ts) return;+ const diagnostics = (code) => ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX).parseDiagnostics.length;+ for (const code of refused) assert.strictEqual(diagnostics(code), 0, `TypeScript parses ${JSON.stringify(code)}`);+ for (const code of grouped) assert.ok(diagnostics(code) > 0, `TypeScript refuses ${JSON.stringify(code)}`);+});++// An arrow with no type parameters is read as it always was (defaultExportIsComplete reads it, not genericArrowIsComplete), whatever its return type holds.+test('an arrow without type parameters keeps its reading of a return type', () => {+ for (const type of ['({ [key: string]: T })', '({ [K in keyof T]: boolean })', '({ [key]: value })', '(x: T) => T', 'module<T>', '(A) => T']) {+ assert.equal(hasDefaultExport(`export default (p: T): ${type} => null as never;\n`), true, type);+ }+});++// The reading recurses once per level of a return type that nests function types, conditional types or prefix operators; past a depth no page has, the return type is+// refused rather than read, and the text is never read twice per level: a deep or long return type neither throws nor takes long.+test('hasDefaultExport refuses a return type nested deeper than any page has, without overflowing the stack', () => {+ const started = Date.now();+ for (const deep of ['(x: T) => '.repeat(20000), 'T extends U ? X : '.repeat(20000), 'keyof '.repeat(20000), '!'.repeat(20000)]) {+ assert.equal(hasDefaultExport(`export default <T,>(p: T): ${deep}T => p;\n`), false);+ }+ // Long, but flat: a union of 20,000 members, and a group 20,000 deep, which is passed over as a whole.+ assert.equal(hasDefaultExport(`export default <T,>(p: T): ${'"a" | '.repeat(20000)}"b" => "b";\n`), true);+ assert.equal(hasDefaultExport(`export default <T,>(p: T): ${'('.repeat(20000)}T${')'.repeat(20000)} => p;\n`), true);+ assert.ok(Date.now() - started < 10000, `took ${Date.now() - started} ms`);+});++// The pages above, and a matrix of heads, parameter lists, return types and bodies, sync and async, against TypeScript 5.8 — the compiler the SDK builds a page with — and+// Babel. The gate accepts exactly the pages TypeScript parses as an arrow with type parameters, and refuses every text cut off between the `<` and the end of the arrow,+// which TypeScript refuses too. Babel parses every page the gate accepts as such an arrow as well; it also takes `<T>(x) => x` for one, which TypeScript reads as an+// element in .tsx, so it is no judge of the refusals. A second matrix holds return types of every form TypeScript's parser reads — names that are keywords elsewhere,+// predicates, function and constructor types that hold an `=>` of their own, parenthesised types that are and are not function types, conditional types, JSDoc forms — with+// every cut of each, and a third the first token of the body.+test('TypeScript and Babel: the gate accepts exactly the generic-arrow default exports TypeScript parses, and refuses every cut before the body', (t) => {+ const ts = loadTypescriptOracle();+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');+ // What TypeScript reads `export default` as: 'error' where the page does not parse.+ const typeScriptReads = (code) => {+ const source = ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ if (source.parseDiagnostics.length > 0) return 'error';+ const exported = source.statements.find((statement) => ts.isExportAssignment(statement));+ if (!exported) return 'no export';+ if (ts.isArrowFunction(exported.expression)) return exported.expression.typeParameters ? 'generic arrow' : 'arrow';+ return ts.SyntaxKind[exported.expression.kind];+ };+ const refusedByTypeScript = (reading) => reading === 'error' || reading === 'no export' || /^Jsx/.test(reading);+ for (const [what, code] of GENERIC_ARROW_EXPORTS) assert.strictEqual(typeScriptReads(code), 'generic arrow', what);+ assert.strictEqual(typeScriptReads(GENERIC_ARROW_EXPORT_LINE_BREAK), 'generic arrow');+ for (const [what, code] of GENERIC_ARROW_REFUSALS) assert.ok(refusedByTypeScript(typeScriptReads(code)), `${what}: TypeScript reads ${typeScriptReads(code)}`);+ assert.strictEqual(typeScriptReads(GENERIC_ARROW_GUESSED), 'generic arrow', 'the one refusal TypeScript parses: a guess of the lexer');++ const GENERIC_HEADS = ['<T,>', '<T extends object>', '<const T,>', '<const T extends readonly unknown[]>', '<T = string>', '<T extends object = {}>', '<T, U extends T>',+ '<T extends (a: string) => void>', '<T extends Record<string, Array<number>>>', '<\n T,\n>', '<T /* c */,>', '<T extends X>'];+ // Heads the rule reads as an element: `<T>`, `<T extends>`, a modifier, a tag name, a fragment.+ const ELEMENT_HEADS = ['<T>', '<T extends>', '<in T,>', '<div>', '<>'];+ const PARAMETERS = ['()', '(p: T)', '({ a }: { a: T }, ...rest: T[])', '(p = <b>(</b>)'];+ const RETURNS = ['', ': JSX.Element', ': { a: T; b: string }', ': Promise<Array<T>>', ': ((x: T) => T)'];+ const BODIES = [' => null', ' => <div/>', ' => {\n return null;\n}'];+ const exports = [];+ for (const head of [...GENERIC_HEADS, ...ELEMENT_HEADS]) exports.push(['', head]);+ // After `async` a `<` is never an element, and one the rule reads as an element is judged as before (above): only the generic heads.+ for (const head of GENERIC_HEADS) exports.push(['async ', head]);+ let accepted = 0;+ let cuts = 0;+ for (const [modifier, head] of exports) {+ for (const parameters of PARAMETERS) {+ for (const returns of RETURNS) {+ for (const body of BODIES) {+ const code = `export default ${modifier}${head}${parameters}${returns}${body};\n`;+ const reading = typeScriptReads(code);+ assert.ok(reading === 'generic arrow' || refusedByTypeScript(reading), `${JSON.stringify(code)}: TypeScript reads ${reading}`);+ assert.strictEqual(pageStructureProblems(code).length === 0, reading === 'generic arrow', `${JSON.stringify(code)}: TypeScript reads ${reading}`);+ if (reading === 'generic arrow') accepted += 1;+ }+ // Every cut from the `<` to the end of the arrow. TypeScript reads no arrow in any of them: it reports an error, or reads what is left as something else+ // (`export default async <T` is the comparison `async < T`, which is no component either).+ const whole = `export default ${modifier}${head}${parameters}${returns} => null;\n`;+ const arrowEnd = whole.lastIndexOf('=>') + 2;+ for (let end = whole.indexOf('<') + 1; end <= arrowEnd; end += 1) {+ const cut = whole.slice(0, end);+ assert.ok(!/arrow$/.test(typeScriptReads(cut)), `${JSON.stringify(cut)}: TypeScript reads an arrow in the cut`);+ assert.strictEqual(hasDefaultExport(cut), false, JSON.stringify(cut));+ cuts += 1;+ }+ }+ }+ }+ assert.ok(accepted >= 1000, `generic-arrow pages accepted: ${accepted}`);++ for (const [what, code] of GENERIC_ARROW_RETURN_TYPES) assert.strictEqual(typeScriptReads(code), 'generic arrow', what);+ for (const [what, code] of GENERIC_ARROW_RETURN_TYPE_REFUSALS) assert.ok(refusedByTypeScript(typeScriptReads(code)), `${what}: TypeScript reads ${typeScriptReads(code)}`);+ for (const [what, body] of GENERIC_ARROW_BODIES) assert.strictEqual(typeScriptReads(`let n = 0;\nexport default <T,>(p: T) => ${body};\n`), 'generic arrow', what);+ // [return type, whether Babel reads it too]. TypeScript's parser reads a keyword as a type's name and the JSDoc forms, which only its checker refuses; Babel refuses them.+ const RETURN_TYPES = [+ ['T', true], ['module', true], ['module<T>', true], ['namespace', true], ['declare', true], ['type', true], ['async', true], ['of', true], ['is', true], ['asserts', true],+ ['A.B.C<D>[]', true], ['A.if', true], ['T[K]', true], ['T[][]', true], ['Promise<Array<T>>', true], ['Map<string, (x: T) => T>', true],+ ['if', false], ['const', false], ['default', false], ['class', false], ['function', false], ['let', false], ['yield', false],+ ['void', true], ['null', true], ['undefined', true], ['true', true], ['-1', true], ['1n', true], ['"s"', true], ['`a${string}`', true], ['unique symbol', true], ['this', true],+ ['keyof T', true], ['readonly T[]', true], ['infer U', true], ['typeof p', true], ['typeof p.x<T>', true], ['import("x").Y<T>', true], ['typeof import("x")', true],+ ['A | B', true], ['| A | B', true], ['& A', true], ['A & B | C', true], ['T extends U ? X : Y', true], ['A extends B ? C : D extends E ? F : G', true],+ ['T extends string ? (x: T) => T : never', true],+ ['{ a: T; b: string }', true], ['{ [K in keyof T]: T[K] }', true], ['[a: T, b?: string, ...rest: T[]]', true], ['{}', true],+ ['p is T', true], ['module is T', true], ['this is T', true], ['asserts p', true], ['asserts p is T', true], ['asserts this', true], ['asserts module is T', true],+ ['(x: T) => T', true], ['() => void', true], ['(...a: T[]) => void', true], ['(this: Window) => void', true], ['(a?) => void', true], ['({ a }: X) => void', true],+ ['(x: T) => (y: T) => T', true], ['(x: T) => { a: T }', true], ['(x: T) => [T, T]', true], ['<U>(x: U) => U', true], ['new () => T', true], ['abstract new () => T', true],+ ['(A) => T', true], ['(x: T) => x is T', true], ['(public x) => void', false], ['(a = 1) => void', false],+ ['(A | B)', true], ['(A[])', true], ['((x: T) => T)', true], ['({ a: T; b: string })', true], ['([A, B][])', true], ['({ a: T })', true], ['({ a })', true], ['({})', true], ['([A, B])', true],+ ['?string', false], ['string?', false], ['!string', false], ['T!', false], ['*', false], ['function(string): number', false],+ ['A | (x: T) => B', true], ['A & new () => B', true], ['keyof', true], ['new', true], ['this.x', true], ['A\n[]', true], ['Promise\n<T>', true], ['T\nextends U ? X : Y', true],+ ['p\nis T', true], ['A || B', true],+ // Parenthesised object types whose key is an index signature's or a mapped type's (no expression, so no binding pattern): types, and the arrow follows.+ ['({ [key: string]: T })', true], ['({ [index: number]: T })', true], ['({ [key: symbol]: T })', true], ['({ [key: `data-${string}`]: T })', true],+ ['({ [key: string]: T; a: T })', true], ['({ [key: string, x]: T })', false], ['({ [K in keyof T]: boolean })', true],+ ['({ [K in keyof T as `get${string & K}`]: () => T[K] })', true], ['({ [K in keyof T]?: T[K] })', true], ['({ readonly [K in keyof T]: T[K] })', true],+ ['({ -readonly [K in keyof T]-?: T[K] })', true],+ // A computed key that holds an expression makes a binding pattern, and the parentheses a function type's parameters: these take the arrow (TypeScript refuses the+ // pages), and with a return type of their own they are function types followed by the arrow.+ ['({ [k]: v })', true], ['({ [K in T]: boolean })', true], ['({ [K in Keys as X]: boolean })', true], ['({ [K in "a" | "b"]: boolean })', true],+ ['({ ["a"]: v, [f(x)]: w })', true], ['({ [a ? b : c]: v })', true], ['({ [k as K]: v })', true], ['({ [typeof k]: v })', true], ['({ [k!]: v })', true],+ ['({ [-1]: v })', true], ['({ [K in Union<A>]: v })', true], ['({ [k]: v }: X) => void', true], ['({ [k]: v = 1, ["s"]: w }: X) => void', true],+ ['({ [a ? b : c]: v }) => T', true], ['({ [K in T]: v }) => T', true], ['({ [new X()]: v }: X) => void', true],+ ];+ const RETURN_BODIES = [' => null', ' => (x: T) => x', ' => {\n return null as never;\n}'];+ const returnPage = (modifier, type, body) => `export default ${modifier}<T,>(p: T): ${type}${body};\n`;+ let returnPages = 0;+ for (const modifier of ['', 'async ']) {+ for (const [type] of RETURN_TYPES) {+ for (const body of RETURN_BODIES) {+ const code = returnPage(modifier, type, body);+ const reading = typeScriptReads(code);+ assert.strictEqual(pageStructureProblems(code).length === 0, reading === 'generic arrow', `${JSON.stringify(code)}: TypeScript reads ${reading}`);+ if (reading === 'generic arrow') returnPages += 1;+ }+ // Every cut from the end of the parameter list to the end of the arrow.+ const whole = returnPage(modifier, type, ' => null');+ const arrowEnd = whole.lastIndexOf('=>') + 2;+ for (let end = whole.indexOf('):') + 1; end <= arrowEnd; end += 1) {+ const cut = whole.slice(0, end);+ assert.ok(!/arrow$/.test(typeScriptReads(cut)), `${JSON.stringify(cut)}: TypeScript reads an arrow in the cut`);+ assert.strictEqual(hasDefaultExport(cut), false, JSON.stringify(cut));+ cuts += 1;+ }+ }+ }+ assert.ok(returnPages >= 400, `pages with a return type accepted: ${returnPages}`);+ // The first token after the arrow: a block or what begins an expression is a body; a `;`, a closing bracket, an operator or a word that only begins a statement is none.+ const BODY_STARTS = [...GENERIC_ARROW_BODIES.map(([, body]) => body), ';', ')', ']', '}', ',', ':', '?', '=', '*', '%', '|', '&', '^', '>', '.x', '...x', '=> 1', '@d class {}',+ 'break', 'case', 'catch', 'const x = 1', 'continue', 'debugger', 'default', 'do', 'else', 'enum', 'export', 'extends', 'finally', 'for', 'if', 'in', 'instanceof', 'return 1',+ 'switch', 'throw p', 'try', 'var x', 'while', 'with', 'static', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'async', 'await p', 'yield', 'null',+ 'true', 'false', 'super.x', 'delete p.x'];+ for (const body of BODY_STARTS) {+ // A `;` ends each page: a page that ends in a word some statements need more after (`let`, `yield`) is read as cut off, whatever comes before it (DANGLING_TAIL).+ const code = `let n = 0;\nexport default <T,>(p: T) => ${body};\n`;+ const reading = typeScriptReads(code);+ assert.strictEqual(hasDefaultExport(code), reading === 'generic arrow', `${JSON.stringify(code)}: TypeScript reads ${reading}`);+ }+ t.diagnostic(`${accepted} generic-arrow pages accepted as TypeScript parses them, ${returnPages} with a return type; ${cuts} cuts refused; ${BODY_STARTS.length} body starts`);++ const babel = loadBabelOracle();+ if (!babel) return t.diagnostic('no Babel parser oracle: set BABEL_ORACLE_PATH to an @babel/parser package to compare the readings');+ const babelReads = (code) => {+ let tree;+ try {+ tree = babel.parse(code, { sourceType: 'module', plugins: ['jsx', 'typescript'] });+ } catch {+ return 'error';+ }+ const exported = tree.program.body.find((statement) => statement.type === 'ExportDefaultDeclaration');+ if (!exported) return 'no export';+ const value = exported.declaration;+ return value.type === 'ArrowFunctionExpression' && value.typeParameters ? 'generic arrow' : value.type;+ };+ for (const [what, code] of GENERIC_ARROW_EXPORTS) assert.strictEqual(babelReads(code), 'generic arrow', what);+ assert.strictEqual(babelReads(GENERIC_ARROW_EXPORT_LINE_BREAK), 'error', 'Babel refuses a line break before the arrow');+ for (const [modifier, head] of exports.filter(([, head]) => !ELEMENT_HEADS.includes(head))) {+ for (const parameters of PARAMETERS) {+ for (const returns of RETURNS) {+ for (const body of BODIES) {+ const code = `export default ${modifier}${head}${parameters}${returns}${body};\n`;+ assert.strictEqual(babelReads(code), 'generic arrow', JSON.stringify(code));+ }+ }+ }+ }+ for (const [what, code] of GENERIC_ARROW_RETURN_TYPES) assert.strictEqual(babelReads(code), 'generic arrow', what);+ for (const modifier of ['', 'async ']) {+ for (const [type, babelReadsIt] of RETURN_TYPES) {+ if (!babelReadsIt) continue;+ for (const body of RETURN_BODIES) {+ const code = returnPage(modifier, type, body);+ if (pageStructureProblems(code).length === 0) assert.strictEqual(babelReads(code), 'generic arrow', JSON.stringify(code));+ }+ }+ }+});+test('endsMidStatement distinguishes dangling operators from postfix and JSX or regex closers', () => {for (const [what, code] of [['relational greater-than needs a right operand', 'const count = 1;\nexport default () => count >'],diff --git a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js b/plugins/model-apps/scripts/tests/table-columns-in-create.test.jsindex 92264e568..8b597eeab 100644--- a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js+++ b/plugins/model-apps/scripts/tests/table-columns-in-create.test.js@@ -16,6 +16,8 @@ const os = require('node:os');const path = require('node:path');const { makeRunner, provisionDataModel, BuildHalt } = require('../lib/entity-provision.js');const { hash } = require('./helpers/read-probe.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');const ORG = 'https://contoso.crm.dynamics.com';@@ -528,6 +530,9 @@ function oneTable(columns, primaryAttribute = { schemaName: 'new_name', displayNentities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns }],};}+// A spec the engine APPLIES names its app, as every spec the build accepts does: an apply holds the app's build lease, which is keyed by the app's+// unique name (lib/app-operation-lease.js). The phases these tests run never read it.+const asApp = (spec) => ({ ...spec, app: { name: 'Tickets' } });test('a new table is created with only its primary name attribute and its ordinary columns follow in ONE change set instead of one request each, with the same results and events', async () => {const before = await provisionOver(ticketSpec(), { inlineColumns: false });@@ -955,8 +960,10 @@ test('a change set the budget had room to wait for and the client\'s sends ran o});test('through the build, a change set the budget has no room to wait for halts the build once with the budget\'s halt — it is not run again, waits for nothing and creates no column one by one', async () => {- const { buildModelApp, isTransientHalt } = require('../build-model-app.js');- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { buildModelApp: buildModelAppInPlace, isTransientHalt } = require('../build-model-app.js');+ const buildModelApp = inOwnFolder(buildModelAppInPlace);+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeThrottleBudget } = require('../lib/throttle-budget.js');const dv = fakeDataverse({ batchFails: () => ({ status: 429, headers: { 'retry-after': '600' }, body: TABLE_LOCKED_BODY }) });const warnings = [];@@ -1105,8 +1112,10 @@ test('a length step the runner stopped before it began is not a length that was});test('through the build, the budget refusing the first of two owed name lengths halts the build once — the second table is set, the length refused is not sent again, and the next run finishes', async () => {- const { buildModelApp, isTransientHalt } = require('../build-model-app.js');- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { buildModelApp: buildModelAppInPlace, isTransientHalt } = require('../build-model-app.js');+ const buildModelApp = inOwnFolder(buildModelAppInPlace);+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { makeThrottleBudget } = require('../lib/throttle-budget.js');const dv = fakeDataverse({ updateFails: firstLengthThrottled() });const spec = { schemaVersion: 2, ...twoOwedLengths({ key: true }), app: { name: 'Budget app' } };@@ -2036,7 +2045,8 @@ test('a length that cannot be set while the phase is halting is a failed, warned// table, keeps its name column as it finds it: one halt, one set. "Nothing labelled is created after the read that sets it" is therefore a claim about one attempt: the retry// creates what the halt kept the first attempt from, after that attempt's read (alignPrimaryNameLength). This is run through the build's own retry loop.test('after a transient halt that follows a sized table\'s create, the length is set exactly once — by the attempt that created the table — and the retry, which finds the table, does not set it again', async () => {- const { buildModelApp } = require('../build-model-app.js');+ const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+ const buildModelApp = inOwnFolder(buildModelAppInPlace);const spec = {app: { name: 'Ticket Desk' },solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },@@ -2754,6 +2764,39 @@ test('a key that waits and that the platform then refuses, or finds already therassert.deepStrictEqual(finished(there).slice(-1), [['skip', 'alt key new_ticket.new_namekey (exists)']]);});+// A key whose columns another key of the table is over: the platform allows one key per set of columns, and answers the create of a second+// one HTTP 400 0x80060894, "An entity key with the selected attributes already exists on entity." (the reference's words), whose English+// words read as "already exists". The build decides it by its code instead, from the keys the table holds, wherever the key is made: here+// the keys that wait for the length step, and those made ahead of it because their label goes out in several languages.+const sameColumnSet = (a, b) => [...a].map((c) => c.toLowerCase()).sort().join('\n') === [...b].map((c) => c.toLowerCase()).sort().join('\n');+const columnsTaken = (body, table) => ([...table.keys.values()].some((k) => sameColumnSet(k.body.KeyAttributes, body.KeyAttributes))+ ? { status: 400, headers: {}, body: { error: { code: '0x80060894', message: 'An entity key with the selected attributes already exists on entity.' } } }+ : null);++test('a key that waits for the length, refused because another key of the table is over its columns (0x80060894), stops the build naming that key: its words do not make it a skip', async () => {+ const twin = { schemaName: 'new_namekey2', displayName: 'Name Key 2', columns: ['new_name'] };+ const run = await provisionOver(keyedTable([NAME_KEY, twin]), { dataverse: { keyFails: columnsTaken }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops');+ assert.match(run.error.message, /^data-model failed: alt key new_ticket\.new_namekey2 was not created: the table new_ticket already has the key new_namekey over the same column \(new_name\), and the spec declares both/);+ assert.deepStrictEqual(finished(run).slice(-3), [['ok', 'primary column length new_ticket.new_name -> 120'], ['ok', 'alt key new_ticket.new_namekey'], ['error', 'alt key new_ticket.new_namekey2']], 'both keys waited for the length step');+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').keys.keys()], ['new_namekey']);+ const lines = run.dv.log.map(requestLine);+ assert.strictEqual(lines[lines.length - 1], "GET /EntityDefinitions(LogicalName='new_ticket')?$select=LogicalName,EntitySetName&$expand=Keys($select=SchemaName,KeyAttributes)", 'the keys are read after the refusal, by the narrow read that finds the table — no label in it');+ assert.deepStrictEqual(run.warnings, [], 'nothing about the length: it was set');+});++test('a key labelled in several languages, made ahead of the length step and refused because another key of the table is over its columns, stops the build naming that key — and is not warned about as a key too large for its column', async () => {+ const first = { schemaName: 'new_namekey', displayName: { 1033: 'Name Key', 3082: 'Clave del nombre' }, columns: ['new_name'] };+ const twin = { schemaName: 'new_namekey2', displayName: { 1033: 'Name Key 2', 3082: 'Otra clave del nombre' }, columns: ['new_name'] };+ const run = await provisionOver(keyedTable([first, twin]), { dataverse: { keyFails: columnsTaken }, capture: true });+ assert.ok(run.error instanceof BuildHalt, 'the build stops');+ assert.match(run.error.message, /^data-model failed: alt key new_ticket\.new_namekey2 was not created: the table new_ticket already has the key new_namekey over the same column \(new_name\), and the spec declares both/);+ const lines = run.dv.log.map(requestLine);+ assert.ok(lines.filter((l) => /\/Keys$/.test(l)).length === 2 && lines.findIndex((l) => l.startsWith('PUT ')) > lines.lastIndexOf("POST /EntityDefinitions(LogicalName='new_ticket')/Keys"), 'both keys were asked for ahead of the length step');+ assert.deepStrictEqual(run.warnings.filter((w) => /alt key new_ticket\.new_namekey2/.test(w)), [], 'the platform refused the key for its columns, not its size');+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, 'the length is still set as the build stops');+});+// What the build's own retry does with a name column length that an attempt which created the table left unset. The build runs a phase// that halts on a transient answer again (build-model-app.js); the attempt that created the table sets the length in its `finally`, but// that step can fail too — the lock that stopped the phase may still be held — and the retry, which finds the table, used to leave its@@ -2764,8 +2807,10 @@ test('a key that waits and that the platform then refuses, or finds already ther// stub misbehaves: the first N requests of a kind answer 503 — and, for the writes of the table, change nothing. `arrange(dv)` is a// last word on the stub, made after the faults are in place: a test wraps the transport in it (swapAfterIdentityRead).async function buildWithRetries(spec, { dataverse = OVERRIDING, faults = {}, arrange, halts = false } = {}) {- const { buildModelApp } = require('../build-model-app.js');- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+ const buildModelApp = inOwnFolder(buildModelAppInPlace);+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const dv = fakeDataverse(dataverse);const left = { createTable: faults.createTable || 0, createFile: faults.createFile || 0, setLength: faults.setLength || 0 };const refuse503 = (what, path, body) => { dv.log.push({ method: what, path: `(503) ${path}`, body }); return { status: 503, headers: {}, body: { error: { message: 'Service Unavailable' } } }; };@@ -3168,10 +3213,11 @@ test('settleOwedLengths: a build that stops for good sets what no attempt got as});test('an attempt that halts before its data-model phase hands on what it was given, unpaid and untried — and a build that stops there settles it', async () => {- const { runSdkBuild, settleOwedLengths } = require('../lib/sdk-build.js');+ const { runSdkBuild: runSdkBuildInPlace, settleOwedLengths } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);let blocked = true;const dv = fakeDataverse({ updateFails: () => (blocked ? refusal() : null) });- const spec = oneTable([], asksFor(120));+ const spec = asApp(oneTable([], asksFor(120)));const owed = new Map();await provisionAgain(dv, spec, { owedLengths: owed });assert.strictEqual(dv.tables.get('new_ticket').primaryLength, 850, 'the first attempt made the table and could not set its length');@@ -3189,10 +3235,11 @@ test('an attempt that halts before its data-model phase hands on what it was giv});test('runSdkBuild carries nothing on a halt when nothing is owed and nothing was handed to it', async () => {- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const stub = { queryRecords: async () => { throw new Error('the environment is not answering'); } };for (const owedLengths of [undefined, [], 'new_ticket', [null, 7, {}, { table: '' }]]) {- const halted = await runSdkBuild(oneTable([], asksFor(120)), { sdk: stub, provisionSdk: stub, apply: true, phases: ['solution'], owedLengths }).then(() => null, (err) => err);+ const halted = await runSdkBuild(asApp(oneTable([], asksFor(120))), { sdk: stub, provisionSdk: stub, apply: true, phases: ['solution'], owedLengths }).then(() => null, (err) => err);assert.match(halted.message, /not answering/);assert.strictEqual(halted.owedLengths, undefined, JSON.stringify(owedLengths));}@@ -3369,8 +3416,10 @@ test('settleOwedLengths: a build that stops for good does not set the length of});test('the final settle of a build that stops for good, after a retry that never reached the data-model phase, leaves a table another maker made again alone — and the halt is still what is reported', async () => {- const { buildModelApp } = require('../build-model-app.js');- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+ const buildModelApp = inOwnFolder(buildModelAppInPlace);+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);let blocked = true;let refuseFile = true;const dv = fakeDataverse({ updateFails: () => (blocked ? refusal() : null) });@@ -4087,12 +4136,13 @@ test('a key moved after the length step because it could not fit, whose size the// sent as, so the plan cannot disagree with the apply about it — whichever language the spec, the command line and the label name. This// goes through the entry both of them share (runSdkBuild), with the same spec and the same options: only `apply` differs.test('the dry-run plan and the apply put a key over the name column in the same place, whichever language the spec, the command line and the label name', async () => {- const { runSdkBuild } = require('../lib/sdk-build.js');+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const kinds = (labels) => labels.filter((l) => /^(alt key|primary column length) /.test(l)).map((l) => (l.startsWith('alt key') ? 'key' : 'length'));for (const specLanguage of [undefined, 1033, 3082]) {for (const override of [undefined, 1033, 3082]) {for (const [what, displayName] of [['a string', 'Name Key'], ['a map of 1033', { 1033: 'Name Key' }], ['a map of 3082', { 3082: 'Clave' }], ['a map of both', { 1033: 'Name Key', 3082: 'Clave' }]]) {- const spec = keyedTable([MAP_KEY(displayName)]);+ const spec = asApp(keyedTable([MAP_KEY(displayName)]));if (specLanguage) spec.languageCode = specLanguage;const dv = fakeDataverse(HONOURING);const sdk = await realSdk(dv.httpClient);@@ -4115,8 +4165,9 @@ test('the dry-run plan and the apply put a key over the name column in the same});test('a spec written in one language and built with the command line\'s other language: the plan lists a one-language key where the apply makes it, after the length', async () => {- const { runSdkBuild } = require('../lib/sdk-build.js');- const spec = keyedTable([MAP_KEY({ 3082: 'Clave' })]);+ const { runSdkBuild: runSdkBuildInPlace } = require('../lib/sdk-build.js');+ const runSdkBuild = inOwnFolder(runSdkBuildInPlace);+ const spec = asApp(keyedTable([MAP_KEY({ 3082: 'Clave' })]));spec.languageCode = 3082;const dv = fakeDataverse(HONOURING);const sdk = await realSdk(dv.httpClient);diff --git a/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js b/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.jsindex 6bac9b7db..f0f5c9359 100644--- a/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js+++ b/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js@@ -20,7 +20,10 @@ const bundle = require('../vendor/cds-maker-sdk.cjs');const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');const { runTeardown } = require('../lib/sdk-teardown.js');const { findExistingTable, provisionDataModel, BuildHalt } = require('../lib/entity-provision.js');-const { runSdkBuild, annotateLivePlan, planFor } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, annotateLivePlan, planFor } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { verifySpec } = require('../lib/verify-spec.js');const { readerFor } = require('../verify-model-app.js');const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');diff --git a/plugins/model-apps/scripts/tests/view-filter-labels.test.js b/plugins/model-apps/scripts/tests/view-filter-labels.test.jsindex d22dd5492..d178f429d 100644--- a/plugins/model-apps/scripts/tests/view-filter-labels.test.js+++ b/plugins/model-apps/scripts/tests/view-filter-labels.test.js@@ -34,11 +34,15 @@ const {makeChoiceReader,makeGlobalChoiceReader,} = require('../lib/view-filter-labels.js');-const { runSdkBuild, viewDef, annotateLivePlan, planFor, BuildHalt } = require('../lib/sdk-build.js');+// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { runSdkBuild: runSdkBuildInPlace, viewDef, annotateLivePlan, planFor, BuildHalt } = require('../lib/sdk-build.js');+const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { verifySpec } = require('../lib/verify-spec.js');const { lintAppSpec } = require('../lib/spec-lint.js');const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');-const { isTransientHalt, buildModelApp } = require('../build-model-app.js');+const { isTransientHalt, buildModelApp: buildModelAppInPlace } = require('../build-model-app.js');+const buildModelApp = inOwnFolder(buildModelAppInPlace);const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');diff --git a/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js b/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.jsindex 02bd1161b..32374cce5 100644--- a/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js+++ b/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js@@ -7,12 +7,13 @@// second create of the name is refused. Before the build handled it, the step threw before it recorded the row or added it to the solution, and every// run after that found the name and reused the row untouched: outside the solution, its content never confirmed. Now the build records the row (in the// run's result, and in the workspace: lib/web-resource-records.js), adds it to the solution, and stops with what a run again does — which is to write the-// content again by id, never to create the name again. Held here:+// content again by id (the page manifest: unless its published copy already holds that content, which is kept), never to create the name again. Held here:// 1. the record itself;// 2. the build's retry policy for the error: it is judged by the failure it carries, and when it carries none — the read-back differed — it is run again;// 3. each site, over the real bundle and the stateful fake of helpers/fake-app-build-org.js (a web resource held in a saved and a published layer, a plain// read answering the published one), with the customization lock refusing the publish: the halt, the row in the solution, the record, the next run —-// the build's own re-run and a new invocation — writing the content again by id, and an unchanged rebuild after it sending what it always did.+// the build's own re-run and a new invocation — writing the content again by id (the manifest: or keeping a published copy that already holds it),+// and an unchanged rebuild after it sending what it always did.const test = require('node:test');const assert = require('node:assert/strict');const fs = require('node:fs');@@ -21,7 +22,8 @@ const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');const { createMakerSdk: createClientSdk } = require('../lib/maker-sdk.js');const { createAzHttpClient } = require('../lib/sdk-http-client.js');-const { runSdkBuild } = require('../lib/sdk-build.js');+const { runSdkBuild, appUniqueName } = require('../lib/sdk-build.js');+const { withAppBuildLease } = require('../lib/app-operation-lease.js');const { requireSuccessfulPush } = require('../lib/entity-provision.js');const { buildModelApp, isTransientHalt } = require('../build-model-app.js');const { retryPolicyFor, judgeFailure, RETRY } = require('../lib/retry-policy.js');@@ -202,6 +204,7 @@ test('a spec web resource whose publish the lock refuses: the build stops namingassert.equal(first.halt.phase, 'web-resources');assert.match(first.halt.message, new RegExp(`Web resource '${SCRIPT.replace(/[/.]/g, '\\$&')}' \\(${id}\\)`), 'it names the web resource and its id');assert.match(first.halt.message, /this build recorded the row as its own and added it to the solution\. Its publication is UNCONFIRMED, not lost: run the build again — it writes the content again by that id, publishes it and reads it back/);+ assert.match(first.halt.message, /run the build again — it writes the content again by that id, publishes it and reads it back \(the call the message names is made for you\)\.$/, 'written again whatever was published: the stop promises the write');assert.equal(added(first.calls, id).length, 1, 'the row is added to the solution as the success path adds it');assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'and recorded for the next run');assert.equal(retryPolicyFor(first.halt), RETRY.SERVICE, 'a lock is the service\'s to clear');@@ -409,6 +412,11 @@ test('the build\'s own re-run of the halt writes it again by id in the same invo// to its membership add, B writes the same row again from a newer spec, the lock refuses B's publish, and B records its unconfirmed write — under the// same id, since it is the same row. A's clear comes after that: it must take only the entry A verified, so that the next build writes B's content again// by id instead of reusing the row with A's content published.+//+// A build of this release can no longer run inside another of the same app and workspace: the build lease (lib/app-operation-lease.js) refuses it+// before it writes anything. The record's revisions are still what guards against a writer the lease does not hold back — a build of an earlier+// release, which takes no build lease — so B runs here with A's lease, which an apply borrows when it is handed it, and so runs beside A as such a+// writer would.test('a recovery whose membership add is answered after another build recorded a later, unconfirmed write of the same row leaves that record: the next build writes the newer content again by id', async () => {const s = scenario();refuseWebResourcePublishes(s.org);@@ -416,13 +424,14 @@ test('a recovery whose membership add is answered after another build recorded aconst id = s.row(SCRIPT).webresourceid;const NEWER = 'var Form = { onLoad: function () { return 2; } };';let other;+ let lease;const stop = s.org.intercept((c) => c.method === 'POST' && c.path === '/AddSolutionComponent' && String(c.body.ComponentId).toLowerCase() === id, async (c) => {stop();refuseWebResourcePublishes(s.org);- other = await s.build(spec([{ name: SCRIPT, type: 'js', content: NEWER }]));+ other = await s.build(spec([{ name: SCRIPT, type: 'js', content: NEWER }]), { buildLease: lease });return s.org.fake.httpClient.post(`${s.org.origin}/api/data/v9.2${c.path}`, c.body);});- const recovered = await s.build(spec());+ const recovered = await withAppBuildLease({ workspaceDir: s.dir, appUniqueName: appUniqueName(spec()) }, (held) => { lease = held; return s.build(spec(), { buildLease: held }); });assert.ok(recovered.outcome && recovered.outcome.ok, String(recovered.halt && recovered.halt.message));assert.ok(other && other.halt, 'the other build ran while A waited for its add, and stopped');assert.equal(other.halt.code, 'WEB_RESOURCE_UNVERIFIED', 'its write of the same row unconfirmed');@@ -545,6 +554,7 @@ test('the generated app icon whose publish the lock refuses: the app step stopsassert.equal(first.halt.phase, 'app-shell');const id = s.row(ICON).webresourceid;assert.match(first.halt.message, new RegExp(`'${ICON}' \\(${id}\\)`));+ assert.match(first.halt.message, /Its publication is UNCONFIRMED, not lost: run the build again — it writes the content again by that id, publishes it and reads it back \(the call the message names is made for you\)\.$/, 'the icon is written again whatever was published: the stop promises the write');assert.equal(added(first.calls, id).length, 1, 'in the solution');assert.equal(s.org.appId(), undefined, 'the app is not written over an icon that is not confirmed');const next = await s.build(APP_SPEC(), { phases: ['app-shell'] });@@ -578,7 +588,8 @@ test('the generated icon recovers by id inside the build retry loop without crea//// The pages go through the REAL page backend over the stateful fake of the page service, as in publish-scope-real-bundle.test.js; the manifest is a web// resource of the app's fake. The page's identity is the manifest, the page list, and the workspace's creation receipts: what a run after an unconfirmed-// manifest write does is proven here — it binds the page it created by its receipt, creates no second page, and writes the manifest again by id.+// manifest write does is proven here — it binds the page it created by its receipt, creates no second page, and writes the manifest again by id where its+// published copy is not what the run wants, or keeps that copy where it is.const { makeGenpageSdk } = require('../lib/genpage-sdk.js');const { FakeGenPageServer, ACCOUNT_TABLE } = require('./helpers/fake-genpage-server.js');const PAGE_CODE = "import * as React from 'react';\nexport default function Overview() { return <div>Overview</div>; }\n";@@ -651,6 +662,36 @@ test('a page manifest whose first write the lock refuses: the pages step stops nassert.equal(fs.existsSync(unconfirmedRecordPath(p.dir, p.org.origin)), false);});+// What the stop for the manifest says the next build does is what that build does. The manifest is first compared with its PUBLISHED copy+// (persistPageManifest): where that copy already holds the content the build would write it is kept, and otherwise written again by id. Live,+// a manifest created and never published — each of its publishes refused — was read back with that content by the run that followed, and+// kept — so the stop must not promise a write, as it does for the spec's web resources and the generated icon, which are written again+// whatever was published. The fake's plain read answers only a row's published copy; the first case sets it to what the platform answered there.+test('the stop for a page manifest whose publication was not confirmed says the next build keeps a published copy that already holds the content, or writes it again by id — and that build does one or the other', async (t) => {+ const MANIFEST_ADVICE = /Its publication is UNCONFIRMED, not lost: run the build again — it reads the published copy and keeps it if it already holds the content that build would write; otherwise it writes the content again by that id, publishes it and reads it back \(the call the message names is made for you\)\.$/;+ for (const kept of [true, false]) {+ const p = pageScenario(t);+ refuseWebResourcePublishes(p.org);+ const first = await p.build(p.pageSpec());+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED', String(first.halt && first.halt.message));+ assert.match(first.halt.message, MANIFEST_ADVICE, 'the manifest\'s stop says what the next build does in either case');+ assert.doesNotMatch(first.halt.message, /run the build again — it writes the content again by that id/, 'and does not promise a write');+ assert.equal(retryPolicyFor(first.halt), RETRY.SERVICE, 'a lock is still the service\'s to clear');+ assert.equal(isTransientHalt(first.halt), true, 'so the build still runs again');+ const row = p.row(MANIFEST);+ assert.equal(added(first.calls, row.webresourceid).length, 1, 'the row is in the solution already');+ if (kept) row.publishedContent = row.content;+ const next = await p.build(p.pageSpec());+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));+ const manifestWrites = next.calls.filter((c) => c.method !== 'GET' && /^\/webresourceset/.test(c.path));+ if (kept) assert.deepEqual(manifestWrites, [], 'the published copy holds the content: kept, not written');+ else assert.deepEqual(manifestWrites.map((c) => `${c.method} ${c.path}`), [`PATCH /webresourceset(${row.webresourceid})`], 'the published copy does not: written again by id');+ assert.equal(manifestCreates(p.org.calls), 1, 'never created a second time');+ assert.equal(fs.existsSync(unconfirmedRecordPath(p.dir, p.org.origin)), false, 'either way the record is cleared');+ assert.deepEqual(listsPages(p.manifest()), p.created);+ }+});+test('the same, inside one invocation: the build\'s own re-run of the halt binds the page it created, writes the manifest by id and finishes', async (t) => {const p = pageScenario(t);refuseWebResourcePublishes(p.org);diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex b543136f0..f936f41fb 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -480,7 +480,8 @@ phase re-uses what's already created and only fills the gaps. SDK metadata is pe`--from <phase>` shortcut; a full rerun is the correct and safe recovery path — after a `WEB_RESOURCE_UNVERIFIED`halt too: a web resource was written but its publication could not be confirmed (often because another customizationheld the environment's lock), the build recorded it, and a rerun using the **same writable workspace** writes it-again by its id; do not delete or rename it. If the halt says its recovery record could not be saved, or reports+again by its id (the page manifest only when its published copy does not already hold that content; otherwise the+rerun keeps it); do not delete or rename it. If the halt says its recovery record could not be saved, or reportsa conflicting name/id, follow that explicit resolution instead — automatic retry is unsafe without the identity.One exception: an`already-exists` halt recurs on a rerun until that workspace directory is deleted — follow its message.@@ -503,6 +504,8 @@ hold page-ownership receipts and the baseline) and run again. The same environme(`<org>.api.crm…` against `<org>.crm…`) also halts: re-run with the host the halt names. The standalone verifiernever opens that workspace either, so it verifies any environment the app is deployed to.+Run only one apply command for an app in its workspace at a time, including its data stage and full build. If another build holds the build or pages lock, let it finish and then rerun the same full command; do not repeatedly launch retries, use a second workspace to bypass it, or delete the workspace. A lock refusal is on stderr with exit 1 and no stdout JSON; do not treat empty stdout as an unknown crash or a reason to reset the workspace. A teardown, download, standalone `/genpage` or `apps.js` mutation, or workspace clear is not stopped by this lock; do not run one against the same app/workspace beside the apply. A lock is abandoned only after its owner is confirmed no longer running; age alone is never sufficient. If automatic reclaim cannot complete, inspect the owner evidence and consider removing only the named lock/reclaim file manually after that confirmation. Keep the workspace and its recovery records. For concurrent-build protection, all overlapping build commands must use the new version. During a mixed-version transition, finish older builds first and keep the downloaded app unique name's spelling unchanged.+With `--publish`, the tables the build changed, and the tables whose forms or charts the app holds or is about to hold, are published in onerequest before the build writes or publishes the app: the tables whose existing views and forms the build edited, the tables of thecharts it wrote, the navigation's tables whenever the build pushes the app (the SDK adds their active Main forms to it on every push the builddiff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.mdindex d48008d45..1d20c5c83 100644--- a/plugins/pcf/CHANGELOG.md+++ b/plugins/pcf/CHANGELOG.md@@ -19,4 +19,4 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r- The push receipt (`pcf-receipt.json`) no longer carries an access token that a refused confirmation read quoted, and every file the SDK writes into a push's workspace goes through the same output guard as model-apps' scripts.- A large result is no longer cut short on Linux and macOS: `emitResult`, the printer of an uncaught error, `check-auth.js`, the result printers of `pcf-inventory.js`, `verify-pcf.js` and `lint-pcf.js`, every script's usage error and the write-safety hook's message make their writes blocking before the process exits. What is printed and every exit status are unchanged; Windows was never affected.-- The output guard (the same module model-apps 2.18.0 ships) also keeps an access token out of bytes written to stdout or stderr, masked with `*` byte for byte so framed output keeps its length, out of the token's base64, percent-encoded and HTML spellings, and out of a token that `util.inspect` or an ellipsis cut short or that was split between two writes (each piece of 24 characters or more), keeping an escape split between two writes whole. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a short piece on the far side of a split escape, base64 of a part of the token, and bytes written to a file.+- The output guard (the same module model-apps 2.19.0 ships) also keeps an access token out of bytes written to stdout or stderr, masked with `*` byte for byte so framed output keeps its length, out of the token's base64 — and the base64 of each of its parts of 24 characters or more — and its percent-encoded and HTML spellings, and out of a token that `util.inspect` or an ellipsis cut short or that was split between two writes (each piece of 24 characters or more), keeping an escape split between two writes whole, also after a nested write and the write around it were both refused. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a short piece on the far side of a split escape, base64 of a piece of the token that is not a whole part, and bytes written to a file.diff --git a/plugins/pcf/scripts/lib/output-redaction.js b/plugins/pcf/scripts/lib/output-redaction.jsindex cc0572b4b..b8bb93fef 100644--- a/plugins/pcf/scripts/lib/output-redaction.js+++ b/plugins/pcf/scripts/lib/output-redaction.js@@ -30,17 +30,22 @@// (guardFatalErrors).// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),// `writeFileAtomic` (lib/apply-snapshot-store.js: the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records) and the SDK's workspace storage — every file the bundle writes goes through its-// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.+// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). The three writers clean what they are given as the file gets it (redactFileData): a text as a text; BYTES — every view of an ArrayBuffer: a+// Buffer, any typed array, a DataView — and a string given with a `hex`, `base64` or `base64url` encoding as the bytes written, a hit masked with as many `*` in a copy. Each call is read on its own: an append is+// not read together with the file it extends. tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.// - not covered, by design: a token another process obtained (`pac` has its own); a piece of a token SHORTER than MIN_TOKEN_PART_LENGTH at the edge of a write or before a cut (it would be taken out of ordinary words — a// token written in two pieces leaves the shorter piece when it is under 24 characters; the first one is written before the second exists); a piece from the MIDDLE of a token that neither begins nor ends a needle (a// token written in three pieces or more, or cut at both ends); the start of a write read through an escape's letters (it is read on the first reading only: a literal backslash before its first letter leaves that letter);// the piece of a token that an escape cut between two writes leaves on its far side when that piece is shorter than 24 characters (the escape stays whole, so its characters count for neither piece);-// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a part alone, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);-// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); bytes given to a FILE writer (the-// writers below clean text); the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than white space-// and ESC between two of its characters.+// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a substring that is not a whole part — or of a part shorter than 24 characters, or of a base64+// spelling —, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);+// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); a token split between two+// appends to a file, and the part of a chunk an append that failed part way left in the file (it is of the cleaned chunk, and is not taken back); what a child process writes, a write of the file system the+// plugin does not list (tests/output-token-writers.test.js), the files listed there as data handed on as it is (the settings a person gave, the package pac is given), and a file the SDK writes other than+// through `writeTextAtomic`; the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than+// white space and ESC between two of its characters.//// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as@@ -50,8 +55,9 @@// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).//-// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64, standard and URL-safe, at each of the three byte alignments it can have inside a longer value (a-// whole `Authorization` header, a body encoded once more), and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.+// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64 and that of each of its parts of 24 characters or more, standard and URL-safe, at each of the three+// byte alignments it can have inside a longer value (a whole `Authorization` header, a body encoded once more, the one part a diagnostic complains about) — the characters made of its own bits, not the ones beside them that+// also hold bits of their neighbours, nor the padding — and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.//// A TOKEN CUT SHORT. A formatter that cuts a long text keeps its beginning, and the end of what it kept can be the beginning of a token: util.inspect prints at most 10,000 characters of a string and then says how many it// left out (`'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters`), and a text cut to a length by hand ends with an ellipsis (`...`, `…`). Where a text says it was cut, the run before it that BEGINS a needle — 24@@ -69,7 +75,7 @@// a dot, an ellipsis, while a needle is being read), and its pieces are the alignments the pass already follows; the start of a text is read for at most the longest needle's length; bytes are read in one pass of the// same kind, needle by needle in lockstep. A text that would need more is not guessed at: the search fails, and every caller fails closed (tests/output-redaction.test.js and tests/output-token-forms.test.js measure// all of it). A text that holds no token comes back as the very string, and bytes as the very bytes.-const { inspect, types: { isUint8Array } } = require('node:util');+const { inspect, types: { isUint8Array, isArrayBufferView } } = require('node:util');// What takes the place of a token, or of a part of one, in a text.const TOKEN_MARKER = '<token>';@@ -106,12 +112,15 @@ const HTML_ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "/*** The other spellings of `token` that are taken out of what the process writes, each an exact needle read as any needle is (with folds and escapes in it):- * - its base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), as it is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so the token's- * first byte can stand at any of three places in a group and each place spells it differently. Of each, only the characters made of the token's own bits — a character that also holds bits of the byte before or- * after it changes with that byte, so it is left out at either end;+ * - the base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), of the token AND of each of its parts of 24 characters or more (needlesOf) — a diagnostic can encode the one+ * part it complains about as well as the whole header — as each is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so a needle's first byte can stand at any of three+ * places in a group and each place spells it differently. Of each, only the characters made of the needle's own bits — a character that also holds bits of the byte before or after it changes with that byte,+ * so it is left out at either end: a complete encoding of a part keeps that character and its padding (`<token>Q==`), and so does one of the token;* - its percent-encoded spelling (upper- and lower-case hex) and its HTML spelling, and those of each of its parts of 24 characters or more — only where they differ from it: a JWT is base64url and dots, which* neither changes, so a JWT has base64 spellings only.- * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more, as a part is; a spelling that is already a needle of the token is not repeated. The longest first.+ * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more — the length of the SPELLING, so that a token of 18 characters keeps the 24 characters of its first alignment; a part shorter than 24 characters+ * is no needle and so has no spelling — and a spelling that is already a needle of the token, or another needle's spelling, is not repeated. The longest first. needlesOf is not changed by any of it: the Dataverse+ * client scrubs the answers it fails with by that list alone (lib/sdk-http-client.js).* @param {string} token* @returns {string[]}*/@@ -122,13 +131,15 @@ function spellingsOf(token) {const keep = (spelled) => {if (spelled.length >= MIN_TOKEN_PART_LENGTH && !plain.includes(spelled)) spellings.add(spelled);};- const bytes = Buffer.from(token, 'utf8');- for (let offset = 0; offset < 3; offset += 1) {- // With `offset` bytes before the token, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)- // hold the token's bits and nothing else.- const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));- keep(standard);- keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));+ for (const needle of plain) {+ const bytes = Buffer.from(needle, 'utf8');+ for (let offset = 0; offset < 3; offset += 1) {+ // With `offset` bytes before the needle, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)+ // hold the needle's bits and nothing else.+ const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));+ keep(standard);+ keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));+ }}for (const needle of plain) {keep(percentSpelling(needle, true));@@ -822,6 +833,56 @@ function redactOutput(text) {return redactWith(preparedNow(), text, true);}+// What a file writer is told when the data it was given could not be checked: a fixed sentence, never the data, which may hold the token.+const UNCHECKED_FILE_DATA = 'output-redaction: the data given to a file writer could not be checked for an access token, so it was not written';++/**+ * `data` as a file writer of the plugin writes it (lib/safe-fs.js `writeFileSafe` and `appendFileSafe`, lib/apply-snapshot-store.js `writeFileAtomic`), with every token this process has obtained taken out — whatever+ * `fs.writeFileSync` and `fs.appendFileSync` take, read as what they write:+ * - a text, as redactOutput reads it (a whole text: a needle's start at its end and its end at its start go too);+ * - BYTES — any view of an ArrayBuffer: a Buffer, a Uint8Array, a Uint16Array or any typed array, a DataView, from this realm or another (`util.types.isArrayBufferView`) — read byte for byte, only the bytes the view+ * covers (`[byteOffset, byteOffset + byteLength)`), and a hit masked with as many `*` in a COPY: the file keeps its length and the caller's memory is not written into. Node writes every such view as its raw bytes+ * (measured on Node 20 and 22: `writeFileSync` writes a Uint16Array and a DataView byte for byte), so a view is read as those bytes and never through `Buffer.from(view)`, which turns a Uint16Array into one byte+ * an element;+ * - a string given with `encoding` `hex`, `base64` or `base64url`, which the writer decodes into the bytes it writes: those bytes are read and, on a hit, masked and returned as a Buffer — the writer must then+ * write it WITHOUT that encoding (it would decode it again).+ * The very `data` when it holds no token, and — before anything is looked at — when no token has been obtained: a process that has none writes what it always wrote, and gets the same errors (a detached view, which+ * Node writes as nothing, included). A view whose bytes cannot be read (detached) or a string that cannot be decoded, when a token has been obtained, is not written: this throws, with a message that does not+ * hold the data, before the writer writes anything — never the data unchecked, and never another text in its place. A raw ArrayBuffer is no view: it is passed on, and Node refuses it (ERR_INVALID_ARG_TYPE).+ * Nothing is carried from one call to the next — two appends of a token's two halves are two writes, read each alone — and nothing is read from the file.+ * @template T+ * @param {T} data+ * @param {{ encoding?: string } | string | null} [opts]+ * @returns {T | Buffer}+ */+function redactFileData(data, opts) {+ if (obtained.size === 0) return data;+ const encoding = opts && typeof opts.encoding === 'string' ? opts.encoding : '';+ if (typeof data === 'string' && BINARY_ENCODINGS.test(encoding)) {+ let decoded;+ try {+ decoded = Buffer.from(data, encoding);+ } catch {+ throw new TypeError(UNCHECKED_FILE_DATA);+ }+ if (decoded.length === 0) return data;+ const masked = maskWith(preparedNow(), decoded, true, 0);+ return masked === decoded ? data : masked;+ }+ if (isArrayBufferView(data)) {+ let raw;+ try {+ raw = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);+ } catch {+ throw new TypeError(UNCHECKED_FILE_DATA);+ }+ if (raw.length === 0) return data;+ const masked = maskWith(preparedNow(), raw, true, 0);+ return masked === raw ? data : masked;+ }+ return redactOutput(data);+}+/*** What a guarded stream writes in place of `chunk`: a text as `redactOutput` makes it, and bytes with every token this process has obtained masked (maskTokenBytes, with the edges of the write) — the very bytes when they* hold none. `from`: where an escape the stream's last write ended inside is finished (guardStream). Anything else is returned as it is.@@ -906,13 +967,17 @@ function guardStream(stream, redact = redactWritten) {}// The memory is this write's before the stream takes it, so that a callback the stream calls at once, and writes from, reads on from it. A write the stream REFUSES — it throws (an encoding it does not know, a// chunk that is no text and no bytes, a stream already ended) — wrote nothing, so the memory goes back to what the last written one left, unless a write made inside it has moved it on; the error is the- // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands.+ // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands. A refused write also takes back its own count: a write made inside another one that the+ // stream refuses as well wrote nothing either, and its count left behind would read, to the outer write, as a write the stream took — the outer one would then keep a memory nothing was written with.writes += 1;const mine = writes;try {return write.call(this, given, ...rest);} catch (error) {- if (writes === mine) open = before;+ if (writes === mine) {+ open = before;+ writes = mine - 1;+ }throw error;}};@@ -1044,6 +1109,7 @@ module.exports = {redactTokens,maskTokenBytes,redactOutput,+ redactFileData,guardStream,makeWritesBlocking,guardFatalErrors,diff --git a/plugins/pcf/scripts/lib/source-literals.js b/plugins/pcf/scripts/lib/source-literals.jsindex 9aa45c861..7ccd3bcf7 100644--- a/plugins/pcf/scripts/lib/source-literals.js+++ b/plugins/pcf/scripts/lib/source-literals.js@@ -4063,9 +4063,10 @@ function blankNonCodePreservingTemplateExpressions(code, opts) {* Both spellings count:* export default <expr|function|class|async function>* export { P as default } / export { default } from './x'+ * and the expression may be a generic arrow, `export default <T,>(props: P<T>) => …` (genericArrowIsComplete).*/// Identifiers may be non-ASCII (`Página`), so every name below is matched by Unicode property. White space is TypeScript's (WS, WS_SINGLE_LINE: see isTrivia), as everywhere in this file.-const DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}+default${WS}+[\p{ID_Continue}$({[*]`, 'gmu');+const DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}+default${WS}+[\p{ID_Continue}$({[*<]`, 'gmu');const NAMED_DEFAULT_EXPORT = new RegExp(String.raw`(?:^${WS_SINGLE_LINE}*|[;}]${WS_SINGLE_LINE}*)export${WS_SINGLE_LINE}*\{[^}]*\bdefault\b[^}]*\}`, 'm');const EXPORT_MODIFIER = new RegExp(String.raw`^(async|abstract)\b${WS_SINGLE_LINE}*`);const ARROW_CUT_OFF = new RegExp(String.raw`=>${WS}*$`);@@ -4096,6 +4097,8 @@ function hasDefaultExport(code) {// `at` is where the exported thing starts in `bare` (blanked code, so strings and comments are gone).function defaultExportIsComplete(bare, at) {const rest = bare.slice(at);+ // A `<` is a generic arrow's type parameters or an element, by TypeScript's rule; only a complete arrow is an export the host can mount.+ if (rest[0] === '<') return genericArrowIsComplete(rest);// `async` and `abstract` only modify what follows. Cut right after one, or inside the keyword it// modifies (`export default abstract clas`), the export is incomplete. Followed by `;` or a line// break instead, the word is a plain exported name (it is a legal identifier), handled below.@@ -4104,6 +4107,9 @@ function defaultExportIsComplete(bare, at) {const after = rest.slice(mod[0].length);if (!trimTrivia(after)) return false;if (!/^(?:function|class)\b/.test(after) && !/^(?:;|[\r\n\u2028\u2029])/.test(after)) {+ // After `async` on its line TypeScript asks the same rule of a `<` (isParenthesizedArrowFunctionExpressionWorker steps over the `async`), so an async generic+ // arrow is read as a plain one is. A head the rule reads as an element makes no arrow (TypeScript reads `async<T>(x: T)` as a call), and is judged below, as it always was.+ if (mod[1] === 'async' && after[0] === '<' && opensTypeParameters(after, 0, null, true).generic) return genericArrowIsComplete(after);// Only an async ARROW is left — `async (x) => …`, `async x => …` — and it needs its `=>` and body.return mod[1] === 'async' && /=>/.test(after) && !ARROW_CUT_OFF.test(after);}@@ -4175,6 +4181,499 @@ function defaultExportIsComplete(bare, at) {return declaresName(bare, name[1]);}+// `export default <T,>(props: Props<T>) => { … }`: a generic arrow, from its `<` (`rest` is blanked code), with or without `async` before it. In a .tsx file TypeScript reads a+// `<` where an assignment expression starts by one rule (parser.ts, isParenthesizedArrowFunctionExpressionWorker, the JSX branch,+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), which opensTypeParameters reads: type parameters when, after an optional `const`, the first name is+// followed by a `,`, an `=`, or `extends` and a token that is not `=`, `>` or `/` —+// <T,>(props: P<T>) => … <T extends object>(p: T) => … <const T,>(p: T) => … <T = string>(p: T) => …+// and an element for any other head: `<div/>`, `<></>`, and `<T>(x) => x`, which in .tsx is the element `<T>` and does not parse. An element is no component the host can+// mount, so it is refused, as it always was. What follows `export default` is an expression (parseExportAssignment), so the rule is asked as it is where an expression is known+// to start (`inExpression`): a head it reads as an element is no function type here. The type parameters must then close, a parameter list must follow them (an arrow with+// type parameters always has one), the arrow's `=>` must follow the list — at once, or right after a return type, read to its end as TypeScript reads one+// (returnTypeEnd) — and a body must follow the arrow. A write cut off anywhere before the body balances its brackets when it stops between them, so only this sees it:+// export default <T,>(props: P<T>) export default <T,>(props: P<T>): JSX.Element export default <T,>(p: T): (x: T) => T export default <T extends (a: A) => void+function genericArrowIsComplete(rest) {+ if (!opensTypeParameters(rest, 0, null, true).generic) return false;+ const typeParametersEnd = typeAnglesEnd(rest, 0);+ if (typeParametersEnd === -1) return false;+ const open = typeTokenAt(rest, typeParametersEnd);+ if (open.kind !== '(') return false;+ const parametersEnd = typeGroupEnd(rest, open.start);+ if (parametersEnd === -1) return false;+ let arrow = typeTokenAt(rest, parametersEnd);+ if (arrow.kind === ':') {+ const returnEnd = returnTypeEnd(rest, arrow.end);+ if (returnEnd === -1) return false;+ arrow = typeTokenAt(rest, returnEnd);+ }+ if (arrow.kind !== '=>' || !startsArrowBody(typeTokenAt(rest, arrow.end))) return false;+ // The body is taken as written, as any exported expression is (its brackets are checked separately), unless the file stops at a token that needs more: `p +`, `p as`.+ return !DANGLING_TAIL.test(rest) && !DANGLING_CAST.test(rest);+}++// What begins an arrow's body: a block, or what begins an expression — a name, any word but those that only begin a statement (a keyword that begins an expression, `this`,+// `new`, `typeof`, `class`, `function`, `import`, …, and a word that is a keyword elsewhere, `module`, `let`, `async`), a literal, a bracket, a prefix operator, `<` (an element+// or a generic arrow), `/` (a regex: a comment is blank) or `#` (`#x in y`). Anything else — `;`, a closing bracket, a binary operator, `.`, `...`, `=>`, `@` — is+// `Expression expected` to TypeScript, as is a statement's word after the arrow: `export default <T,>() =>` and `const x = 1;` on the next line has no body.+const EXPRESSION_KEYWORDS = new Set(['class', 'delete', 'false', 'function', 'import', 'new', 'null', 'super', 'this', 'true', 'typeof', 'void']);+const BODY_START_TOKENS = new Set(['{', '(', '[', '!', '~', '+', '-', '++', '--', '<', '/', '#', 'string', 'template', 'number']);+function startsArrowBody(token) {+ if (token.kind === 'word') return EXPRESSION_KEYWORDS.has(token.text) || !(RESERVED_WORDS.has(token.text) || token.text === 'const');+ return BODY_START_TOKENS.has(token.kind);+}++// A token, for the reading of a type and an arrow above and below: the token of `src` (blanked code, where a string or a template is its quotes around blank and a comment is+// blank) at or after `k`, as { kind, text, start, end, newline }. `kind` is 'word' — a name or a keyword; `text` is its characters, or '' for a word written with an escape,+// which is a name and no keyword here — 'string', 'template', 'number', 'eof' (a string the text does not close ends it too), or the punctuator: the longest of+// TYPE_PUNCTUATORS that stands there, as TypeScript's scanner reads one (scanner.ts, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/scanner.ts: `||` is no `|`, and+// `?.` before a digit is a `?`), or else one character — a `>` always, which the parser only joins to what follows it where an operator is expected. `newline` says a line+// terminator stands before the token: TypeScript's parser reads no type arguments, `[`, `extends`, `is` or name of an assertion on a line after what they continue.+const TYPE_PUNCTUATORS = ['===', '!==', '...', '=>', '==', '!=', '||', '&&', '??', '?.', '*=', '|=', '&=', '++', '--'];+function typeTokenAt(src, k) {+ let j = k;+ let newline = false;+ while (j < src.length && isTrivia(src[j])) {+ if (isLineTerminator(src[j])) newline = true;+ j += 1;+ }+ const token = (kind, end, text = src.slice(j, end)) => ({ kind, text, start: j, end, newline });+ if (j >= src.length) return token('eof', j, '');+ const c = src[j];+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, j + 1);+ return close === -1 ? token('eof', src.length, '') : token(c === '`' ? 'template' : 'string', close + 1);+ }+ // A number: digits, letters (hex digits, an exponent, `n`, `_`), points, and a sign right after the `e` of a decimal exponent (`1e+5`).+ if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(src[j + 1] || ''))) {+ const hex = c === '0' && /[xX]/.test(src[j + 1] || '');+ let e = j + 1;+ while (e < src.length && (/[0-9A-Za-z_.]/.test(src[e]) || (!hex && (src[e] === '+' || src[e] === '-') && /[eE]/.test(src[e - 1])))) e += 1;+ return token('number', e);+ }+ if (c === '\\' || /[\p{ID_Start}$_]/u.test(String.fromCodePoint(src.codePointAt(j)))) {+ const word = readRuleToken(src, j);+ if (word.kind === 'word') return token('word', word.end, word.escaped ? '' : word.text);+ }+ const punctuator = TYPE_PUNCTUATORS.find((p) => src.startsWith(p, j) && !(p === '?.' && /[0-9]/.test(src[j + 2] || '')));+ return punctuator ? token(punctuator, j + punctuator.length) : token(c, j + 1);+}++// The index just past the bracket that closes the `(`, `[` or `{` at `open` in `src` (blanked code), or -1 where none does or another kind closes first. Brackets of every kind+// are matched, and a string's or a template's quote, which the blanking keeps, is passed to its pair: what is between them is blank.+function typeGroupEnd(src, open) {+ const closers = [];+ for (let k = open; k < src.length; k += 1) {+ const c = src[k];+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, k + 1);+ if (close === -1) return -1;+ k = close;+ } else if (c === '(') closers.push(')');+ else if (c === '[') closers.push(']');+ else if (c === '{') closers.push('}');+ else if (c === ')' || c === ']' || c === '}') {+ if (closers.pop() !== c) return -1;+ if (closers.length === 0) return k + 1;+ }+ }+ return -1;+}++// The index just past the `>` that closes the type parameters or type arguments whose `<` is at `open` in `src` (blanked code), or -1 where none does. A group in brackets is+// passed over whole (typeGroupEnd), so no angle in it is counted, and the `>` of an `=>` closes nothing: `<T extends (a: A) => void>`, `Map<string, (x: T) => T>`.+function typeAnglesEnd(src, open) {+ let depth = 0;+ for (let k = open; k < src.length; k += 1) {+ const c = src[k];+ if (c === '"' || c === "'" || c === '`' || c === '(' || c === '[' || c === '{') {+ const end = c === '(' || c === '[' || c === '{' ? typeGroupEnd(src, k) : src.indexOf(c, k + 1) + 1;+ if (end <= 0) return -1;+ k = end - 1;+ } else if (c === ')' || c === ']' || c === '}') return -1;+ else if (c === '<') depth += 1;+ else if (c === '>' && src[k - 1] !== '=') {+ depth -= 1;+ if (depth === 0) return k + 1;+ }+ }+ return -1;+}++// The words isStartOfType takes besides a name (and which a name cannot be: a reserved word among them is a type's keyword there).+const TYPE_START_KEYWORDS = new Set([...PRIMITIVE_TYPES, 'readonly', 'unique', 'typeof', 'new', 'infer', 'import', 'asserts', 'function']);+// How deep the reading of a return type goes — a level per function type in a return type, conditional type in a branch or prefix operator — before it refuses the return type+// rather than recurse further: far deeper than any page, and far short of the stack.+const RETURN_TYPE_DEPTH = 200;++// Where a return type ends: the index just past it in `src` (blanked code) when it starts after the colon at `from`, or -1 where TypeScript's parser reports an error before it+// ends, or the text ends first. The arrow's `=>` is the first token after its return type, and a return type may hold an `=>` of its own at its own level — `(p): (x: T) => T => …`,+// `(p): new () => T => …` — so only a reading of the type tells the two apart, and a write cut right after such a type has no arrow. The type is read as TypeScript 5.8 reads it+// (parser.ts, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts: parseTypeOrTypePredicate, parseType and what they call; each function below names its+// own), one level at a time: what a group in brackets, a list in angle brackets, a string or a template holds is passed over whole, since nothing in it can end the type, and+// is not read. Where an author and a guess would part, it reads as TypeScript does:+// - any word names a type, a keyword too (parseEntityNameOfTypeReference reads an identifier NAME): `module<T>`, `namespace` and `declare` are names, and so are `if` and+// `const`, which only the checker refuses. A statement after the return type is not seen by its first word: the type ends before it, and the missing arrow refuses it;+// - a `(` begins a function type only where isUnambiguouslyStartOfFunctionType says so — `()`, `(...`, or a parameter's start (modifiers, then a name, `this` or a binding+// pattern that parses with no error) followed by `:`, `,`, `?` or `=`, or by `)` and `=>` — and a parenthesised type otherwise: `(p): (A) => T => …` holds a function+// type, `(p): (A | B) => …` a parenthesised type and then the arrow, and `(p): ({ a: T }) => p` a function type that takes the arrow's `=>` (an error);+// - type arguments, `[`, `extends`, `is` and an assertion's name continue a type only on its line; a function or constructor type after `|` or `&` is an error (TS1385, TS1388);+// - the JSDoc forms TypeScript's parser takes in a .tsx file and only its checker refuses (`?T`, `T?`, `!T`, `T!`, `*`, `function(…): T`) are read too.+function returnTypeEnd(src, from) {+ let depth = 0;+ const at = (k) => typeTokenAt(src, k);+ const isWord = (token, text) => token.kind === 'word' && token.text === text;+ // isIdentifier: a word that is no reserved word, nor `await`, which parseExportAssignment makes a keyword in an export.+ const identifier = (token) => token.kind === 'word' && (token.text === '' || !(RESERVED_WORDS.has(token.text) || token.text === 'const' || token.text === 'await'));+ // isBindingIdentifier: a word that is no reserved word.+ const bindingIdentifier = (token) => token.kind === 'word' && (token.text === '' || !(RESERVED_WORDS.has(token.text) || token.text === 'const'));+ // A reading that nests one level deeper; past RETURN_TYPE_DEPTH the type is refused.+ const nested = (read) => {+ if (depth >= RETURN_TYPE_DEPTH) return -1;+ depth += 1;+ try {+ return read();+ } finally {+ depth -= 1;+ }+ };++ // parseTypeOrTypePredicate: a name and `is` on its line make a predicate, whose type follows.+ const typeOrPredicate = (k) => {+ const name = at(k);+ if (identifier(name)) {+ const is = at(name.end);+ if (isWord(is, 'is') && !is.newline) return type(is.end, false);+ }+ return type(k, false);+ };+ // parseType: a function or constructor type, or a union and, on its line, `extends` and the rest of a conditional type — where conditional types are allowed: not in the+ // `extends` clause of one (`noConditional`).+ const type = (k, noConditional) => nested(() => {+ if (startsFunctionType(k)) return functionType(k);+ const end = unionOrIntersection(k, '|', noConditional);+ if (end === -1 || noConditional) return end;+ const ext = at(end);+ if (!isWord(ext, 'extends') || ext.newline) return end;+ const extendsEnd = type(ext.end, true);+ if (extendsEnd === -1 || at(extendsEnd).kind !== '?') return -1;+ const trueEnd = type(at(extendsEnd).end, false);+ if (trueEnd === -1 || at(trueEnd).kind !== ':') return -1;+ return type(at(trueEnd).end, false);+ });+ // isStartOfFunctionTypeOrConstructorType.+ const startsFunctionType = (k) => {+ const token = at(k);+ if (token.kind === '<' || isWord(token, 'new')) return true;+ if (isWord(token, 'abstract')) return isWord(at(token.end), 'new');+ return token.kind === '(' && unambiguousFunctionType(token.end);+ };+ // isUnambiguouslyStartOfFunctionType and skipParameterStart, after the `(`. The modifiers before a parameter's name (PARAMETER_MODIFIERS) are stepped over as parseModifiers+ // takes them (nextTokenCanFollowModifier): each where what follows can follow a modifier — on its line, but after `static` and `export` on any (and no `*`, `{` or `as`+ // after `export`).+ const unambiguousFunctionType = (k) => {+ let token = at(k);+ if (token.kind === ')' || token.kind === '...') return true;+ while (token.kind === 'word' && PARAMETER_MODIFIERS.has(token.text)) {+ const next = at(token.end);+ const follows = next.kind === 'word' || ['[', '{', '*', '...', 'string', 'number'].includes(next.kind);+ const exported = token.text !== 'export' || (next.kind !== '*' && next.kind !== '{' && !isWord(next, 'as') && !isWord(next, 'default'));+ if (!follows || !exported || (next.newline && token.text !== 'static' && token.text !== 'export')) break;+ token = next;+ }+ let end;+ if (identifier(token) || isWord(token, 'this')) end = token.end;+ else if (token.kind === '[' || token.kind === '{') end = bindingPatternEnd(token.start);+ else return false;+ if (end === -1) return false;+ const after = at(end);+ if (after.kind === ':' || after.kind === ',' || after.kind === '?' || after.kind === '=') return true;+ return after.kind === ')' && at(after.end).kind === '=>';+ };+ // parseObjectBindingPattern and parseArrayBindingPattern, whose `{` or `[` is at `open`: the index just past the pattern, or -1 where it does not parse with no error. A+ // default value is passed over to the `,` or the bracket that ends it (defaultValueEnd) — a known limit: the comma between a generic call's type arguments,+ // `{ a = f<T, U>() }`, is taken for the end of the value, the pattern reads as none, and a write cut right after a function type with such a parameter is accepted+ // (AGENTS.md, "TSX source lexer — known limits"; the page compile refuses it).+ const bindingPatternEnd = (open) => nested(() => {+ const object = src[open] === '{';+ const closer = object ? '}' : ']';+ let k = open + 1;+ for (;;) {+ let token = at(k);+ if (token.kind === closer) return token.end;+ if (!object && token.kind === ',') {+ k = token.end;+ continue;+ }+ if (token.kind === '...') token = at(token.end);+ let end;+ if (object) {+ // A property name — a word, a string, a number or a computed `[…]` that holds an expression — then `:` and the element; or a binding name alone.+ if (token.kind === 'word' || token.kind === 'string' || token.kind === 'number') end = token.end;+ else if (token.kind === '[' && computedKeyIsExpression(token.start)) end = typeGroupEnd(src, token.start);+ else return -1;+ if (end === -1) return -1;+ const colon = at(end);+ if (colon.kind === ':') end = bindingElementEnd(colon.end);+ else if (!bindingIdentifier(token)) return -1;+ } else {+ end = bindingElementEnd(token.start);+ }+ if (end === -1) return -1;+ let next = at(end);+ if (next.kind === '=') {+ end = defaultValueEnd(next.end, closer);+ if (end === -1) return -1;+ next = at(end);+ }+ if (next.kind === closer) return next.end;+ if (next.kind !== ',') return -1;+ k = next.end;+ }+ });+ const bindingElementEnd = (k) => {+ const token = at(k);+ if (token.kind === '[' || token.kind === '{') return bindingPatternEnd(token.start);+ return bindingIdentifier(token) ? token.end : -1;+ };+ // Whether the `[` at `open` holds an expression, as a binding pattern's computed key must (parseComputedPropertyName: parseExpression, `in` allowed). The same brackets hold+ // an index signature's key, `[key: string]`, and a mapped type's, `[K in keyof T]`, `[K in keyof T as …]`, in an object type — and neither is an expression: a `:` that no `?`+ // opened, or a word right after an operand (`keyof` is a name in an expression, and `T` follows it), ends the reading. So `({ [key: string]: T }) => …` holds a+ // parenthesised type and the arrow, where `({ [key]: v }) => …` and `({ [K in T]: v }) => …` (`K in T` is an expression) hold a function type's parameters. The+ // expression is read only as far as that needs — operands, prefix and binary operators, `?` and `:`, member access, calls, indexes, `!`, type arguments where they close and+ // what follows can follow them (canFollowTypeArgumentsInExpression), and a type after `as` or `satisfies` — and what it does not know (an arrow, `function`, a regex, JSX)+ // is taken for no expression: a type then, never a function type's parameters, so the reading can let a page TypeScript refuses through but never refuse one it parses.+ const computedKeyIsExpression = (open) => {+ const close = typeGroupEnd(src, open);+ if (close === -1) return false;+ const groupEnd = (token) => {+ const end = typeGroupEnd(src, token.start);+ return end !== -1 && end < close ? end : -1;+ };+ let k = open + 1;+ let operand = false;+ let questions = 0;+ for (;;) {+ const token = at(k);+ if (token.start >= close - 1) return token.start === close - 1 && operand && questions === 0;+ const word = token.kind === 'word' ? token.text : null;+ if (!operand) {+ // A prefix operator, then an operand: a name or a keyword that is a value, a literal, or a group (a parenthesised expression, an array, an object).+ if (['!', '~', '+', '-', '++', '--'].includes(token.kind) || ['typeof', 'void', 'delete', 'await', 'new'].includes(word)) k = token.end;+ else if (word !== null && (!(RESERVED_WORDS.has(word) || word === 'const') || ['this', 'null', 'true', 'false', 'super'].includes(word))) { operand = true; k = token.end; }+ else if (token.kind === 'number' || token.kind === 'string' || token.kind === 'template') { operand = true; k = token.end; }+ else if (token.kind === '(' || token.kind === '[' || token.kind === '{') { k = groupEnd(token); operand = true; if (k === -1) return false; }+ else return false;+ } else if (token.kind === '.' || token.kind === '?.') {+ // A member, or after `?.` a call or an index (read next).+ const name = at(token.end);+ if (name.kind === 'word') k = name.end;+ else if (token.kind === '?.' && (name.kind === '(' || name.kind === '[')) k = token.end;+ else return false;+ } else if (token.kind === '(' || token.kind === '[') {+ // A call, or an index — which holds an argument: `T[]` is no expression.+ k = groupEnd(token);+ if (k === -1 || (token.kind === '[' && at(token.end).start === k - 1)) return false;+ } else if (token.kind === '!' || token.kind === '++' || token.kind === '--' || token.kind === 'template') {+ k = token.end;+ } else if (token.kind === '<') {+ // Type arguments where they close and what follows can follow them — `(`, a template, the end, or a binary operator; a comparison otherwise.+ const end = typeAnglesEnd(src, token.start);+ const next = end === -1 || end >= close ? null : at(end);+ if (next !== null && (next.start === close - 1 || ['(', 'template', ',', '?', ':', '==', '===', '!=', '!==', '&&', '||', '??', '|', '&', '^', '*', '/', '%'].includes(next.kind) || ['in', 'instanceof', 'as', 'satisfies'].includes(next.kind === 'word' ? next.text : null))) k = end;+ else {+ operand = false;+ k = token.end;+ }+ } else if ((word === 'as' || word === 'satisfies') && !token.newline) {+ const end = type(token.end, false);+ if (end === -1 || end >= close) return false;+ k = end;+ } else if (token.kind === '?' || token.kind === ':' || word === 'in' || word === 'instanceof'+ || ['+', '-', '*', '/', '%', '<', '>', '&', '|', '^', '=', ',', '==', '===', '!=', '!==', '&&', '||', '??', '*=', '|=', '&='].includes(token.kind)) {+ if (token.kind === '?') questions += 1;+ if (token.kind === ':' && --questions < 0) return false;+ operand = false;+ k = token.end;+ } else {+ // An operand right after an operand (`keyof T`), or what this reading does not know.+ return false;+ }+ }+ };+ const defaultValueEnd = (k, closer) => {+ for (let j = k; j < src.length; j += 1) {+ const c = src[j];+ if (c === ',' || c === closer) return j;+ if (c === '"' || c === "'" || c === '`') {+ const close = src.indexOf(c, j + 1);+ if (close === -1) return -1;+ j = close;+ } else if (c === '(' || c === '[' || c === '{') {+ const end = typeGroupEnd(src, j);+ if (end === -1) return -1;+ j = end - 1;+ } else if (c === ')' || c === ']' || c === '}') return -1;+ }+ return -1;+ };+ // parseFunctionOrConstructorType: [`abstract`] [`new`] [type parameters] parameters `=>` and a return type.+ const functionType = (k) => {+ let token = at(k);+ if (isWord(token, 'abstract')) token = at(token.end);+ if (isWord(token, 'new')) token = at(token.end);+ if (token.kind === '<') {+ const end = typeAnglesEnd(src, token.start);+ if (end === -1) return -1;+ token = at(end);+ }+ if (token.kind !== '(') return -1;+ const parametersEnd = typeGroupEnd(src, token.start);+ if (parametersEnd === -1 || at(parametersEnd).kind !== '=>') return -1;+ return typeOrPredicate(at(parametersEnd).end);+ };+ // parseUnionOrIntersectionType: an optional leading operator, then constituents with the operator between them; a function or constructor type where a constituent+ // follows an operator is an error (parseFunctionOrConstructorTypeToError). A union's constituents are intersections, an intersection's prefix-operator types.+ const unionOrIntersection = (k, operator, noConditional) => {+ const constituent = (j) => (startsFunctionType(j) ? -1 : operator === '|' ? unionOrIntersection(j, '&', noConditional) : typeOperator(j, noConditional));+ const lead = at(k);+ let end = lead.kind === operator ? constituent(lead.end) : operator === '|' ? unionOrIntersection(k, '&', noConditional) : typeOperator(k, noConditional);+ while (end !== -1 && at(end).kind === operator) end = constituent(at(end).end);+ return end;+ };+ // parseTypeOperatorOrHigher: `keyof`, `unique` and `readonly` take the type after them; `infer` a name and maybe a constraint, which it keeps unless a `?` follows it where+ // conditional types are allowed (tryParseConstraintOfInferType: the `extends` then begins a conditional type); anything else is a postfix type.+ const typeOperator = (k, noConditional) => nested(() => {+ const token = at(k);+ if (isWord(token, 'keyof') || isWord(token, 'unique') || isWord(token, 'readonly')) return typeOperator(token.end, noConditional);+ if (!isWord(token, 'infer')) return postfix(k);+ const name = at(token.end);+ if (!identifier(name)) return -1;+ const ext = at(name.end);+ if (!isWord(ext, 'extends')) return name.end;+ const constraint = type(ext.end, true);+ return constraint !== -1 && (noConditional || at(constraint).kind !== '?') ? constraint : name.end;+ });+ // parsePostfixTypeOrHigher: on the type's line, `[…]` (an array or an indexed access) and the JSDoc `!` and `?` — a `?` before what can start a type is a conditional's,+ // and ends the type.+ const postfix = (k) => {+ let end = nonArray(k);+ while (end !== -1) {+ const token = at(end);+ if (token.newline) return end;+ if (token.kind === '!') end = token.end;+ else if (token.kind === '?' && !startsType(token.end, 0)) end = token.end;+ else if (token.kind === '[') end = typeGroupEnd(src, token.start);+ else return end;+ }+ return -1;+ };+ // isStartOfType, for the token at `k` (`nesting` bounds the look into parentheses).+ const startsType = (k, nesting) => {+ const token = at(k);+ if (token.kind === 'word') return TYPE_START_KEYWORDS.has(token.text) || identifier(token);+ if (['{', '[', '<', '|', '&', '*', '?', '!', '...', 'string', 'number', 'template'].includes(token.kind)) return true;+ if (token.kind === '-') return at(token.end).kind === 'number';+ if (token.kind !== '(' || nesting > 4) return false;+ // isStartOfParenthesizedOrFunctionType: `)`, a parameter's start or a type's after the `(`.+ const next = at(token.end);+ return next.kind === ')' || next.kind === '...' || next.kind === '[' || next.kind === '{' || next.kind === '#' || next.kind === '@' || bindingIdentifier(next)+ || startsType(token.end, nesting + 1);+ };+ // parseNonArrayType.+ const nonArray = (k) => nested(() => {+ const token = at(k);+ switch (token.kind) {+ case 'word': return wordType(token, k);+ case 'string': case 'template': case 'number': case '*': return token.end;+ case '{': case '[': case '(': return typeGroupEnd(src, token.start);+ // reScanAsteriskEqualsToken and reScanQuestionToken: `*=` is a `*` and then `=`, `??` two `?`.+ case '*=': return token.start + 1;+ case '??': return jsdocNullable(token.start + 1);+ case '?': return jsdocNullable(token.end);+ case '!': return nonArray(token.end);+ case '-': {+ const number = at(token.end);+ return number.kind === 'number' ? number.end : -1;+ }+ default: return -1;+ }+ });+ // parseJSDocUnknownOrNullableType, after its `?`: a `?` alone before `,`, `}`, `)`, `>`, `=` or `|`, and a prefix to a type otherwise.+ const jsdocNullable = (k) => ([',', '}', ')', '>', '=', '|'].includes(at(k).kind) ? k : type(k, false));+ const wordType = (token, k) => {+ const word = token.text;+ if (word === 'this') {+ // parseThisTypePredicate: `this is` on one line.+ const is = at(token.end);+ return isWord(is, 'is') && !is.newline ? type(is.end, false) : token.end;+ }+ if (word === 'void' || word === 'true' || word === 'false' || word === 'null') return token.end;+ // A keyword type (`string`, `number`, …) is a type of its own unless a `.` follows, which makes it the first name of a dotted one (parseKeywordAndNoDot).+ if (PRIMITIVE_TYPES.has(word)) return at(token.end).kind === '.' ? typeReference(k) : token.end;+ if (word === 'typeof') return isWord(at(token.end), 'import') ? importType(token.end) : typeQuery(token.end);+ if (word === 'import') return importType(k);+ if (word === 'function') {+ // parseJSDocFunctionType: `function(…)` and maybe `: type`; `function` alone is a name.+ const open = at(token.end);+ if (open.kind !== '(') return token.end;+ const end = typeGroupEnd(src, open.start);+ return end !== -1 && at(end).kind === ':' ? typeOrPredicate(at(end).end) : end;+ }+ if (word === 'asserts') {+ // parseAssertsTypePredicate, where a word follows on the line: `asserts this` or `asserts name`, then maybe `is` and a type (on any line).+ const name = at(token.end);+ if (name.kind === 'word' && !name.newline) {+ if (!isWord(name, 'this') && !identifier(name)) return -1;+ const is = at(name.end);+ return isWord(is, 'is') ? type(is.end, false) : name.end;+ }+ }+ return typeReference(k);+ };+ // parseTypeReference: a name — any word, dotted (parseEntityName) — and type arguments on its line.+ const typeReference = (k) => {+ const end = entityName(k);+ return end === -1 ? -1 : typeArgumentsOnLine(end, true);+ };+ const entityName = (k) => {+ const first = at(k);+ if (first.kind !== 'word') return -1;+ let end = first.end;+ for (;;) {+ const dot = at(end);+ if (dot.kind !== '.') return end;+ const name = at(dot.end);+ // `A.<T>`: the dot ends the name (a JSDoc-style list of type arguments, which the checker refuses).+ if (name.kind === '<') return dot.end;+ // parseRightSideOfDot: a word on the next line with another word after it on that line begins a declaration, and the name is missing.+ if (name.kind !== 'word' || (name.newline && at(name.end).kind === 'word' && !at(name.end).newline)) return -1;+ end = name.end;+ }+ };+ // Type arguments where they may stand: on the line of what they follow (parseTypeArgumentsOfTypeReference). Those of `typeof x<T>` are tried, and dropped where they do not+ // close (tryParseTypeArguments): `required` is false there.+ const typeArgumentsOnLine = (end, required) => {+ const open = at(end);+ if (open.kind !== '<' || open.newline) return end;+ const close = typeAnglesEnd(src, open.start);+ return close !== -1 ? close : required ? -1 : end;+ };+ // parseTypeQuery, after `typeof`: a name, then type arguments on its line.+ const typeQuery = (k) => {+ const end = entityName(k);+ return end === -1 ? -1 : typeArgumentsOnLine(end, false);+ };+ // parseImportType, from its `import`: `import(…)`, then maybe `.` and a name, then type arguments on the line.+ const importType = (k) => {+ const open = at(at(k).end);+ let end = open.kind === '(' ? typeGroupEnd(src, open.start) : -1;+ if (end !== -1 && at(end).kind === '.') end = entityName(at(end).end);+ return end === -1 ? -1 : typeArgumentsOnLine(end, true);+ };++ return typeOrPredicate(from);+}+// True when `name` is a local object binding. This is narrower than declaresName on purpose:// `export default pages.Home` is complete when `pages` is an object literal, but `React.memo` at EOF// is usually a truncated call on an imported namespace and remains rejected.diff --git a/plugins/pcf/scripts/tests/helpers/push-token-child.js b/plugins/pcf/scripts/tests/helpers/push-token-child.jsindex 98f9d4bda..41a1d3ec3 100644--- a/plugins/pcf/scripts/tests/helpers/push-token-child.js+++ b/plugins/pcf/scripts/tests/helpers/push-token-child.js@@ -3,7 +3,9 @@// (HTTP 403) with a diagnostic repeating the access token the process sent, folded onto several lines, so a test can read what reached the process's descriptors and its folders: stdout, stderr, the receipt// `pcf-receipt.json` and the SDK's workspace. Run by tests/pcf-push-token.test.js:// node push-token-child.js <project folder> <how the diagnostic spells the token>-// `how` is `folded` (every eight characters, as a gateway wraps a long header), `plain`, `escaped-fold` (the fold written as the JSON escape `\r\n`, as a diagnostic that was itself JSON holds it) or `none` (a diagnostic with no token in it).+// `how` is `folded` (every eight characters, as a gateway wraps a long header), `plain`, `escaped-fold` (the fold written as the JSON escape `\r\n`, as a diagnostic that was itself JSON holds it), `part-base64` (the+// characters of the signature's base64 that are made of its own bits, at the second alignment: what a longer encoded value holds of it), `part-base64-complete` (the signature's complete base64, padding and all) or `none`+// (a diagnostic with no token in it).const fs = require('node:fs');const path = require('node:path');const Module = require('node:module');@@ -11,7 +13,7 @@ const Module = require('node:module');const SCRIPTS = path.resolve(__dirname, '..', '..');const { createAzHttpClient } = require(path.join(SCRIPTS, 'lib', 'sdk-http-client.js'));const data = require(path.join(SCRIPTS, 'lib', 'pcf-dataverse.js'));-const { TOKEN } = require('./push-token.js');+const { TOKEN, PARTS, base64Of } = require('./push-token.js');const [, , project, how = 'folded'] = process.argv;const ORG = 'https://contoso.crm.dynamics.com';@@ -19,6 +21,8 @@ const spelling = {plain: TOKEN,folded: TOKEN.match(/.{1,8}/g).join('\r\n '),'escaped-fold': TOKEN.match(/.{1,8}/g).join('\\r\\n '),+ 'part-base64': base64Of(PARTS[2])[1],+ 'part-base64-complete': Buffer.from(PARTS[2]).toString('base64'),none: 'nothing secret here',}[how];if (spelling === undefined) throw new Error(`unknown spelling ${how}`);diff --git a/plugins/pcf/scripts/tests/helpers/push-token.js b/plugins/pcf/scripts/tests/helpers/push-token.jsindex d364797dc..60c6535c6 100644--- a/plugins/pcf/scripts/tests/helpers/push-token.js+++ b/plugins/pcf/scripts/tests/helpers/push-token.js@@ -13,4 +13,20 @@ const SECRETS = [TOKEN, ...PARTS];const views = (text) => [text, text.replace(/\s+/g, ''), text.replace(/\\+[rntf]/g, '').replace(/\s+/g, '')];const leaksIn = (text, secrets = SECRETS) => secrets.filter((secret) => views(String(text)).some((view) => view.includes(secret)));-module.exports = { PARTS, TOKEN, SECRETS, leaksIn };+// The base64 of `text` as it stands inside a longer value, at each of the three byte alignments, found by trying rather than by the module's arithmetic: the characters that stay the same whatever bytes stand before+// and after it (the characters at either end that also hold bits of a neighbour change with it, and are not the text's own).+function base64Of(text, alphabet = 'base64') {+ const spellings = [];+ for (let offset = 0; offset < 3; offset += 1) {+ const zeros = Buffer.concat([Buffer.alloc(offset, 0x00), Buffer.from(text), Buffer.alloc(3, 0x00)]).toString(alphabet);+ const ones = Buffer.concat([Buffer.alloc(offset, 0xff), Buffer.from(text), Buffer.alloc(3, 0xff)]).toString(alphabet);+ let from = 0;+ while (zeros[from] !== ones[from]) from += 1;+ let to = from;+ while (to < zeros.length && zeros[to] === ones[to]) to += 1;+ spellings.push(zeros.slice(from, to));+ }+ return spellings;+}++module.exports = { PARTS, TOKEN, SECRETS, leaksIn, base64Of };diff --git a/plugins/pcf/scripts/tests/pcf-push-token.test.js b/plugins/pcf/scripts/tests/pcf-push-token.test.jsindex 5c346ff8b..f6a22b6ed 100644--- a/plugins/pcf/scripts/tests/pcf-push-token.test.js+++ b/plugins/pcf/scripts/tests/pcf-push-token.test.js@@ -9,7 +9,7 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const { spawnSync } = require('node:child_process');-const { TOKEN, SECRETS, leaksIn } = require('./helpers/push-token.js');+const { TOKEN, SECRETS, PARTS, leaksIn, base64Of } = require('./helpers/push-token.js');const SCRIPTS = path.resolve(__dirname, '..');const CHILD = path.join(__dirname, 'helpers', 'push-token-child.js');@@ -68,6 +68,28 @@ test('a refusal that does not repeat the token is written to the receipt as theassert.deepEqual(leaksIn(ran.stdout), []);});+// The base64 of one part of the token — the signature — in the diagnostic: the characters made of its own bits are taken out; a complete encoding keeps the character that also holds the padding's bits, and the padding.+test('a refusal that repeats the BASE64 of a part of the token writes a receipt without it: exactly its own characters become the marker, and a complete encoding keeps only its fringe and padding — JSON still', () => {+ const own = base64Of(PARTS[2]);+ const spellings = [...own, ...base64Of(PARTS[2], 'base64url')];+ const windows = (secret) => Array.from({ length: Math.max(0, secret.length - 23) }, (_, i) => secret.slice(i, i + 24));+ const left = (text) => spellings.flatMap(windows).filter((window) => text.includes(window));+ const complete = Buffer.from(PARTS[2]).toString('base64');+ const fringe = complete.slice(own[0].length);+ assert.ok(complete.startsWith(own[0]) && fringe.length > 0, 'the complete encoding is the signature\'s own characters, a fringe character and padding');+ for (const [how, ending] of [['part-base64', MARK], ['part-base64-complete', `${MARK}${fringe}`]]) {+ const ran = pushWith(how);+ assert.equal(ran.status, 1, `${how}: ${ran.stderr.slice(0, 500)}`);+ const receipt = JSON.parse(ran.files.get('pcf-receipt.json'));+ assert.ok(receipt.registered.reason.startsWith('HTTP 403 from '), receipt.registered.reason);+ assert.ok(receipt.registered.reason.endsWith(`: Header check failed for value ${ending}`), `${how}: ${receipt.registered.reason}`);+ assert.deepEqual(left(ran.files.get('pcf-receipt.json')), [], `${how}: the receipt holds a piece of 24 characters of the signature's base64`);+ assert.deepEqual(left(ran.stdout), [], `${how}: stdout`);+ assert.deepEqual(left(ran.stderr), [], `${how}: stderr`);+ assert.equal(JSON.parse(ran.stdout).registered.reason, receipt.registered.reason, 'the receipt says what the result says');+ }+});+test('the receipt is the one file this plugin writes that carries a service\'s words, and it is written through the guard — every other write of file content is listed, with the reason it cannot carry a token', () => {const files = (dir, out = []) => {for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {