Skip to content

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

model-apps evals: agent routing eval, fixtures for every genpage prompt, 89 more checks (#688)

Akshay Maloo9e03581b26e3
diff --git a/.github/workflows/model-apps-agent-evals.yml b/.github/workflows/model-apps-agent-evals.yml
new file mode 100644
index 000000000..5933f6d22
--- /dev/null
+++ b/.github/workflows/model-apps-agent-evals.yml
@@ -0,0 +1,143 @@
+# Agent-in-the-loop evals for the model-apps plugin: launches a real agent CLI headlessly and
+# grades which skill it routes each prompt to (evals/model-apps/routing/).
+#
+# Why this is NOT part of model-apps-script-tests.yml (the per-PR gate):
+# * it is non-deterministic (graded as a pass RATE over several trials), so it must not be a
+# hard merge gate;
+# * it costs real model usage (~1 turn per trial; 20 cases x 3 trials per full run), billed to
+# the organization;
+# * fork PRs cannot be given Copilot request rights, so a required check would block outside
+# contributions.
+# The deterministic graders (genpage Layer 1/2, app-builder structural) DO run on every PR.
+#
+# When it runs:
+# * on a same-repo PR labelled `run-agent-evals` — use it on PRs that touch a SKILL.md
+# description, where routing is exactly what changed. Re-apply the label to re-run after
+# new commits. Report-only; not a required check;
+# * weekly (drift: the model behind the CLI changes even when this repo does not);
+# * on demand (workflow_dispatch) — e.g. before a release, or to compare models.
+#
+# Credentials: none to provision for the default agent. Copilot CLI authenticates with the
+# workflow's built-in GITHUB_TOKEN when the job holds `copilot-requests: write`; usage is billed
+# to the organization, which needs the "Allow use of Copilot CLI billed to the organization"
+# Copilot policy (on by default when Copilot CLI is enabled). See
+# https://docs.github.com/copilot/how-tos/copilot-cli/use-copilot-cli-in-actions
+# agent=claude (dispatch only) needs an ANTHROPIC_API_KEY secret and clean-skips without it.
+name: model-apps-agent-evals
+
+on:
+ pull_request:
+ types: [labeled]
+ branches:
+ - main
+ paths:
+ - "plugins/model-apps/skills/**"
+ - "plugins/model-apps/agents/**"
+ - "evals/model-apps/routing/**"
+ schedule:
+ - cron: "0 9 * * 1"
+ workflow_dispatch:
+ inputs:
+ agent:
+ description: "Agent CLI to drive"
+ type: choice
+ options: [copilot, claude]
+ default: copilot
+ tier:
+ description: "Tier filter (empty = all tiers)"
+ type: choice
+ options: ["", smoke, full, stress]
+ default: ""
+ runs:
+ description: "Trials per case"
+ default: "3"
+ model:
+ description: "Model passed to the CLI (empty = CLI default)"
+ default: ""
+
+permissions:
+ contents: read
+
+jobs:
+ routing-eval:
+ name: routing-eval (${{ inputs.agent || 'copilot' }})
+ # The label must be the one that triggered this event (adding any other label to a PR
+ # does not re-run the eval), and never from a fork.
+ if: >-
+ github.event_name != 'pull_request' ||
+ (github.event.label.name == 'run-agent-evals' &&
+ github.event.pull_request.head.repo.full_name == github.repository)
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ # Lets Copilot CLI authenticate with GITHUB_TOKEN. Scoped to this job only.
+ copilot-requests: write
+ env:
+ # Trials invoke plugin skills, whose hooks can emit telemetry; CI is not real usage.
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"
+ AGENT: ${{ inputs.agent || 'copilot' }}
+ TIER: ${{ inputs.tier || '' }}
+ RUNS: ${{ inputs.runs || '3' }}
+ MODEL: ${{ inputs.model || '' }}
+ # Pinned so a CLI release cannot change what the eval measures (or what runs with a
+ # model credential in scope) without a reviewed bump here.
+ COPILOT_CLI_VERSION: "1.0.92"
+ CLAUDE_CODE_VERSION: "2.1.284"
+ steps:
+ - name: check-credentials
+ id: creds
+ shell: bash
+ env:
+ HAS_ANTHROPIC: ${{ secrets.ANTHROPIC_API_KEY != '' }}
+ run: |
+ if [ "$AGENT" = "claude" ] && [ "$HAS_ANTHROPIC" != "true" ]; then
+ echo "::notice::ANTHROPIC_API_KEY is not configured; skipping the claude routing eval."
+ echo "skip=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "skip=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: checkout
+ if: steps.creds.outputs.skip != 'true'
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: setup-node
+ if: steps.creds.outputs.skip != 'true'
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 22
+
+ # No credential is in this step's environment: npm runs package install scripts.
+ - name: install-agent-cli
+ if: steps.creds.outputs.skip != 'true'
+ shell: bash
+ run: |
+ if [ "$AGENT" = "copilot" ]; then npm install -g "@github/copilot@${COPILOT_CLI_VERSION}"; else npm install -g "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}"; fi
+
+ # Exit 1 (a case under threshold) fails the run so the signal is visible; exit 2 is a
+ # harness error (CLI not authorized, plugin not loaded). Raw transcripts are
+ # deliberately NOT uploaded — this repo is public and a transcript can echo runner
+ # paths and model reasoning; the results JSON carries outcomes only.
+ - name: run-routing-eval
+ if: steps.creds.outputs.skip != 'true'
+ shell: bash
+ env:
+ # Only the selected agent's credential is set; the other resolves to ''.
+ GITHUB_TOKEN: ${{ (inputs.agent || 'copilot') == 'copilot' && github.token || '' }}
+ ANTHROPIC_API_KEY: ${{ (inputs.agent || 'copilot') == 'claude' && secrets.ANTHROPIC_API_KEY || '' }}
+ run: |
+ args=(--agent "$AGENT" --runs "$RUNS" --out routing-results.json)
+ [ -n "$TIER" ] && args+=(--tier "$TIER")
+ [ -n "$MODEL" ] && args+=(--model "$MODEL")
+ node evals/model-apps/routing/run-routing.js "${args[@]}"
+
+ - name: upload-results
+ if: always() && steps.creds.outputs.skip != 'true'
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: routing-results-${{ env.AGENT }}
+ path: routing-results.json
+ if-no-files-found: ignore
\ No newline at end of file
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index 152524d79..4324c7fa1 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -87,6 +87,14 @@ jobs:
working-directory: plugins/model-apps
run: node scripts/run-tests.js
+ # The routing eval's runner launches agent CLIs as child processes, and on Windows
+ # those are .cmd shims that must go through cmd.exe (quoting, process-tree kill). Its
+ # unit tests drive a fake agent only — no model, no credentials — so run them on every
+ # OS here; in the Ubuntu-only eval job below the Windows shim test would always skip.
+ - name: run-routing-eval-unit-tests
+ shell: bash
+ run: node --test evals/model-apps/routing/tests/*.test.js
+
test-model-apps-evals:
name: test-model-apps-evals
runs-on: ubuntu-latest
@@ -106,10 +114,12 @@ jobs:
# owned by this plugin, so it is gated by the same path filter. First the
# unit tests of the scoring/fixture code: `evals/model-apps/tests/` holds
# tests for code shared by the app-builder and genpage runners; a new test
- # directory has to be added here or it silently never runs.
+ # directory has to be added here or it silently never runs. The routing tests
+ # drive a FAKE agent process only; the real agent-in-the-loop routing eval runs
+ # in model-apps-agent-evals.yml, because it needs model access and is not a gate.
- name: run-model-apps-eval-tests
shell: bash
- run: node --test evals/model-apps/tests/*.test.js evals/model-apps/app-builder/tests/*.test.js evals/model-apps/genpage/tests/*.test.js
+ run: node --test evals/model-apps/tests/*.test.js evals/model-apps/app-builder/tests/*.test.js evals/model-apps/genpage/tests/*.test.js evals/model-apps/routing/tests/*.test.js
# Then the runners themselves. They score the COMMITTED fixtures — captured
# plans, transcripts and specs — offline, in about a second, with no
diff --git a/evals/model-apps/app-builder/EVAL_GUIDE.md b/evals/model-apps/app-builder/EVAL_GUIDE.md
index 15052e4eb..a43c5d059 100644
--- a/evals/model-apps/app-builder/EVAL_GUIDE.md
+++ b/evals/model-apps/app-builder/EVAL_GUIDE.md
@@ -155,6 +155,8 @@ exit 1; malformed fixtures and argument errors return exit 2.
The live smoke (`plugins/model-apps/scripts/smoke-eval.js`) grades actual Dataverse provisioning.
These offline evals complement it; they do not certify live deployment, SDK serialization or runtime UI behavior.
+Nor do they grade the *skill's* judgment: each fixture is a hand-authored App Spec, so the suite tests the deterministic engine (spec → plan → facts), not whether `/app-builder` authors a good spec from a user's intent. Whether a prompt reaches `/app-builder` at all is graded by the agent-in-the-loop routing eval in `evals/model-apps/routing/`.
+
## Cross-links
- Plugin `AGENTS.md` → *Eval Suite*
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index e48278bb4..2be1626e4 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -60,7 +60,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
### Layer 1 — Workflow assertions
-**Input:** `workflow-log.md`, `genpage-plan.md`, optionally `genpage-edit-plan.md` and `genpage-entity-creation-log.md` (legacy `entity-creation-log.md` remains supported). Current synthetic fixtures also supply `fixture.json`, ordered `tool-results.json` and the declared JSON/text/source snapshots.
+**Input:** `workflow-log.md`, `genpage-plan.md`, optionally `genpage-edit-plan.md`, `genpage-entity-creation-log.md` (legacy `entity-creation-log.md` remains supported) and a captured `RuntimeTypes.ts`. Current synthetic fixtures also supply `fixture.json`, ordered `tool-results.json` and the declared JSON/text/source snapshots.
**What it checks:**
- Prereq commands are recorded (`node --version`, `pac help` with version **> 2.10.0**)
@@ -75,6 +75,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- Current upload commands use `genpage-upload.js` with file transport; the preservation fixture compares exact approved/forwarded text and before/after name, model and binding sets
- Custom API discovery/gates/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
- Prefix discipline holds across plan, entity-creation log, and resolved names
+- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/`generate-types`/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
**Runner:** `evals/model-apps/genpage/run-layer-1.js`
**Library:** `lib/assertions-layer-1.js` (one check function per assertion text)
@@ -134,7 +135,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 **20 fixture directories / 26 top-level TSX files**, representing 18 prompt IDs. IDs **3, 6, 8, 9, 12, 14, 16** have no fixture and are not 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 **27 fixture directories / 34 top-level TSX files**, representing 25 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.
### Enumerating registered and unmatched checks
@@ -252,6 +253,13 @@ The suite ships both kinds:
| 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) | — |
+| 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) | — |
+| 12 | `12-account-plan-revision` (current plan revision) | — |
+| 14 | `14-account-list-edit-collision` (current filename collision) | — |
+| 16 | `16-account-list` (current minimal existing-table page) | — |
The mix gives:
- A **green baseline** to catch runner regressions (synthetics)
@@ -264,7 +272,7 @@ The mix gives:
`fixtures/contracts.json` explicitly labels the 13 existing directories as historical contract 1, without rewriting captured content. Raw PAC transport, legacy navigation spelling and missing transport/read-back artifacts are **not** certified as current compliant. Contract 2 uses a per-directory `fixture.json` and `tool-results.json`: one ordered record per command with its own result, plus `artifacts` listing the exact files to load. Artifact paths must stay inside the fixture and be plain files.
-The seven new fixtures exercise these current contracts:
+The first seven contract-2 fixtures exercise these current contracts:
| Fixture | Evidence/check | Negative control in scorer tests |
|---------|----------------|----------------------------------|
@@ -297,14 +305,14 @@ Exit codes:
### Filter by tier
```bash
-node run-layer-1.js --tier smoke # 4 stored fixtures, 5 prompt definitions
-node run-layer-1.js --tier full # 15 stored fixtures, 17 prompt definitions
-node run-layer-1.js --tier stress # 1 stored fixture (id 10), 3 prompt definitions
+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
```
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; plan-revision and filename-collision prompts still have no fixture.
+refusal, the plan-revision trace and the filename-collision trace.
### Filter by eval id (debugging)
@@ -358,6 +366,8 @@ When to run which tier:
- **Stress tier:** with the full suite, or when changing the orchestrator probe logic, filename validation, or plan-mode handling.
- **All tiers:** before bumping the plugin version (any 2.x.0 release).
+These runners grade artifacts a run already produced; none of them can see whether a prompt reached `/genpage` in the first place. That is graded by the agent-in-the-loop **routing eval** (`evals/model-apps/routing/`, see its `EVAL_GUIDE.md`), which runs on a PR labelled `run-agent-evals`, weekly, and on demand — label any PR that edits the skill's `description:`.
+
---
## Quick start
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index d9281c640..cc99a1d6b 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -387,9 +387,9 @@
"expectations": [
"Phase 1 (Planner): Plan initially contains a Pages table with 2 pages",
"Phase 5a: Orchestrator reads the Pages table and detects duplicate filenames",
- "Phase 5a: Orchestrator rewrites genpage-plan.md with unique filenames (e.g., account-list.tsx, account-edit.tsx) before dispatching builders",
- "Phase 5b: Two page-builders are invoked in parallel with distinct target filenames",
- "Phase 5b: No builder overwrites another builder's output (both .tsx files exist after Phase 5)",
+ "Phase 5a: check-page-files.js refuses the colliding plan and the orchestrator halts and re-plans through the planner (it never renames files itself), so genpage-plan.md carries unique, re-approved filenames (e.g., account-list.tsx, account-edit.tsx) before any builder is dispatched",
+ "Phase 5c: Two page-builders are invoked in parallel with distinct target filenames",
+ "Phase 5c: No builder overwrites another builder's output (both .tsx files exist after Phase 5)",
"Phase 6: Both pages are deployed with their distinct filenames"
]
},
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/.approved-genpage-plan.md b/evals/model-apps/genpage/fixtures/12-account-plan-revision/.approved-genpage-plan.md
new file mode 100644
index 000000000..cd3bd9daa
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/.approved-genpage-plan.md
@@ -0,0 +1,29 @@
+## Genpage Plan
+
+### Pages (1 total)
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Accounts | account-list.tsx | Account grid with a search box, a filter toolbar and sortable columns | account |
+
+### Data Strategy
+- Entities needed: account
+- Entities that exist: account
+- Entities to create: none
+- Connector bindings: none
+- Custom API bindings: none
+- Sample data: not applicable (no new entities)
+
+### App
+- Using: Contoso Sales (11111111-1111-4111-8111-111111111111)
+
+### Solution
+- Default / new (code-only flow; no solution question)
+
+### Localization
+- English only — no localization needed
+
+### Design
+- Revised per your feedback: a search box in the header (account name, account number, city, country/region, email, main phone) IN ADDITION TO the filter toolbar
+- Filter toolbar: Status (All / Active / Inactive), Industry, Country/Region, Clear filters, Refresh
+- Search and toolbar filters combine; every column sortable, default sort by account name
+- Window cache + in-flight de-dupe for the on-mount account query
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/account-list.tsx b/evals/model-apps/genpage/fixtures/12-account-plan-revision/account-list.tsx
new file mode 100644
index 000000000..badea8406
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/account-list.tsx
@@ -0,0 +1,534 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ GeneratedComponentProps,
+ account,
+ ReadableTableRow,
+ QueryTableOptions,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Badge,
+ SearchBox,
+ Toolbar,
+ ToolbarButton,
+ ToolbarDivider,
+ Dropdown,
+ Option,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import type { TableColumnSizingOptions } from '@fluentui/react-components';
+import { ArrowClockwiseRegular, FilterDismissRegular, FilterRegular, SearchRegular } from '@fluentui/react-icons';
+
+type AccountRow = ReadableTableRow<account>;
+type LoadedAccounts = { rows: AccountRow[]; hasMoreRows: boolean };
+type LoadState = LoadedAccounts & { loading: boolean; error: string | null };
+type StatusFilter = 'all' | 'active' | 'inactive';
+type Filters = { status: StatusFilter; industry: string; country: string };
+
+// Window-scoped cache + in-flight promise (references/data-caching.md, Pattern 1). The keys
+// carry the page name so another page querying account with a different select never shares them.
+const CACHE_KEY = '__ppAccountFilterList_accountCache';
+const INFLIGHT_KEY = '__ppAccountFilterList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const PAGE_SIZE = 500;
+const ALL = '__all__';
+const NO_FILTERS: Filters = { status: 'all', industry: ALL, country: ALL };
+const FORMATTED = '@OData.Community.Display.V1.FormattedValue';
+
+const ACCOUNT_QUERY: QueryTableOptions<account> = {
+ select: [
+ 'accountid',
+ 'name',
+ 'accountnumber',
+ 'industrycode',
+ 'address1_city',
+ 'address1_country',
+ 'telephone1',
+ 'emailaddress1',
+ 'statecode',
+ ],
+ orderBy: 'name asc',
+ pageSize: PAGE_SIZE,
+};
+
+const STATUS_LABELS: Record<StatusFilter, string> = {
+ all: 'All statuses',
+ active: 'Active',
+ inactive: 'Inactive',
+};
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ contain: 'layout',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ height: '100%',
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: tokens.spacingHorizontalXL,
+ overflow: 'hidden',
+ color: tokens.colorNeutralForeground1,
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ titleBlock: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ },
+ subtitle: {
+ color: tokens.colorNeutralForeground2,
+ },
+ search: {
+ minWidth: '240px',
+ maxWidth: '360px',
+ flexGrow: 1,
+ '@media (max-width: 640px)': {
+ maxWidth: '100%',
+ },
+ },
+ toolbar: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ paddingTop: tokens.spacingVerticalXS,
+ paddingBottom: tokens.spacingVerticalXS,
+ paddingLeft: tokens.spacingHorizontalS,
+ paddingRight: tokens.spacingHorizontalS,
+ backgroundColor: tokens.colorNeutralBackground2,
+ borderRadius: tokens.borderRadiusMedium,
+ },
+ toolbarLabel: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalXS,
+ color: tokens.colorNeutralForeground2,
+ fontWeight: tokens.fontWeightSemibold,
+ },
+ filterDropdown: {
+ minWidth: '160px',
+ '@media (max-width: 640px)': {
+ minWidth: '100%',
+ },
+ },
+ gridArea: {
+ flexGrow: 1,
+ minHeight: 0,
+ overflow: 'auto',
+ borderTopWidth: tokens.strokeWidthThin,
+ borderRightWidth: tokens.strokeWidthThin,
+ borderBottomWidth: tokens.strokeWidthThin,
+ borderLeftWidth: tokens.strokeWidthThin,
+ borderTopStyle: 'solid',
+ borderRightStyle: 'solid',
+ borderBottomStyle: 'solid',
+ borderLeftStyle: 'solid',
+ borderTopColor: tokens.colorNeutralStroke2,
+ borderRightColor: tokens.colorNeutralStroke2,
+ borderBottomColor: tokens.colorNeutralStroke2,
+ borderLeftColor: tokens.colorNeutralStroke2,
+ borderRadius: tokens.borderRadiusMedium,
+ },
+ truncate: {
+ display: 'block',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ cellLayout: {
+ minWidth: 0,
+ overflow: 'hidden',
+ },
+ centered: {
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ padding: tokens.spacingVerticalXXL,
+ color: tokens.colorNeutralForeground2,
+ },
+ footer: {
+ color: tokens.colorNeutralForeground2,
+ },
+});
+
+function formattedValue(row: AccountRow, field: string): string {
+ const value = (row as unknown as Record<string, unknown>)[`${field}${FORMATTED}`];
+ return typeof value === 'string' ? value : '';
+}
+
+function textOf(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function compareText(a: string, b: string): number {
+ return a.localeCompare(b, undefined, { sensitivity: 'base' });
+}
+
+function isActive(row: AccountRow): boolean {
+ // statecode 0 = Active, 1 = Inactive for every Dataverse table with a state model.
+ return Number(row.statecode) === 0;
+}
+
+function matchesSearch(row: AccountRow, term: string): boolean {
+ if (!term) return true;
+ const haystack = [
+ textOf(row.name),
+ textOf(row.accountnumber),
+ textOf(row.address1_city),
+ textOf(row.address1_country),
+ textOf(row.emailaddress1),
+ textOf(row.telephone1),
+ ];
+ return haystack.some((value) => value.toLowerCase().includes(term));
+}
+
+function matchesFilters(row: AccountRow, filters: Filters): boolean {
+ if (filters.status === 'active' && !isActive(row)) return false;
+ if (filters.status === 'inactive' && isActive(row)) return false;
+ if (filters.industry !== ALL && formattedValue(row, 'industrycode') !== filters.industry) return false;
+ if (filters.country !== ALL && textOf(row.address1_country) !== filters.country) return false;
+ return true;
+}
+
+function distinctValues(rows: AccountRow[], pick: (row: AccountRow) => string): string[] {
+ const values = new Set<string>();
+ for (const row of rows) {
+ const value = pick(row).trim();
+ if (value) values.add(value);
+ }
+ return Array.from(values).sort(compareText);
+}
+
+function activeFilterCount(filters: Filters): number {
+ return (filters.status !== 'all' ? 1 : 0) + (filters.industry !== ALL ? 1 : 0) + (filters.country !== ALL ? 1 : 0);
+}
+
+function readCache(): LoadedAccounts | undefined {
+ return winAny[CACHE_KEY] as LoadedAccounts | undefined;
+}
+
+function TextCell(props: { value: string; className: string; layoutClassName: string }) {
+ return (
+ <TableCellLayout className={props.layoutClassName}>
+ <span className={props.className} title={props.value}>
+ {props.value || '—'}
+ </span>
+ </TableCellLayout>
+ );
+}
+
+const COLUMN_SIZING: TableColumnSizingOptions = {
+ name: { defaultWidth: 240, minWidth: 180 },
+ accountnumber: { defaultWidth: 130, minWidth: 100 },
+ industry: { defaultWidth: 170, minWidth: 130 },
+ city: { defaultWidth: 140, minWidth: 110 },
+ country: { defaultWidth: 140, minWidth: 110 },
+ phone: { defaultWidth: 150, minWidth: 120 },
+ email: { defaultWidth: 220, minWidth: 160 },
+ status: { defaultWidth: 110, minWidth: 90 },
+};
+
+function buildColumns(truncate: string, cellLayout: string) {
+ return [
+ createTableColumn<AccountRow>({
+ columnId: 'name',
+ compare: (a, b) => compareText(textOf(a.name), textOf(b.name)),
+ renderHeaderCell: () => 'Account name',
+ renderCell: (item) => <TextCell value={textOf(item.name)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'accountnumber',
+ compare: (a, b) => compareText(textOf(a.accountnumber), textOf(b.accountnumber)),
+ renderHeaderCell: () => 'Account number',
+ renderCell: (item) => <TextCell value={textOf(item.accountnumber)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'industry',
+ compare: (a, b) => compareText(formattedValue(a, 'industrycode'), formattedValue(b, 'industrycode')),
+ renderHeaderCell: () => 'Industry',
+ renderCell: (item) => <TextCell value={formattedValue(item, 'industrycode')} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'city',
+ compare: (a, b) => compareText(textOf(a.address1_city), textOf(b.address1_city)),
+ renderHeaderCell: () => 'City',
+ renderCell: (item) => <TextCell value={textOf(item.address1_city)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'country',
+ compare: (a, b) => compareText(textOf(a.address1_country), textOf(b.address1_country)),
+ renderHeaderCell: () => 'Country/Region',
+ renderCell: (item) => <TextCell value={textOf(item.address1_country)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'phone',
+ compare: (a, b) => compareText(textOf(a.telephone1), textOf(b.telephone1)),
+ renderHeaderCell: () => 'Main phone',
+ renderCell: (item) => <TextCell value={textOf(item.telephone1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'email',
+ compare: (a, b) => compareText(textOf(a.emailaddress1), textOf(b.emailaddress1)),
+ renderHeaderCell: () => 'Email',
+ renderCell: (item) => <TextCell value={textOf(item.emailaddress1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'status',
+ compare: (a, b) => Number(a.statecode) - Number(b.statecode),
+ renderHeaderCell: () => 'Status',
+ renderCell: (item) => (
+ <TableCellLayout>
+ <Badge appearance="tint" color={isActive(item) ? 'success' : 'informative'}>
+ {formattedValue(item, 'statecode') || (isActive(item) ? 'Active' : 'Inactive')}
+ </Badge>
+ </TableCellLayout>
+ ),
+ }),
+ ];
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // list page takes no input; destructured per the component contract
+ const styles = useStyles();
+ const dataReady = !!dataApi;
+
+ // Overlay listboxes portal into this element instead of the designer's document.body (Rule 16).
+ const [mountNode, setMountNode] = useState<HTMLElement | null>(null);
+ const [{ rows, hasMoreRows, loading, error }, setData] = useState<LoadState>(() => {
+ const cached = readCache();
+ return cached
+ ? { rows: cached.rows, hasMoreRows: cached.hasMoreRows, loading: false, error: null }
+ : { rows: [], hasMoreRows: false, loading: true, error: null };
+ });
+ const [reloadKey, setReloadKey] = useState(0);
+ const [search, setSearch] = useState('');
+ const [filters, setFilters] = useState<Filters>(NO_FILTERS);
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = readCache();
+ if (cached !== undefined) {
+ if (cached.rows !== rows) setData({ rows: cached.rows, hasMoreRows: cached.hasMoreRows, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // One shared promise on window: the host double-mounts the page on open, and the second
+ // mount must await this query rather than issue its own.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<LoadedAccounts> | undefined;
+ if (!inflight) {
+ const pending: Promise<LoadedAccounts> = (async () => {
+ const result = await dataApi.queryTable('account', ACCOUNT_QUERY);
+ const loaded: LoadedAccounts = { rows: result.rows, hasMoreRows: result.hasMoreRows };
+ winAny[CACHE_KEY] = loaded;
+ return loaded;
+ })().finally(() => {
+ if (winAny[INFLIGHT_KEY] === pending) delete winAny[INFLIGHT_KEY];
+ });
+ winAny[INFLIGHT_KEY] = pending;
+ inflight = pending;
+ }
+ const shared = inflight;
+
+ (async () => {
+ try {
+ const loaded = await shared;
+ if (!cancelled) setData({ rows: loaded.rows, hasMoreRows: loaded.hasMoreRows, loading: false, error: null });
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load accounts.';
+ setData({ rows: [], hasMoreRows: false, loading: false, error: message });
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and the manual reload key only: dataApi is a new reference on every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ const columns = useMemo(() => buildColumns(styles.truncate, styles.cellLayout), [styles.truncate, styles.cellLayout]);
+ const industries = useMemo(() => distinctValues(rows, (row) => formattedValue(row, 'industrycode')), [rows]);
+ const countries = useMemo(() => distinctValues(rows, (row) => textOf(row.address1_country)), [rows]);
+ const visibleRows = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ return rows.filter((row) => matchesSearch(row, term) && matchesFilters(row, filters));
+ }, [rows, search, filters]);
+
+ const filterCount = activeFilterCount(filters);
+
+ const refresh = () => {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ rows: [], hasMoreRows: false, loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ };
+
+ const clearFilters = () => setFilters(NO_FILTERS);
+
+ if (loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading accounts…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root} ref={setMountNode}>
+ <header className={styles.header}>
+ <div className={styles.titleBlock}>
+ <Text as="h1" size={700} weight="semibold">
+ Accounts
+ </Text>
+ <Text size={200} className={styles.subtitle}>
+ Search, filter and sort account records
+ </Text>
+ </div>
+ <SearchBox
+ className={styles.search}
+ placeholder="Search name, number, city, email or phone"
+ value={search}
+ onChange={(_, data) => setSearch(data.value ?? '')}
+ contentBefore={<SearchRegular />}
+ aria-label="Search accounts"
+ />
+ </header>
+
+ <Toolbar className={styles.toolbar} aria-label="Account filters">
+ <span className={styles.toolbarLabel}>
+ <FilterRegular aria-hidden="true" />
+ Filters
+ {filterCount > 0 && (
+ <Badge size="small" appearance="filled" color="brand" aria-label={`${filterCount} filters applied`}>
+ {filterCount}
+ </Badge>
+ )}
+ </span>
+ <Dropdown
+ className={styles.filterDropdown}
+ aria-label="Filter by status"
+ value={STATUS_LABELS[filters.status]}
+ selectedOptions={[filters.status]}
+ onOptionSelect={(_, data) =>
+ setFilters((prev) => ({ ...prev, status: (data.optionValue as StatusFilter | undefined) ?? 'all' }))
+ }
+ mountNode={mountNode}
+ >
+ <Option value="all">All statuses</Option>
+ <Option value="active">Active</Option>
+ <Option value="inactive">Inactive</Option>
+ </Dropdown>
+ <Dropdown
+ className={styles.filterDropdown}
+ aria-label="Filter by industry"
+ value={filters.industry === ALL ? 'All industries' : filters.industry}
+ selectedOptions={[filters.industry]}
+ onOptionSelect={(_, data) => setFilters((prev) => ({ ...prev, industry: data.optionValue ?? ALL }))}
+ mountNode={mountNode}
+ >
+ <Option value={ALL}>All industries</Option>
+ {industries.map((industry) => (
+ <Option key={industry} value={industry}>
+ {industry}
+ </Option>
+ ))}
+ </Dropdown>
+ <Dropdown
+ className={styles.filterDropdown}
+ aria-label="Filter by country or region"
+ value={filters.country === ALL ? 'All countries/regions' : filters.country}
+ selectedOptions={[filters.country]}
+ onOptionSelect={(_, data) => setFilters((prev) => ({ ...prev, country: data.optionValue ?? ALL }))}
+ mountNode={mountNode}
+ >
+ <Option value={ALL}>All countries/regions</Option>
+ {countries.map((country) => (
+ <Option key={country} value={country}>
+ {country}
+ </Option>
+ ))}
+ </Dropdown>
+ <ToolbarDivider />
+ <ToolbarButton icon={<FilterDismissRegular />} onClick={clearFilters} disabled={filterCount === 0}>
+ Clear filters
+ </ToolbarButton>
+ <ToolbarButton icon={<ArrowClockwiseRegular />} onClick={refresh} aria-label="Refresh accounts">
+ Refresh
+ </ToolbarButton>
+ </Toolbar>
+
+ {error && (
+ <MessageBar intent="error">
+ <MessageBarBody>{error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <div className={styles.gridArea}>
+ {visibleRows.length === 0 ? (
+ <div className={styles.centered} role="status">
+ <Text>{rows.length === 0 ? 'No accounts found.' : 'No accounts match the current search and filters.'}</Text>
+ </div>
+ ) : (
+ <DataGrid
+ items={visibleRows}
+ columns={columns}
+ getRowId={(item) => item.accountid}
+ sortable
+ defaultSortState={{ sortColumn: 'name', sortDirection: 'ascending' }}
+ resizableColumns
+ columnSizingOptions={COLUMN_SIZING}
+ focusMode="composite"
+ aria-label="Accounts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<AccountRow>>
+ {({ item, rowId }) => (
+ <DataGridRow<AccountRow> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+
+ <Text size={200} className={styles.footer} role="status">
+ Showing {visibleRows.length} of {rows.length} accounts
+ {hasMoreRows ? ` (first ${PAGE_SIZE} by name — refine your search to narrow the list)` : ''}
+ </Text>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/agent-message.txt b/evals/model-apps/genpage/fixtures/12-account-plan-revision/agent-message.txt
new file mode 100644
index 000000000..252bc1779
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/agent-message.txt
@@ -0,0 +1 @@
+Created an Accounts page with a search box, a filter toolbar (status, industry, country/region) and sortable columns.
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/fixture.json b/evals/model-apps/genpage/fixtures/12-account-plan-revision/fixture.json
new file mode 100644
index 000000000..7d29381f2
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/fixture.json
@@ -0,0 +1,16 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed attended single-page trace, not an agent capture. The first plan presentation is rejected with 'add a search box in addition to the filter toolbar'; the planner revises, the revised plan is re-presented and approved, and only then is genpage-plan.md written and provenance-verified against the approved (revised) body. The generated page has both the search box and the filter toolbar.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan, Steps 5-7 (revision re-presentation, approval writeback, plan provenance)",
+ "plugins/model-apps/agents/genpage-planner.md Step 5: Hand the Plan Back for Approval",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a and 5b: Validate the plan; Single-page fast path",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy",
+ "plugins/model-apps/references/rules.md DataGrid Requirements and Data Fetching"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": [".approved-genpage-plan.md", "prompt.txt", "agent-message.txt", "page-name.txt"],
+ "worker": { "targets": ["account-list.tsx"] }
+}
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/genpage-plan.md b/evals/model-apps/genpage/fixtures/12-account-plan-revision/genpage-plan.md
new file mode 100644
index 000000000..9b8c51625
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/genpage-plan.md
@@ -0,0 +1,60 @@
+# Genpage Plan
+
+## User Requirements
+Build a page showing Account records with a filter toolbar and sortable columns.
+
+Revision requested at plan approval: add a search box in addition to the filter toolbar.
+
+## Working Directory
+D:/work/account-filter-list
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Sales (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Accounts | account-list.tsx | Account grid with a search box, a filter toolbar and sortable columns | 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: Fluent UI V9 defaults with theme tokens; title and search box share the header row, the filter toolbar sits directly below it, and only the grid area scrolls.
+- Features: free-text search box (account name, account number, city, country/region, email, main phone) applied together with a filter toolbar (status, industry, country/region, clear filters, refresh); every grid column sortable, default sort by account name ascending.
+- Accessibility: labelled search box and filter dropdowns, toolbar exposed with an aria-label, keyboard-navigable DataGrid, WCAG AA contrast via tokens.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Accounts | 9-list-with-caching.tsx | Dataverse list with SearchBox, window cache and in-flight de-dupe |
+| Accounts | 1-account-grid.tsx | Account DataGrid with sortable columns via createTableColumn compare |
+
+## Per-Page Specifications
+
+### Accounts
+- **File:** account-list.tsx
+- **Purpose:** Account grid with a search box, a filter toolbar and sortable columns
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** SearchBox in the header filters rows by name, account number, city, country/region, email and main phone; a Toolbar below the header holds Status (All / Active / Inactive), Industry and Country/Region dropdowns plus Clear filters and Refresh buttons; search and toolbar filters combine (AND); every column is sortable; a footer shows "Showing X of Y accounts" and notes when more than 500 rows exist.
+- **Components:** SearchBox, Toolbar, ToolbarButton, ToolbarDivider, Dropdown, Option, Badge, DataGrid (DataGridHeader, DataGridHeaderCell, DataGridBody, DataGridRow, DataGridCell), TableCellLayout, createTableColumn, MessageBar, Spinner, Text; icons SearchRegular, FilterRegular, FilterDismissRegular, ArrowClockwiseRegular.
+- **Layout:** Flex-column root filling the host container (position relative, contain layout); header row wraps on narrow widths; toolbar wraps its controls; grid area flexes and scrolls; no viewport units.
+- **Data Binding:** dataApi.queryTable("account") on mount selecting accountid, name, accountnumber, industrycode, address1_city, address1_country, telephone1, emailaddress1, statecode; orderBy name asc, pageSize 500; read result.rows; industry and status labels from @OData.Community.Display.V1.FormattedValue; window cache plus in-flight de-dupe keyed by page name; single batched setData; readiness-only dependencies.
+- **Interactions:** Typing in the search box and choosing toolbar filters narrow the grid client-side; Clear filters resets the toolbar (search text is kept); Refresh evicts the cache and in-flight entry and refetches; clicking a column header sorts by that column; filter dropdown listboxes use the page mountNode.
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/page-name.txt b/evals/model-apps/genpage/fixtures/12-account-plan-revision/page-name.txt
new file mode 100644
index 000000000..2fe961567
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/page-name.txt
@@ -0,0 +1 @@
+Accounts
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/prompt.txt b/evals/model-apps/genpage/fixtures/12-account-plan-revision/prompt.txt
new file mode 100644
index 000000000..01784d2ce
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/prompt.txt
@@ -0,0 +1,3 @@
+Build a page showing Account records with a filter toolbar and sortable columns.
+
+Revision requested at plan approval: add a search box in addition to the filter toolbar.
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/tool-results.json b/evals/model-apps/genpage/fixtures/12-account-plan-revision/tool-results.json
new file mode 100644
index 000000000..f9ac7f702
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/tool-results.json
@@ -0,0 +1,41 @@
+[
+ {
+ "id": "interaction-mode",
+ "command": "node scripts\\resolve-interaction-mode.js",
+ "result": { "ok": true, "interactive": true, "reason": "default (attended)" }
+ },
+ {
+ "id": "plan-prepare",
+ "command": "node scripts\\genpage-plan-provenance.js prepare --plan genpage-plan.md",
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\account-filter-list\\genpage-plan.md", "quarantinedPath": null }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node scripts\\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md",
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\account-filter-list\\genpage-plan.md", "kind": "create", "targets": ["account-list.tsx"], "writtenHash": "e0318b452fdd6f6eeeefe99cd0a4c599e19c9008eb4066de32411064dc6988d3" }
+ },
+ {
+ "id": "page-files",
+ "command": "node scripts\\check-page-files.js --plan genpage-plan.md",
+ "result": { "ok": true, "workingDir": "D:\\work\\account-filter-list", "files": ["account-list.tsx"], "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "stamp",
+ "command": "node scripts\\genpage-worker-output.js --stamp --file account-list.tsx",
+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\account-filter-list\\account-list.tsx", "existed": false }
+ },
+ { "id": "write", "command": "Write account-list.tsx", "artifact": "account-list.tsx" },
+ {
+ "id": "gate",
+ "command": "node scripts\\genpage-worker-output.js --file account-list.tsx",
+ "artifact": "account-list.tsx",
+ "result": { "ok": true, "filePath": "D:\\work\\account-filter-list\\account-list.tsx", "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "upload",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file account-list.tsx --name-file page-name.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "12121212-1212-4212-8212-121212121212", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/12-account-plan-revision/workflow-log.md b/evals/model-apps/genpage/fixtures/12-account-plan-revision/workflow-log.md
new file mode 100644
index 000000000..532b8e8c2
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/12-account-plan-revision/workflow-log.md
@@ -0,0 +1,130 @@
+# Workflow Log — Eval 12: Account page, plan revised at approval
+
+Synthetic trace constructed from the current SKILL.md phases, not a captured agent run.
+Commands run from the working directory; `scripts\` is `${PLUGIN_ROOT}\scripts`.
+
+## Phase 0 — Working directory setup
+- `node scripts\check-version.js` → no output (plugin up to date)
+- Working directory created: `D:\work\account-filter-list` (kebab-case from "Account records with a filter toolbar")
+
+## Phase 0.5 — Local-dev manifest
+- `node scripts\generate-page-manifest.js 'D:\work\account-filter-list' 'account-filter-list'` → exit 0; wrote package.json and genpage.d.ts (no --features)
+
+## Phase 1 — Plan (interactive steps in the main loop; discovery via genpage-planner)
+
+### Interaction mode
+- `node scripts\resolve-interaction-mode.js` → {"ok":true,"interactive":true,"reason":"default (attended)"} — attended run
+
+### Prereq checks (run separately, not chained with &&)
+- `node --version` → v20.20.2
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
+
+### Auth check
+- `pac auth list` → one profile, active (*): [email protected], https://contoso.crm.dynamics.com/
+- Active environment reported to user: "Working with environment: Contoso (https://contoso.crm.dynamics.com)"
+
+### Questions
+- AskUserQuestion: Create new page(s) or edit an existing one? → Create new page(s)
+- `pac model list-languages` → 1033 English en-US (RTL: No) only → no localization
+- Description question skipped: the /genpage arguments already describe the page
+- Data source question skipped: the description names Account records → Dataverse entity: account
+- AskUserQuestion: Any specific requirements? → Filter toolbar and sortable columns
+
+### Entity detection
+- `pac model list-tables --search 'account'` → rows account, accountleads, accountlevelmonitoring; exact logical-name match `account` → exists
+- No entity creation required
+
+### App detection
+- `pac model list` → 2 apps (Contoso Sales, Contoso Service)
+- AskUserQuestion: Which model-driven app should the page be added to? → Contoso Sales (11111111-1111-4111-8111-111111111111)
+
+### Solution selection
+- Code-only flow (existing entity, existing app) → solution selection question SKIPPED
+- Defaults recorded for the plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Connector / Custom API contracts
+- First planner invocation received `No connector bindings.` and `No custom API bindings.`; the planner returned no connector_discovery_required or custom_api_discovery_required action
+
+### Plan presentation 1 — changes requested
+- Task genpage-planner (discovery + plan) returned the proposed plan with one page, Accounts
+- EnterPlanMode called with the initial plan:
+ - Pages (1 total): Accounts | account-list.tsx | Account grid with a filter toolbar and sortable columns | account
+ - Design: filter toolbar (Status, Industry, Country/Region, Clear filters, Refresh); every column sortable, default sort by account name; no search box
+- ExitPlanMode called → changes requested (revised): "add a search box in addition to the filter toolbar"
+- genpage-plan.md NOT written: the planner writes the plan only after approval
+
+### Revision
+- Task genpage-planner re-invoked with the revision request plus everything already discovered (attended mode, create new, environment, languages, account exists, app Contoso Sales, Default/new, both binding sentinels) so no question was asked twice
+- Planner returned the revised plan: same page and file name; Design now adds a header search box (account name, account number, city, country/region, email, main phone) that combines with the unchanged filter toolbar; Key Features/Components updated with SearchBox
+
+### Plan presentation 2 — approved
+- EnterPlanMode called with the revised plan (search box + filter toolbar + sortable columns)
+- ExitPlanMode called → approved
+
+### Plan written (planner authorship + provenance)
+- `node scripts\genpage-plan-provenance.js prepare --plan genpage-plan.md` → {"ok":true,"action":"prepare","quarantinedPath":null} (no earlier plan existed)
+- Approved (revised) plan body saved verbatim to `.approved-genpage-plan.md`
+- Task genpage-planner re-invoked with outcome approved plus the revised plan body and all discovery → wrote genpage-plan.md
+- `node scripts\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md` → {"ok":true,"kind":"create","targets":["account-list.tsx"]}
+- writtenHash: e0318b452fdd6f6eeeefe99cd0a4c599e19c9008eb4066de32411064dc6988d3
+- genpage-plan.md is the REVISED version: ## User Requirements carries the revision, ## Design Preferences and the Accounts per-page spec list the search box alongside the filter toolbar
+
+## Phase 2 — Entity creation
+- SKIPPED: plan says "No entity creation required — all entities already exist."
+- check-auth.js not run (no entity work); entity builder not dispatched
+
+## Phase 3 — App creation/selection
+- SKIPPED: existing app Contoso Sales (11111111-1111-4111-8111-111111111111)
+
+## Phase 4 — RuntimeTypes
+- `pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-filter-list/RuntimeTypes.ts'` → RuntimeTypes.ts written
+- Read RuntimeTypes.ts: account columns accountid, name, accountnumber, industrycode, address1_city, address1_country, telephone1, emailaddress1, statecode verified
+
+## Phase 4.5 — Connector bindings
+- Plan says `No connector bindings.` → Connectors: none; no connectors.json, no --connectors
+
+## Phase 4.6 — Custom API bindings
+- `node scripts\lib\feature-flags.js custom-api` → disabled; plan body is exactly `No custom API bindings.` → continue with no actions.json
+
+## Phase 4.7 — Page telemetry
+- `node scripts\lib\feature-flags.js custom-telemetry` → disabled → Telemetry: disabled
+
+## Phase 5a — Plan validation
+- 1 page in ## Pages; ### Accounts subsection present in ## Per-Page Specifications
+- `node scripts\check-page-files.js --plan genpage-plan.md` → {"ok":true,"files":["account-list.tsx"],"problems":[]}
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → inlined build, no Task subagent for the page builder
+- Data mode: dataverse; Connectors: none; Telemetry: disabled
+- Read references/rules.md
+- Read samples/9-list-with-caching.tsx and samples/1-account-grid.tsx (## Relevant Samples)
+- Needs caching: true → read references/data-caching.md
+- Read genpage-plan.md and RuntimeTypes.ts
+- `node scripts\genpage-worker-output.js --stamp --file account-list.tsx` → {"ok":true,"action":"stamp","existed":false}
+- Wrote account-list.tsx implementing the revised plan: SearchBox in the header AND the filter Toolbar (Status, Industry, Country/Region dropdowns, Clear filters, Refresh), sortable DataGrid columns with createTableColumn compare + resizableColumns/columnSizingOptions
+- Icon verification against references/verified-icons.txt (one Grep per name from the `@fluentui/react-icons` import): SearchRegular, FilterRegular, FilterDismissRegular, ArrowClockwiseRegular — all present
+- Grep `['"]?borderWidth['"]?\s*:` → no matches (four explicit border-side widths used)
+- `node scripts\genpage-worker-output.js --file account-list.tsx` → {"ok":true,"problems":[]}
+
+## Phase 6 — Deploy
+- Cleared prompt.txt, agent-message.txt and page-name.txt (none was a link or folder), then wrote them with the file tool
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file account-list.tsx --name-file page-name.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap`
+- Prompt scope: full page description from plan's `## User Requirements` (create), including the approved revision
+- Result: page-id = 12121212-1212-4212-8212-121212121212, status = success (associated result in tool-results.json)
+
+## Phase 6.5 — Navigation fix-up
+- SKIPPED: single page, no PAGEREF_ tokens
+
+## 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 | account-list.tsx | account | Deployed |
+
+- App: Contoso Sales (11111111-1111-4111-8111-111111111111)
+- Entities created: none
+- Plan presentations: 2 (first: changes requested — add a search box; second: approved)
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.approved-genpage-plan.md b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.approved-genpage-plan.md
new file mode 100644
index 000000000..69519f133
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.approved-genpage-plan.md
@@ -0,0 +1,29 @@
+## Genpage Plan
+
+### Pages (2 total)
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Accounts | account-list.tsx | List of all Account records with search, sortable columns and an Edit action per row | account |
+| Edit Account | account-edit.tsx | Edit form for a single Account record opened from the Accounts list | account |
+
+### Data Strategy
+- Entities needed: account
+- Entities that exist: account
+- Entities to create: none
+- Connector bindings: none
+- Custom API bindings: none
+- Sample data: not applicable (no new entities)
+
+### App
+- Using: Contoso Sales (11111111-1111-4111-8111-111111111111)
+
+### Solution
+- Default / new (code-only flow; no solution question)
+
+### Localization
+- English only — no localization needed
+
+### Design
+- Re-planned after the Phase 5a page-file gate refused the earlier plan: both pages had been assigned account.tsx, so parallel builders would have overwritten each other. Pages, purposes and design are unchanged; only the file names (and the PAGEREF tokens derived from them) differ.
+- Accounts (account-list.tsx): all accounts, search, sortable columns, Edit action → Edit Account via PAGEREF_account-edit with data.accountId
+- Edit Account (account-edit.tsx): reads pageInput.data.accountId, saves changed fields with updateRow, Back → Accounts via PAGEREF_account-list
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md
new file mode 100644
index 000000000..63dd0e62a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/.genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md
@@ -0,0 +1,71 @@
+# Genpage Plan
+
+## User Requirements
+Build two pages for tracking Account records — one for listing all accounts and one for editing a single account.
+
+## Working Directory
+D:/work/account-tracking
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Sales (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Accounts | account.tsx | List of all Account records with search, sortable columns and an Edit action per row | account |
+| Edit Account | account.tsx | Edit form for a single Account record opened from the Accounts list | 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: Fluent UI V9 defaults with theme tokens; list page fills the host container with a scrolling grid area; edit page uses a card form, two columns on wide screens and one column on narrow screens.
+- Features: list shows all accounts (paged with loadMoreRows, capped at 5,000 rows), client-side search and sortable columns; each row has an Edit action that opens the Edit Account page for that row; the edit page saves only changed fields, can discard changes and navigates back to the list.
+- Accessibility: labelled search box and form fields, required marker and validation message on Account name, keyboard-navigable DataGrid, Edit buttons carry the account name in their aria-label.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Accounts | 9-list-with-caching.tsx | Dataverse list with SearchBox, sibling-page PAGEREF navigation, window cache and in-flight de-dupe |
+| Edit Account | 10-detail-with-pageinput.tsx | Page reached by navigateTo that reads its input and caches per record |
+| Edit Account | 3-account-crud-dataverse.tsx | Account updateRow with verified column names |
+
+## Per-Page Specifications
+
+### Accounts
+- **File:** account.tsx
+- **Purpose:** List of all Account records with search, sortable columns and an Edit action per row
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** All accounts loaded page by page (queryTable pageSize 250, then loadMoreRows until hasMoreRows is false or 5,000 rows); SearchBox filters by name, account number, city, email and main phone; sortable columns (default account name ascending); Refresh button; footer "Showing X of Y accounts".
+- **Components:** SearchBox, Button, DataGrid (DataGridHeader, DataGridHeaderCell, DataGridBody, DataGridRow, DataGridCell), TableCellLayout, createTableColumn, MessageBar, Spinner, Text; icons SearchRegular, EditRegular, ArrowClockwiseRegular.
+- **Layout:** Flex-column root filling the host container; header with title opposite the search box and Refresh; grid area flexes and scrolls; columnSizingOptions for every column plus resizableColumns.
+- **Data Binding:** dataApi.queryTable("account") selecting accountid, name, accountnumber, address1_city, telephone1, emailaddress1; orderBy name asc; read result.rows; window keys `__ppAccountList_accountCache` and `__ppAccountList_accountInflight`; single batched setData; readiness-only dependencies plus a reload key.
+- **Interactions:** Edit button on each row calls Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_account", data: { accountId } }); Refresh evicts both window keys and refetches; column headers sort.
+
+### Edit Account
+- **File:** account.tsx
+- **Purpose:** Edit form for a single Account record opened from the Accounts list
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** Reads the account id from pageInput.data.accountId (GUID string; braces tolerated); retrieves the record and shows an edit form for name (required), account number, main phone, email (format-checked), website, street, city, state/province, ZIP/postal code, country/region and description; Save sends only changed fields (emptied fields clear the column); Discard changes restores the loaded values; unsaved-changes warning; success and error MessageBars; empty state with a Back button when no account id was passed.
+- **Components:** Card, Field, Input, Textarea, Button, Divider, MessageBar, Spinner, Text; icons ArrowLeftRegular, SaveRegular, ArrowUndoRegular.
+- **Layout:** Scrolling flex-column root; header with Back button, title and last-modified date; card with Account details, Address and Description sections; field grid collapses to one column under 720px.
+- **Data Binding:** dataApi.retrieveRow("account", { id, select: accountid, name, accountnumber, telephone1, emailaddress1, websiteurl, address1_line1, address1_city, address1_stateorprovince, address1_postalcode, address1_country, description, modifiedon }); modifiedon shown from its FormattedValue annotation; per-record Map cache and in-flight Map on window (`__ppAccountEdit_accountCache`, `__ppAccountEdit_accountInflight`); dataApi.updateRow("account", id, changedFields) in try/catch; after a successful save update the record cache and delete `__ppAccountList_accountCache` and `__ppAccountList_accountInflight` so the list refetches; one state object, one setData per outcome.
+- **Interactions:** Back buttons call Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_account" }); Save submits the form; Discard changes resets the form.
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-edit.tsx b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-edit.tsx
new file mode 100644
index 000000000..d4ddbe840
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-edit.tsx
@@ -0,0 +1,467 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ GeneratedComponentProps,
+ account,
+ ReadableTableRow,
+ RetrieveRowOptions,
+ WritableTableRow,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ Card,
+ Divider,
+ Field,
+ Input,
+ Textarea,
+ MessageBar,
+ MessageBarBody,
+} from '@fluentui/react-components';
+import { ArrowLeftRegular, ArrowUndoRegular, SaveRegular } from '@fluentui/react-icons';
+
+type AccountRow = ReadableTableRow<account>;
+type XrmNavigation = { Navigation?: { navigateTo?: (input: Record<string, unknown>) => Promise<unknown> } };
+
+const EDITABLE_FIELDS = [
+ 'name',
+ 'accountnumber',
+ 'telephone1',
+ 'emailaddress1',
+ 'websiteurl',
+ 'address1_line1',
+ 'address1_city',
+ 'address1_stateorprovince',
+ 'address1_postalcode',
+ 'address1_country',
+ 'description',
+] as const;
+type EditableField = (typeof EDITABLE_FIELDS)[number];
+type AccountForm = Record<EditableField, string>;
+type Notice = { intent: 'success' | 'error'; text: string };
+type PageState = {
+ record: AccountRow | null;
+ form: AccountForm;
+ loading: boolean;
+ error: string | null;
+ saving: boolean;
+ showErrors: boolean;
+ notice: Notice | null;
+};
+
+const FIELD_LABELS: Record<EditableField, string> = {
+ name: 'Account name',
+ accountnumber: 'Account number',
+ telephone1: 'Main phone',
+ emailaddress1: 'Email',
+ websiteurl: 'Website',
+ address1_line1: 'Street',
+ address1_city: 'City',
+ address1_stateorprovince: 'State/Province',
+ address1_postalcode: 'ZIP/Postal code',
+ address1_country: 'Country/Region',
+ description: 'Description',
+};
+
+const DETAILS_FIELDS: EditableField[] = ['name', 'accountnumber', 'telephone1', 'emailaddress1', 'websiteurl'];
+const ADDRESS_FIELDS: EditableField[] = ['address1_line1', 'address1_city', 'address1_stateorprovince', 'address1_postalcode', 'address1_country'];
+
+const SELECT_COLUMNS: RetrieveRowOptions<account>['select'] = [
+ 'accountid',
+ 'name',
+ 'accountnumber',
+ 'telephone1',
+ 'emailaddress1',
+ 'websiteurl',
+ 'address1_line1',
+ 'address1_city',
+ 'address1_stateorprovince',
+ 'address1_postalcode',
+ 'address1_country',
+ 'description',
+ 'modifiedon',
+];
+
+// Per-record Map cache + in-flight Map on window (references/data-caching.md, Pattern 2), so the
+// host double-mount retrieves each account once and a return visit renders without a spinner.
+const DETAIL_CACHE_KEY = '__ppAccountEdit_accountCache';
+const DETAIL_INFLIGHT_KEY = '__ppAccountEdit_accountInflight';
+// Owned by the Accounts list page; evicted after a save so the list shows the edit on return.
+const LIST_CACHE_KEY = '__ppAccountList_accountCache';
+const LIST_INFLIGHT_KEY = '__ppAccountList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+const detailCache: Map<string, AccountRow> =
+ (winAny[DETAIL_CACHE_KEY] as Map<string, AccountRow> | undefined) ?? new Map<string, AccountRow>();
+winAny[DETAIL_CACHE_KEY] = detailCache;
+const detailInflight: Map<string, Promise<AccountRow>> =
+ (winAny[DETAIL_INFLIGHT_KEY] as Map<string, Promise<AccountRow>> | undefined) ?? new Map<string, Promise<AccountRow>>();
+winAny[DETAIL_INFLIGHT_KEY] = detailInflight;
+
+const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ contain: 'layout',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ height: '100%',
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: tokens.spacingHorizontalXL,
+ overflowY: 'auto',
+ color: tokens.colorNeutralForeground1,
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ titleBlock: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ title: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ meta: {
+ color: tokens.colorNeutralForeground2,
+ },
+ card: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalL,
+ maxWidth: '960px',
+ },
+ sectionTitle: {
+ fontWeight: tokens.fontWeightSemibold,
+ },
+ fieldGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ columnGap: tokens.spacingHorizontalL,
+ rowGap: tokens.spacingVerticalM,
+ '@media (max-width: 720px)': {
+ gridTemplateColumns: 'minmax(0, 1fr)',
+ },
+ },
+ actions: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalS,
+ },
+ centered: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingVerticalXXL,
+ color: tokens.colorNeutralForeground2,
+ textAlign: 'center',
+ },
+});
+
+function readAccountId(pageInput: { data?: Record<string, unknown> } | undefined): string | undefined {
+ // pageInput.data values are unknown-typed primitives; accept only a GUID string (braces allowed).
+ const raw = pageInput?.data?.accountId;
+ if (typeof raw !== 'string') return undefined;
+ const trimmed = raw.trim().replace(/^\{/, '').replace(/\}$/, '');
+ return GUID_PATTERN.test(trimmed) ? trimmed.toLowerCase() : undefined;
+}
+
+function fieldText(row: AccountRow | null, field: string): string {
+ if (!row) return '';
+ const value = (row as unknown as Record<string, unknown>)[field];
+ return typeof value === 'string' ? value : '';
+}
+
+function toForm(row: AccountRow | null): AccountForm {
+ const form = {} as AccountForm;
+ for (const field of EDITABLE_FIELDS) form[field] = fieldText(row, field);
+ return form;
+}
+
+function changedFields(original: AccountForm, current: AccountForm): EditableField[] {
+ return EDITABLE_FIELDS.filter((field) => original[field] !== current[field]);
+}
+
+function validate(form: AccountForm): Partial<Record<EditableField, string>> {
+ const errors: Partial<Record<EditableField, string>> = {};
+ if (!form.name.trim()) errors.name = 'Account name is required.';
+ if (form.emailaddress1.trim() && !EMAIL_PATTERN.test(form.emailaddress1.trim())) {
+ errors.emailaddress1 = 'Enter a valid email address.';
+ }
+ return errors;
+}
+
+function toPayload(form: AccountForm, fields: EditableField[]): Record<string, string | null> {
+ // An emptied text box clears the column rather than storing an empty string.
+ const payload: Record<string, string | null> = {};
+ for (const field of fields) {
+ const value = form[field].trim();
+ payload[field] = value ? value : null;
+ }
+ return payload;
+}
+
+function openAccountsList() {
+ const xrm = (window as unknown as { Xrm?: XrmNavigation }).Xrm;
+ void xrm?.Navigation?.navigateTo?.({
+ pageType: "generative",
+ pageId: "14141414-1414-4414-8414-141414141401",
+ });
+}
+
+function initialState(accountId: string | undefined): PageState {
+ const cached = accountId ? detailCache.get(accountId) : undefined;
+ return {
+ record: cached ?? null,
+ form: toForm(cached ?? null),
+ loading: !!accountId && cached === undefined,
+ error: null,
+ saving: false,
+ showErrors: false,
+ notice: null,
+ };
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ const styles = useStyles();
+
+ // Derived synchronously from props on every render; never copied into state.
+ const accountId = readAccountId(pageInput as { data?: Record<string, unknown> } | undefined);
+ const dataReady = !!dataApi && !!accountId;
+
+ const [state, setData] = useState<PageState>(() => initialState(accountId));
+ const { record, form, loading, error, saving, showErrors, notice } = state;
+
+ useEffect(() => {
+ if (!dataReady || !accountId) return;
+ const id = accountId;
+
+ const hit = detailCache.get(id);
+ if (hit !== undefined) {
+ if (record !== hit) {
+ setData({ record: hit, form: toForm(hit), loading: false, error: null, saving: false, showErrors: false, notice: null });
+ }
+ return;
+ }
+ let cancelled = false;
+
+ let pending = detailInflight.get(id);
+ if (!pending) {
+ const request: Promise<AccountRow> = (async () => {
+ const row = await dataApi.retrieveRow('account', { id, select: SELECT_COLUMNS });
+ detailCache.set(id, row);
+ return row;
+ })().finally(() => {
+ if (detailInflight.get(id) === request) detailInflight.delete(id);
+ });
+ detailInflight.set(id, request);
+ pending = request;
+ }
+ const shared = pending;
+
+ (async () => {
+ try {
+ const row = await shared;
+ if (!cancelled) {
+ setData({ record: row, form: toForm(row), loading: false, error: null, saving: false, showErrors: false, notice: null });
+ }
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load the account.';
+ setData({ record: null, form: toForm(null), loading: false, error: message, saving: false, showErrors: false, notice: null });
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and the account id only: dataApi is a new reference on every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, accountId]);
+
+ const original = useMemo(() => toForm(record), [record]);
+ const changed = useMemo(() => changedFields(original, form), [original, form]);
+ const errors = useMemo(() => validate(form), [form]);
+
+ const setField = (field: EditableField, value: string) => {
+ setData((prev) => ({ ...prev, form: { ...prev.form, [field]: value }, notice: null }));
+ };
+
+ const discard = () => {
+ setData((prev) => ({ ...prev, form: toForm(prev.record), showErrors: false, notice: null }));
+ };
+
+ const handleSave = async () => {
+ if (!accountId || !record || saving || changed.length === 0) return;
+ if (Object.keys(errors).length > 0) {
+ setData((prev) => ({ ...prev, showErrors: true, notice: { intent: 'error', text: 'Fix the highlighted fields before saving.' } }));
+ return;
+ }
+ const payload = toPayload(form, changed);
+ setData((prev) => ({ ...prev, saving: true, notice: null }));
+ try {
+ await dataApi.updateRow('account', accountId, payload as unknown as WritableTableRow<account>);
+ const merged = { ...record, ...payload } as unknown as AccountRow;
+ detailCache.set(accountId, merged);
+ delete winAny[LIST_CACHE_KEY];
+ delete winAny[LIST_INFLIGHT_KEY];
+ setData({
+ record: merged,
+ form: toForm(merged),
+ loading: false,
+ error: null,
+ saving: false,
+ showErrors: false,
+ notice: { intent: 'success', text: 'Account saved.' },
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Unable to save the account.';
+ setData((prev) => ({ ...prev, saving: false, notice: { intent: 'error', text: message } }));
+ }
+ };
+
+ const renderField = (field: EditableField) => {
+ const message = showErrors ? errors[field] : undefined;
+ return (
+ <Field
+ key={field}
+ label={FIELD_LABELS[field]}
+ required={field === 'name'}
+ validationState={message ? 'error' : 'none'}
+ validationMessage={message}
+ >
+ <Input
+ type={field === 'emailaddress1' ? 'email' : field === 'websiteurl' ? 'url' : 'text'}
+ value={form[field]}
+ onChange={(_, data) => setField(field, data.value)}
+ disabled={saving}
+ />
+ </Field>
+ );
+ };
+
+ if (!accountId) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Text>No account selected. Open this page from the Accounts list.</Text>
+ <Button icon={<ArrowLeftRegular />} onClick={openAccountsList}>
+ Back to accounts
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading account…" />
+ </div>
+ </div>
+ );
+ }
+
+ if (!record) {
+ return (
+ <div className={styles.root}>
+ <MessageBar intent="error">
+ <MessageBarBody>{error ?? 'The account could not be found.'}</MessageBarBody>
+ </MessageBar>
+ <div>
+ <Button icon={<ArrowLeftRegular />} onClick={openAccountsList}>
+ Back to accounts
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ const modifiedOn = fieldText(record, '[email protected]');
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <Button appearance="subtle" icon={<ArrowLeftRegular />} onClick={openAccountsList} aria-label="Back to accounts">
+ Back
+ </Button>
+ <div className={styles.titleBlock}>
+ <Text as="h1" size={700} weight="semibold" className={styles.title}>
+ Edit {original.name || 'account'}
+ </Text>
+ {modifiedOn && (
+ <Text size={200} className={styles.meta}>
+ Last modified {modifiedOn}
+ </Text>
+ )}
+ </div>
+ </header>
+
+ {notice && (
+ <MessageBar intent={notice.intent}>
+ <MessageBarBody>{notice.text}</MessageBarBody>
+ </MessageBar>
+ )}
+ {!notice && changed.length > 0 && (
+ <MessageBar intent="warning">
+ <MessageBarBody>You have unsaved changes.</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <form
+ aria-label="Edit account"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleSave();
+ }}
+ >
+ <Card className={styles.card}>
+ <Text as="h2" size={400} className={styles.sectionTitle}>
+ Account details
+ </Text>
+ <div className={styles.fieldGrid}>{DETAILS_FIELDS.map(renderField)}</div>
+ <Divider />
+ <Text as="h2" size={400} className={styles.sectionTitle}>
+ Address
+ </Text>
+ <div className={styles.fieldGrid}>{ADDRESS_FIELDS.map(renderField)}</div>
+ <Divider />
+ <Field label={FIELD_LABELS.description}>
+ <Textarea
+ value={form.description}
+ onChange={(_, data) => setField('description', data.value)}
+ resize="vertical"
+ disabled={saving}
+ />
+ </Field>
+ <div className={styles.actions}>
+ <Button type="submit" appearance="primary" icon={saving ? <Spinner size="tiny" /> : <SaveRegular />} disabled={saving || changed.length === 0}>
+ {saving ? 'Saving' : 'Save'}
+ </Button>
+ <Button type="button" icon={<ArrowUndoRegular />} onClick={discard} disabled={saving || changed.length === 0}>
+ Discard changes
+ </Button>
+ </div>
+ </Card>
+ </form>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-list.tsx b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-list.tsx
new file mode 100644
index 000000000..da4a4ffb9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/account-list.tsx
@@ -0,0 +1,370 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ GeneratedComponentProps,
+ account,
+ ReadableTableRow,
+ QueryTableOptions,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ SearchBox,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import type { TableColumnSizingOptions } from '@fluentui/react-components';
+import { ArrowClockwiseRegular, EditRegular, SearchRegular } from '@fluentui/react-icons';
+
+type AccountRow = ReadableTableRow<account>;
+type LoadedAccounts = { rows: AccountRow[]; truncated: boolean };
+type LoadState = LoadedAccounts & { loading: boolean; error: string | null };
+type XrmNavigation = { Navigation?: { navigateTo?: (input: Record<string, unknown>) => Promise<unknown> } };
+
+// Window-scoped list cache + in-flight promise (references/data-caching.md, Pattern 1). The Edit
+// Account page evicts these two keys after a successful save so this list refetches on return.
+const CACHE_KEY = '__ppAccountList_accountCache';
+const INFLIGHT_KEY = '__ppAccountList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const PAGE_SIZE = 250;
+// "All accounts" is read page by page through loadMoreRows; the cap keeps a very large table from
+// holding thousands of rows in window memory, and the footer says when it was reached.
+const MAX_ROWS = 5000;
+
+const LIST_QUERY: QueryTableOptions<account> = {
+ select: ['accountid', 'name', 'accountnumber', 'address1_city', 'telephone1', 'emailaddress1'],
+ orderBy: 'name asc',
+ pageSize: PAGE_SIZE,
+};
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ contain: 'layout',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ height: '100%',
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: tokens.spacingHorizontalXL,
+ overflow: 'hidden',
+ color: tokens.colorNeutralForeground1,
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ headerActions: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ flexGrow: 1,
+ justifyContent: 'flex-end',
+ '@media (max-width: 640px)': {
+ justifyContent: 'stretch',
+ },
+ },
+ search: {
+ minWidth: '220px',
+ maxWidth: '360px',
+ flexGrow: 1,
+ },
+ gridArea: {
+ flexGrow: 1,
+ minHeight: 0,
+ overflow: 'auto',
+ },
+ truncate: {
+ display: 'block',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ cellLayout: {
+ minWidth: 0,
+ overflow: 'hidden',
+ },
+ centered: {
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ padding: tokens.spacingVerticalXXL,
+ color: tokens.colorNeutralForeground2,
+ },
+ footer: {
+ color: tokens.colorNeutralForeground2,
+ },
+});
+
+function textOf(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function compareText(a: string, b: string): number {
+ return a.localeCompare(b, undefined, { sensitivity: 'base' });
+}
+
+function matchesSearch(row: AccountRow, term: string): boolean {
+ if (!term) return true;
+ return [row.name, row.accountnumber, row.address1_city, row.emailaddress1, row.telephone1]
+ .map(textOf)
+ .some((value) => value.toLowerCase().includes(term));
+}
+
+function readCache(): LoadedAccounts | undefined {
+ return winAny[CACHE_KEY] as LoadedAccounts | undefined;
+}
+
+function openEditPage(accountId: string) {
+ const xrm = (window as unknown as { Xrm?: XrmNavigation }).Xrm;
+ // The sibling Edit Account page receives the id in `data` (never recordId) and reads it as
+ // pageInput.data.accountId. Phase 6.5 replaces the placeholder with the deployed page id.
+ void xrm?.Navigation?.navigateTo?.({
+ pageType: "generative",
+ pageId: "14141414-1414-4414-8414-141414141402",
+ data: { accountId },
+ });
+}
+
+function TextCell(props: { value: string; className: string; layoutClassName: string }) {
+ return (
+ <TableCellLayout className={props.layoutClassName}>
+ <span className={props.className} title={props.value}>
+ {props.value || '—'}
+ </span>
+ </TableCellLayout>
+ );
+}
+
+const COLUMN_SIZING: TableColumnSizingOptions = {
+ name: { defaultWidth: 260, minWidth: 180 },
+ accountnumber: { defaultWidth: 140, minWidth: 110 },
+ city: { defaultWidth: 160, minWidth: 120 },
+ phone: { defaultWidth: 160, minWidth: 120 },
+ email: { defaultWidth: 240, minWidth: 160 },
+ actions: { defaultWidth: 100, minWidth: 90 },
+};
+
+function buildColumns(truncate: string, cellLayout: string) {
+ return [
+ createTableColumn<AccountRow>({
+ columnId: 'name',
+ compare: (a, b) => compareText(textOf(a.name), textOf(b.name)),
+ renderHeaderCell: () => 'Account name',
+ renderCell: (item) => <TextCell value={textOf(item.name)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'accountnumber',
+ compare: (a, b) => compareText(textOf(a.accountnumber), textOf(b.accountnumber)),
+ renderHeaderCell: () => 'Account number',
+ renderCell: (item) => <TextCell value={textOf(item.accountnumber)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'city',
+ compare: (a, b) => compareText(textOf(a.address1_city), textOf(b.address1_city)),
+ renderHeaderCell: () => 'City',
+ renderCell: (item) => <TextCell value={textOf(item.address1_city)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'phone',
+ compare: (a, b) => compareText(textOf(a.telephone1), textOf(b.telephone1)),
+ renderHeaderCell: () => 'Main phone',
+ renderCell: (item) => <TextCell value={textOf(item.telephone1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'email',
+ compare: (a, b) => compareText(textOf(a.emailaddress1), textOf(b.emailaddress1)),
+ renderHeaderCell: () => 'Email',
+ renderCell: (item) => <TextCell value={textOf(item.emailaddress1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'actions',
+ renderHeaderCell: () => 'Actions',
+ renderCell: (item) => (
+ <TableCellLayout>
+ <Button
+ appearance="subtle"
+ size="small"
+ icon={<EditRegular />}
+ onClick={() => openEditPage(item.accountid)}
+ aria-label={`Edit ${textOf(item.name) || 'account'}`}
+ >
+ Edit
+ </Button>
+ </TableCellLayout>
+ ),
+ }),
+ ];
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // the list page takes no input; destructured per the component contract
+ const styles = useStyles();
+ const dataReady = !!dataApi;
+
+ const [{ rows, truncated, loading, error }, setData] = useState<LoadState>(() => {
+ const cached = readCache();
+ return cached
+ ? { rows: cached.rows, truncated: cached.truncated, loading: false, error: null }
+ : { rows: [], truncated: false, loading: true, error: null };
+ });
+ const [reloadKey, setReloadKey] = useState(0);
+ const [search, setSearch] = useState('');
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = readCache();
+ if (cached !== undefined) {
+ if (cached.rows !== rows) setData({ rows: cached.rows, truncated: cached.truncated, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // The host double-mounts the page on open; the second mount awaits this shared promise.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<LoadedAccounts> | undefined;
+ if (!inflight) {
+ const pending: Promise<LoadedAccounts> = (async () => {
+ let page = await dataApi.queryTable('account', LIST_QUERY);
+ const all: AccountRow[] = [...page.rows];
+ while (page.hasMoreRows && page.loadMoreRows && all.length < MAX_ROWS) {
+ page = await page.loadMoreRows();
+ all.push(...page.rows);
+ }
+ const loaded: LoadedAccounts = { rows: all, truncated: page.hasMoreRows };
+ winAny[CACHE_KEY] = loaded;
+ return loaded;
+ })().finally(() => {
+ if (winAny[INFLIGHT_KEY] === pending) delete winAny[INFLIGHT_KEY];
+ });
+ winAny[INFLIGHT_KEY] = pending;
+ inflight = pending;
+ }
+ const shared = inflight;
+
+ (async () => {
+ try {
+ const loaded = await shared;
+ if (!cancelled) setData({ rows: loaded.rows, truncated: loaded.truncated, loading: false, error: null });
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load accounts.';
+ setData({ rows: [], truncated: false, loading: false, error: message });
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and the manual reload key only: dataApi is a new reference on every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ const columns = useMemo(() => buildColumns(styles.truncate, styles.cellLayout), [styles.truncate, styles.cellLayout]);
+ const visibleRows = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ return rows.filter((row) => matchesSearch(row, term));
+ }, [rows, search]);
+
+ const refresh = () => {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ rows: [], truncated: false, loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ };
+
+ if (loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading accounts…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <Text as="h1" size={700} weight="semibold">
+ Accounts
+ </Text>
+ <div className={styles.headerActions}>
+ <SearchBox
+ className={styles.search}
+ placeholder="Search name, number, city, email or phone"
+ value={search}
+ onChange={(_, data) => setSearch(data.value ?? '')}
+ contentBefore={<SearchRegular />}
+ aria-label="Search accounts"
+ />
+ <Button icon={<ArrowClockwiseRegular />} onClick={refresh} aria-label="Refresh accounts">
+ Refresh
+ </Button>
+ </div>
+ </header>
+
+ {error && (
+ <MessageBar intent="error">
+ <MessageBarBody>{error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <div className={styles.gridArea}>
+ {visibleRows.length === 0 ? (
+ <div className={styles.centered} role="status">
+ <Text>{rows.length === 0 ? 'No accounts found.' : 'No accounts match your search.'}</Text>
+ </div>
+ ) : (
+ <DataGrid
+ items={visibleRows}
+ columns={columns}
+ getRowId={(item) => item.accountid}
+ sortable
+ defaultSortState={{ sortColumn: 'name', sortDirection: 'ascending' }}
+ resizableColumns
+ columnSizingOptions={COLUMN_SIZING}
+ focusMode="composite"
+ aria-label="Accounts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<AccountRow>>
+ {({ item, rowId }) => (
+ <DataGridRow<AccountRow> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+
+ <Text size={200} className={styles.footer} role="status">
+ Showing {visibleRows.length} of {rows.length} accounts
+ {truncated ? ` (only the first ${MAX_ROWS} accounts by name are loaded)` : ''}
+ </Text>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/agent-message.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/agent-message.txt
new file mode 100644
index 000000000..dd587ae89
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/agent-message.txt
@@ -0,0 +1 @@
+Created an Accounts list page and an Edit Account page that navigate to each other.
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-edit.tsx b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-edit.tsx
new file mode 100644
index 000000000..fdc721d73
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-edit.tsx
@@ -0,0 +1,467 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ GeneratedComponentProps,
+ account,
+ ReadableTableRow,
+ RetrieveRowOptions,
+ WritableTableRow,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ Card,
+ Divider,
+ Field,
+ Input,
+ Textarea,
+ MessageBar,
+ MessageBarBody,
+} from '@fluentui/react-components';
+import { ArrowLeftRegular, ArrowUndoRegular, SaveRegular } from '@fluentui/react-icons';
+
+type AccountRow = ReadableTableRow<account>;
+type XrmNavigation = { Navigation?: { navigateTo?: (input: Record<string, unknown>) => Promise<unknown> } };
+
+const EDITABLE_FIELDS = [
+ 'name',
+ 'accountnumber',
+ 'telephone1',
+ 'emailaddress1',
+ 'websiteurl',
+ 'address1_line1',
+ 'address1_city',
+ 'address1_stateorprovince',
+ 'address1_postalcode',
+ 'address1_country',
+ 'description',
+] as const;
+type EditableField = (typeof EDITABLE_FIELDS)[number];
+type AccountForm = Record<EditableField, string>;
+type Notice = { intent: 'success' | 'error'; text: string };
+type PageState = {
+ record: AccountRow | null;
+ form: AccountForm;
+ loading: boolean;
+ error: string | null;
+ saving: boolean;
+ showErrors: boolean;
+ notice: Notice | null;
+};
+
+const FIELD_LABELS: Record<EditableField, string> = {
+ name: 'Account name',
+ accountnumber: 'Account number',
+ telephone1: 'Main phone',
+ emailaddress1: 'Email',
+ websiteurl: 'Website',
+ address1_line1: 'Street',
+ address1_city: 'City',
+ address1_stateorprovince: 'State/Province',
+ address1_postalcode: 'ZIP/Postal code',
+ address1_country: 'Country/Region',
+ description: 'Description',
+};
+
+const DETAILS_FIELDS: EditableField[] = ['name', 'accountnumber', 'telephone1', 'emailaddress1', 'websiteurl'];
+const ADDRESS_FIELDS: EditableField[] = ['address1_line1', 'address1_city', 'address1_stateorprovince', 'address1_postalcode', 'address1_country'];
+
+const SELECT_COLUMNS: RetrieveRowOptions<account>['select'] = [
+ 'accountid',
+ 'name',
+ 'accountnumber',
+ 'telephone1',
+ 'emailaddress1',
+ 'websiteurl',
+ 'address1_line1',
+ 'address1_city',
+ 'address1_stateorprovince',
+ 'address1_postalcode',
+ 'address1_country',
+ 'description',
+ 'modifiedon',
+];
+
+// Per-record Map cache + in-flight Map on window (references/data-caching.md, Pattern 2), so the
+// host double-mount retrieves each account once and a return visit renders without a spinner.
+const DETAIL_CACHE_KEY = '__ppAccountEdit_accountCache';
+const DETAIL_INFLIGHT_KEY = '__ppAccountEdit_accountInflight';
+// Owned by the Accounts list page; evicted after a save so the list shows the edit on return.
+const LIST_CACHE_KEY = '__ppAccountList_accountCache';
+const LIST_INFLIGHT_KEY = '__ppAccountList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+const detailCache: Map<string, AccountRow> =
+ (winAny[DETAIL_CACHE_KEY] as Map<string, AccountRow> | undefined) ?? new Map<string, AccountRow>();
+winAny[DETAIL_CACHE_KEY] = detailCache;
+const detailInflight: Map<string, Promise<AccountRow>> =
+ (winAny[DETAIL_INFLIGHT_KEY] as Map<string, Promise<AccountRow>> | undefined) ?? new Map<string, Promise<AccountRow>>();
+winAny[DETAIL_INFLIGHT_KEY] = detailInflight;
+
+const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ contain: 'layout',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ height: '100%',
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: tokens.spacingHorizontalXL,
+ overflowY: 'auto',
+ color: tokens.colorNeutralForeground1,
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ titleBlock: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ title: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ meta: {
+ color: tokens.colorNeutralForeground2,
+ },
+ card: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalL,
+ maxWidth: '960px',
+ },
+ sectionTitle: {
+ fontWeight: tokens.fontWeightSemibold,
+ },
+ fieldGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ columnGap: tokens.spacingHorizontalL,
+ rowGap: tokens.spacingVerticalM,
+ '@media (max-width: 720px)': {
+ gridTemplateColumns: 'minmax(0, 1fr)',
+ },
+ },
+ actions: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalS,
+ },
+ centered: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingVerticalXXL,
+ color: tokens.colorNeutralForeground2,
+ textAlign: 'center',
+ },
+});
+
+function readAccountId(pageInput: { data?: Record<string, unknown> } | undefined): string | undefined {
+ // pageInput.data values are unknown-typed primitives; accept only a GUID string (braces allowed).
+ const raw = pageInput?.data?.accountId;
+ if (typeof raw !== 'string') return undefined;
+ const trimmed = raw.trim().replace(/^\{/, '').replace(/\}$/, '');
+ return GUID_PATTERN.test(trimmed) ? trimmed.toLowerCase() : undefined;
+}
+
+function fieldText(row: AccountRow | null, field: string): string {
+ if (!row) return '';
+ const value = (row as unknown as Record<string, unknown>)[field];
+ return typeof value === 'string' ? value : '';
+}
+
+function toForm(row: AccountRow | null): AccountForm {
+ const form = {} as AccountForm;
+ for (const field of EDITABLE_FIELDS) form[field] = fieldText(row, field);
+ return form;
+}
+
+function changedFields(original: AccountForm, current: AccountForm): EditableField[] {
+ return EDITABLE_FIELDS.filter((field) => original[field] !== current[field]);
+}
+
+function validate(form: AccountForm): Partial<Record<EditableField, string>> {
+ const errors: Partial<Record<EditableField, string>> = {};
+ if (!form.name.trim()) errors.name = 'Account name is required.';
+ if (form.emailaddress1.trim() && !EMAIL_PATTERN.test(form.emailaddress1.trim())) {
+ errors.emailaddress1 = 'Enter a valid email address.';
+ }
+ return errors;
+}
+
+function toPayload(form: AccountForm, fields: EditableField[]): Record<string, string | null> {
+ // An emptied text box clears the column rather than storing an empty string.
+ const payload: Record<string, string | null> = {};
+ for (const field of fields) {
+ const value = form[field].trim();
+ payload[field] = value ? value : null;
+ }
+ return payload;
+}
+
+function openAccountsList() {
+ const xrm = (window as unknown as { Xrm?: XrmNavigation }).Xrm;
+ void xrm?.Navigation?.navigateTo?.({
+ pageType: "generative",
+ pageId: "PAGEREF_account-list",
+ });
+}
+
+function initialState(accountId: string | undefined): PageState {
+ const cached = accountId ? detailCache.get(accountId) : undefined;
+ return {
+ record: cached ?? null,
+ form: toForm(cached ?? null),
+ loading: !!accountId && cached === undefined,
+ error: null,
+ saving: false,
+ showErrors: false,
+ notice: null,
+ };
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ const styles = useStyles();
+
+ // Derived synchronously from props on every render; never copied into state.
+ const accountId = readAccountId(pageInput as { data?: Record<string, unknown> } | undefined);
+ const dataReady = !!dataApi && !!accountId;
+
+ const [state, setData] = useState<PageState>(() => initialState(accountId));
+ const { record, form, loading, error, saving, showErrors, notice } = state;
+
+ useEffect(() => {
+ if (!dataReady || !accountId) return;
+ const id = accountId;
+
+ const hit = detailCache.get(id);
+ if (hit !== undefined) {
+ if (record !== hit) {
+ setData({ record: hit, form: toForm(hit), loading: false, error: null, saving: false, showErrors: false, notice: null });
+ }
+ return;
+ }
+ let cancelled = false;
+
+ let pending = detailInflight.get(id);
+ if (!pending) {
+ const request: Promise<AccountRow> = (async () => {
+ const row = await dataApi.retrieveRow('account', { id, select: SELECT_COLUMNS });
+ detailCache.set(id, row);
+ return row;
+ })().finally(() => {
+ if (detailInflight.get(id) === request) detailInflight.delete(id);
+ });
+ detailInflight.set(id, request);
+ pending = request;
+ }
+ const shared = pending;
+
+ (async () => {
+ try {
+ const row = await shared;
+ if (!cancelled) {
+ setData({ record: row, form: toForm(row), loading: false, error: null, saving: false, showErrors: false, notice: null });
+ }
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load the account.';
+ setData({ record: null, form: toForm(null), loading: false, error: message, saving: false, showErrors: false, notice: null });
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and the account id only: dataApi is a new reference on every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, accountId]);
+
+ const original = useMemo(() => toForm(record), [record]);
+ const changed = useMemo(() => changedFields(original, form), [original, form]);
+ const errors = useMemo(() => validate(form), [form]);
+
+ const setField = (field: EditableField, value: string) => {
+ setData((prev) => ({ ...prev, form: { ...prev.form, [field]: value }, notice: null }));
+ };
+
+ const discard = () => {
+ setData((prev) => ({ ...prev, form: toForm(prev.record), showErrors: false, notice: null }));
+ };
+
+ const handleSave = async () => {
+ if (!accountId || !record || saving || changed.length === 0) return;
+ if (Object.keys(errors).length > 0) {
+ setData((prev) => ({ ...prev, showErrors: true, notice: { intent: 'error', text: 'Fix the highlighted fields before saving.' } }));
+ return;
+ }
+ const payload = toPayload(form, changed);
+ setData((prev) => ({ ...prev, saving: true, notice: null }));
+ try {
+ await dataApi.updateRow('account', accountId, payload as unknown as WritableTableRow<account>);
+ const merged = { ...record, ...payload } as unknown as AccountRow;
+ detailCache.set(accountId, merged);
+ delete winAny[LIST_CACHE_KEY];
+ delete winAny[LIST_INFLIGHT_KEY];
+ setData({
+ record: merged,
+ form: toForm(merged),
+ loading: false,
+ error: null,
+ saving: false,
+ showErrors: false,
+ notice: { intent: 'success', text: 'Account saved.' },
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Unable to save the account.';
+ setData((prev) => ({ ...prev, saving: false, notice: { intent: 'error', text: message } }));
+ }
+ };
+
+ const renderField = (field: EditableField) => {
+ const message = showErrors ? errors[field] : undefined;
+ return (
+ <Field
+ key={field}
+ label={FIELD_LABELS[field]}
+ required={field === 'name'}
+ validationState={message ? 'error' : 'none'}
+ validationMessage={message}
+ >
+ <Input
+ type={field === 'emailaddress1' ? 'email' : field === 'websiteurl' ? 'url' : 'text'}
+ value={form[field]}
+ onChange={(_, data) => setField(field, data.value)}
+ disabled={saving}
+ />
+ </Field>
+ );
+ };
+
+ if (!accountId) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Text>No account selected. Open this page from the Accounts list.</Text>
+ <Button icon={<ArrowLeftRegular />} onClick={openAccountsList}>
+ Back to accounts
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading account…" />
+ </div>
+ </div>
+ );
+ }
+
+ if (!record) {
+ return (
+ <div className={styles.root}>
+ <MessageBar intent="error">
+ <MessageBarBody>{error ?? 'The account could not be found.'}</MessageBarBody>
+ </MessageBar>
+ <div>
+ <Button icon={<ArrowLeftRegular />} onClick={openAccountsList}>
+ Back to accounts
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ const modifiedOn = fieldText(record, '[email protected]');
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <Button appearance="subtle" icon={<ArrowLeftRegular />} onClick={openAccountsList} aria-label="Back to accounts">
+ Back
+ </Button>
+ <div className={styles.titleBlock}>
+ <Text as="h1" size={700} weight="semibold" className={styles.title}>
+ Edit {original.name || 'account'}
+ </Text>
+ {modifiedOn && (
+ <Text size={200} className={styles.meta}>
+ Last modified {modifiedOn}
+ </Text>
+ )}
+ </div>
+ </header>
+
+ {notice && (
+ <MessageBar intent={notice.intent}>
+ <MessageBarBody>{notice.text}</MessageBarBody>
+ </MessageBar>
+ )}
+ {!notice && changed.length > 0 && (
+ <MessageBar intent="warning">
+ <MessageBarBody>You have unsaved changes.</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <form
+ aria-label="Edit account"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleSave();
+ }}
+ >
+ <Card className={styles.card}>
+ <Text as="h2" size={400} className={styles.sectionTitle}>
+ Account details
+ </Text>
+ <div className={styles.fieldGrid}>{DETAILS_FIELDS.map(renderField)}</div>
+ <Divider />
+ <Text as="h2" size={400} className={styles.sectionTitle}>
+ Address
+ </Text>
+ <div className={styles.fieldGrid}>{ADDRESS_FIELDS.map(renderField)}</div>
+ <Divider />
+ <Field label={FIELD_LABELS.description}>
+ <Textarea
+ value={form.description}
+ onChange={(_, data) => setField('description', data.value)}
+ resize="vertical"
+ disabled={saving}
+ />
+ </Field>
+ <div className={styles.actions}>
+ <Button type="submit" appearance="primary" icon={saving ? <Spinner size="tiny" /> : <SaveRegular />} disabled={saving || changed.length === 0}>
+ {saving ? 'Saving' : 'Save'}
+ </Button>
+ <Button type="button" icon={<ArrowUndoRegular />} onClick={discard} disabled={saving || changed.length === 0}>
+ Discard changes
+ </Button>
+ </div>
+ </Card>
+ </form>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-list.tsx b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-list.tsx
new file mode 100644
index 000000000..7ca464bd9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/before/account-list.tsx
@@ -0,0 +1,370 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ GeneratedComponentProps,
+ account,
+ ReadableTableRow,
+ QueryTableOptions,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ SearchBox,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import type { TableColumnSizingOptions } from '@fluentui/react-components';
+import { ArrowClockwiseRegular, EditRegular, SearchRegular } from '@fluentui/react-icons';
+
+type AccountRow = ReadableTableRow<account>;
+type LoadedAccounts = { rows: AccountRow[]; truncated: boolean };
+type LoadState = LoadedAccounts & { loading: boolean; error: string | null };
+type XrmNavigation = { Navigation?: { navigateTo?: (input: Record<string, unknown>) => Promise<unknown> } };
+
+// Window-scoped list cache + in-flight promise (references/data-caching.md, Pattern 1). The Edit
+// Account page evicts these two keys after a successful save so this list refetches on return.
+const CACHE_KEY = '__ppAccountList_accountCache';
+const INFLIGHT_KEY = '__ppAccountList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const PAGE_SIZE = 250;
+// "All accounts" is read page by page through loadMoreRows; the cap keeps a very large table from
+// holding thousands of rows in window memory, and the footer says when it was reached.
+const MAX_ROWS = 5000;
+
+const LIST_QUERY: QueryTableOptions<account> = {
+ select: ['accountid', 'name', 'accountnumber', 'address1_city', 'telephone1', 'emailaddress1'],
+ orderBy: 'name asc',
+ pageSize: PAGE_SIZE,
+};
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ contain: 'layout',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ height: '100%',
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: tokens.spacingHorizontalXL,
+ overflow: 'hidden',
+ color: tokens.colorNeutralForeground1,
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ headerActions: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ flexGrow: 1,
+ justifyContent: 'flex-end',
+ '@media (max-width: 640px)': {
+ justifyContent: 'stretch',
+ },
+ },
+ search: {
+ minWidth: '220px',
+ maxWidth: '360px',
+ flexGrow: 1,
+ },
+ gridArea: {
+ flexGrow: 1,
+ minHeight: 0,
+ overflow: 'auto',
+ },
+ truncate: {
+ display: 'block',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ cellLayout: {
+ minWidth: 0,
+ overflow: 'hidden',
+ },
+ centered: {
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ padding: tokens.spacingVerticalXXL,
+ color: tokens.colorNeutralForeground2,
+ },
+ footer: {
+ color: tokens.colorNeutralForeground2,
+ },
+});
+
+function textOf(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function compareText(a: string, b: string): number {
+ return a.localeCompare(b, undefined, { sensitivity: 'base' });
+}
+
+function matchesSearch(row: AccountRow, term: string): boolean {
+ if (!term) return true;
+ return [row.name, row.accountnumber, row.address1_city, row.emailaddress1, row.telephone1]
+ .map(textOf)
+ .some((value) => value.toLowerCase().includes(term));
+}
+
+function readCache(): LoadedAccounts | undefined {
+ return winAny[CACHE_KEY] as LoadedAccounts | undefined;
+}
+
+function openEditPage(accountId: string) {
+ const xrm = (window as unknown as { Xrm?: XrmNavigation }).Xrm;
+ // The sibling Edit Account page receives the id in `data` (never recordId) and reads it as
+ // pageInput.data.accountId. Phase 6.5 replaces the placeholder with the deployed page id.
+ void xrm?.Navigation?.navigateTo?.({
+ pageType: "generative",
+ pageId: "PAGEREF_account-edit",
+ data: { accountId },
+ });
+}
+
+function TextCell(props: { value: string; className: string; layoutClassName: string }) {
+ return (
+ <TableCellLayout className={props.layoutClassName}>
+ <span className={props.className} title={props.value}>
+ {props.value || '—'}
+ </span>
+ </TableCellLayout>
+ );
+}
+
+const COLUMN_SIZING: TableColumnSizingOptions = {
+ name: { defaultWidth: 260, minWidth: 180 },
+ accountnumber: { defaultWidth: 140, minWidth: 110 },
+ city: { defaultWidth: 160, minWidth: 120 },
+ phone: { defaultWidth: 160, minWidth: 120 },
+ email: { defaultWidth: 240, minWidth: 160 },
+ actions: { defaultWidth: 100, minWidth: 90 },
+};
+
+function buildColumns(truncate: string, cellLayout: string) {
+ return [
+ createTableColumn<AccountRow>({
+ columnId: 'name',
+ compare: (a, b) => compareText(textOf(a.name), textOf(b.name)),
+ renderHeaderCell: () => 'Account name',
+ renderCell: (item) => <TextCell value={textOf(item.name)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'accountnumber',
+ compare: (a, b) => compareText(textOf(a.accountnumber), textOf(b.accountnumber)),
+ renderHeaderCell: () => 'Account number',
+ renderCell: (item) => <TextCell value={textOf(item.accountnumber)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'city',
+ compare: (a, b) => compareText(textOf(a.address1_city), textOf(b.address1_city)),
+ renderHeaderCell: () => 'City',
+ renderCell: (item) => <TextCell value={textOf(item.address1_city)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'phone',
+ compare: (a, b) => compareText(textOf(a.telephone1), textOf(b.telephone1)),
+ renderHeaderCell: () => 'Main phone',
+ renderCell: (item) => <TextCell value={textOf(item.telephone1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'email',
+ compare: (a, b) => compareText(textOf(a.emailaddress1), textOf(b.emailaddress1)),
+ renderHeaderCell: () => 'Email',
+ renderCell: (item) => <TextCell value={textOf(item.emailaddress1)} className={truncate} layoutClassName={cellLayout} />,
+ }),
+ createTableColumn<AccountRow>({
+ columnId: 'actions',
+ renderHeaderCell: () => 'Actions',
+ renderCell: (item) => (
+ <TableCellLayout>
+ <Button
+ appearance="subtle"
+ size="small"
+ icon={<EditRegular />}
+ onClick={() => openEditPage(item.accountid)}
+ aria-label={`Edit ${textOf(item.name) || 'account'}`}
+ >
+ Edit
+ </Button>
+ </TableCellLayout>
+ ),
+ }),
+ ];
+}
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // the list page takes no input; destructured per the component contract
+ const styles = useStyles();
+ const dataReady = !!dataApi;
+
+ const [{ rows, truncated, loading, error }, setData] = useState<LoadState>(() => {
+ const cached = readCache();
+ return cached
+ ? { rows: cached.rows, truncated: cached.truncated, loading: false, error: null }
+ : { rows: [], truncated: false, loading: true, error: null };
+ });
+ const [reloadKey, setReloadKey] = useState(0);
+ const [search, setSearch] = useState('');
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = readCache();
+ if (cached !== undefined) {
+ if (cached.rows !== rows) setData({ rows: cached.rows, truncated: cached.truncated, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // The host double-mounts the page on open; the second mount awaits this shared promise.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<LoadedAccounts> | undefined;
+ if (!inflight) {
+ const pending: Promise<LoadedAccounts> = (async () => {
+ let page = await dataApi.queryTable('account', LIST_QUERY);
+ const all: AccountRow[] = [...page.rows];
+ while (page.hasMoreRows && page.loadMoreRows && all.length < MAX_ROWS) {
+ page = await page.loadMoreRows();
+ all.push(...page.rows);
+ }
+ const loaded: LoadedAccounts = { rows: all, truncated: page.hasMoreRows };
+ winAny[CACHE_KEY] = loaded;
+ return loaded;
+ })().finally(() => {
+ if (winAny[INFLIGHT_KEY] === pending) delete winAny[INFLIGHT_KEY];
+ });
+ winAny[INFLIGHT_KEY] = pending;
+ inflight = pending;
+ }
+ const shared = inflight;
+
+ (async () => {
+ try {
+ const loaded = await shared;
+ if (!cancelled) setData({ rows: loaded.rows, truncated: loaded.truncated, loading: false, error: null });
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load accounts.';
+ setData({ rows: [], truncated: false, loading: false, error: message });
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and the manual reload key only: dataApi is a new reference on every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ const columns = useMemo(() => buildColumns(styles.truncate, styles.cellLayout), [styles.truncate, styles.cellLayout]);
+ const visibleRows = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ return rows.filter((row) => matchesSearch(row, term));
+ }, [rows, search]);
+
+ const refresh = () => {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ rows: [], truncated: false, loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ };
+
+ if (loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading accounts…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <Text as="h1" size={700} weight="semibold">
+ Accounts
+ </Text>
+ <div className={styles.headerActions}>
+ <SearchBox
+ className={styles.search}
+ placeholder="Search name, number, city, email or phone"
+ value={search}
+ onChange={(_, data) => setSearch(data.value ?? '')}
+ contentBefore={<SearchRegular />}
+ aria-label="Search accounts"
+ />
+ <Button icon={<ArrowClockwiseRegular />} onClick={refresh} aria-label="Refresh accounts">
+ Refresh
+ </Button>
+ </div>
+ </header>
+
+ {error && (
+ <MessageBar intent="error">
+ <MessageBarBody>{error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <div className={styles.gridArea}>
+ {visibleRows.length === 0 ? (
+ <div className={styles.centered} role="status">
+ <Text>{rows.length === 0 ? 'No accounts found.' : 'No accounts match your search.'}</Text>
+ </div>
+ ) : (
+ <DataGrid
+ items={visibleRows}
+ columns={columns}
+ getRowId={(item) => item.accountid}
+ sortable
+ defaultSortState={{ sortColumn: 'name', sortDirection: 'ascending' }}
+ resizableColumns
+ columnSizingOptions={COLUMN_SIZING}
+ focusMode="composite"
+ aria-label="Accounts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<AccountRow>>
+ {({ item, rowId }) => (
+ <DataGridRow<AccountRow> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+
+ <Text size={200} className={styles.footer} role="status">
+ Showing {visibleRows.length} of {rows.length} accounts
+ {truncated ? ` (only the first ${MAX_ROWS} accounts by name are loaded)` : ''}
+ </Text>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixture.json b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixture.json
new file mode 100644
index 000000000..8f4146d9d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixture.json
@@ -0,0 +1,40 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed attended two-page trace, not an agent capture. The first approved plan gives both pages the file name account.tsx; the Phase 5a page-file gate (check-page-files.js) refuses it with a collision before any builder is stamped or dispatched; the orchestrator re-plans through genpage-planner, the renamed files (account-list.tsx, account-edit.tsx) are re-approved, the earlier plan is quarantined and the rewritten genpage-plan.md is provenance-verified; then two page builders run in parallel, both pages deploy, and Phase 6.5 resolves their mutual navigation. before/ holds each page as authored and first uploaded; the top-level pages are the Phase 6.5 resolved files. .genpage-provenance/ holds the quarantined colliding plan.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5a: Validate the plan before dispatch",
+ "plugins/model-apps/scripts/check-page-files.js collision refusal",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan, Steps 5-7 (re-presentation, approval writeback, plan provenance)",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5c: Multi-page: invoke page-builders in parallel",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6.5: Navigation Fix-Up",
+ "plugins/model-apps/references/plan-schema.md ## Pages file name rules",
+ "plugins/model-apps/references/rules.md Generative Page Navigation"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": [
+ ".genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md",
+ ".approved-genpage-plan.md",
+ "before/account-list.tsx",
+ "before/account-edit.tsx",
+ "prompt.txt",
+ "agent-message.txt",
+ "fixup-prompt.txt",
+ "fixup-message.txt",
+ "names/account-list.txt",
+ "names/account-edit.txt"
+ ],
+ "navigation": {
+ "pageMap": {
+ "account-list": "14141414-1414-4414-8414-141414141401",
+ "account-edit": "14141414-1414-4414-8414-141414141402"
+ },
+ "sources": [
+ { "key": "account-list", "file": "account-list.tsx", "before": "before/account-list.tsx" },
+ { "key": "account-edit", "file": "account-edit.tsx", "before": "before/account-edit.tsx" }
+ ],
+ "expectedTargets": { "account-list": ["account-edit"], "account-edit": ["account-list"] }
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-message.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-message.txt
new file mode 100644
index 000000000..7717ea116
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-message.txt
@@ -0,0 +1 @@
+Replaced PAGEREF_account-list and PAGEREF_account-edit tokens with actual page IDs returned by Phase 6
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-prompt.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-prompt.txt
new file mode 100644
index 000000000..05ec3f3c1
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/fixup-prompt.txt
@@ -0,0 +1 @@
+Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/genpage-plan.md b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/genpage-plan.md
new file mode 100644
index 000000000..abe0df2e8
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/genpage-plan.md
@@ -0,0 +1,71 @@
+# Genpage Plan
+
+## User Requirements
+Build two pages for tracking Account records — one for listing all accounts and one for editing a single account.
+
+## Working Directory
+D:/work/account-tracking
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Sales (11111111-1111-4111-8111-111111111111)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Accounts | account-list.tsx | List of all Account records with search, sortable columns and an Edit action per row | account |
+| Edit Account | account-edit.tsx | Edit form for a single Account record opened from the Accounts list | 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: Fluent UI V9 defaults with theme tokens; list page fills the host container with a scrolling grid area; edit page uses a card form, two columns on wide screens and one column on narrow screens.
+- Features: list shows all accounts (paged with loadMoreRows, capped at 5,000 rows), client-side search and sortable columns; each row has an Edit action that opens the Edit Account page for that row; the edit page saves only changed fields, can discard changes and navigates back to the list.
+- Accessibility: labelled search box and form fields, required marker and validation message on Account name, keyboard-navigable DataGrid, Edit buttons carry the account name in their aria-label.
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Accounts | 9-list-with-caching.tsx | Dataverse list with SearchBox, sibling-page PAGEREF navigation, window cache and in-flight de-dupe |
+| Edit Account | 10-detail-with-pageinput.tsx | Page reached by navigateTo that reads its input and caches per record |
+| Edit Account | 3-account-crud-dataverse.tsx | Account updateRow with verified column names |
+
+## Per-Page Specifications
+
+### Accounts
+- **File:** account-list.tsx
+- **Purpose:** List of all Account records with search, sortable columns and an Edit action per row
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** All accounts loaded page by page (queryTable pageSize 250, then loadMoreRows until hasMoreRows is false or 5,000 rows); SearchBox filters by name, account number, city, email and main phone; sortable columns (default account name ascending); Refresh button; footer "Showing X of Y accounts".
+- **Components:** SearchBox, Button, DataGrid (DataGridHeader, DataGridHeaderCell, DataGridBody, DataGridRow, DataGridCell), TableCellLayout, createTableColumn, MessageBar, Spinner, Text; icons SearchRegular, EditRegular, ArrowClockwiseRegular.
+- **Layout:** Flex-column root filling the host container; header with title opposite the search box and Refresh; grid area flexes and scrolls; columnSizingOptions for every column plus resizableColumns.
+- **Data Binding:** dataApi.queryTable("account") selecting accountid, name, accountnumber, address1_city, telephone1, emailaddress1; orderBy name asc; read result.rows; window keys `__ppAccountList_accountCache` and `__ppAccountList_accountInflight`; single batched setData; readiness-only dependencies plus a reload key.
+- **Interactions:** Edit button on each row calls Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_account-edit", data: { accountId } }); Refresh evicts both window keys and refetches; column headers sort.
+
+### Edit Account
+- **File:** account-edit.tsx
+- **Purpose:** Edit form for a single Account record opened from the Accounts list
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** Reads the account id from pageInput.data.accountId (GUID string; braces tolerated); retrieves the record and shows an edit form for name (required), account number, main phone, email (format-checked), website, street, city, state/province, ZIP/postal code, country/region and description; Save sends only changed fields (emptied fields clear the column); Discard changes restores the loaded values; unsaved-changes warning; success and error MessageBars; empty state with a Back button when no account id was passed.
+- **Components:** Card, Field, Input, Textarea, Button, Divider, MessageBar, Spinner, Text; icons ArrowLeftRegular, SaveRegular, ArrowUndoRegular.
+- **Layout:** Scrolling flex-column root; header with Back button, title and last-modified date; card with Account details, Address and Description sections; field grid collapses to one column under 720px.
+- **Data Binding:** dataApi.retrieveRow("account", { id, select: accountid, name, accountnumber, telephone1, emailaddress1, websiteurl, address1_line1, address1_city, address1_stateorprovince, address1_postalcode, address1_country, description, modifiedon }); modifiedon shown from its FormattedValue annotation; per-record Map cache and in-flight Map on window (`__ppAccountEdit_accountCache`, `__ppAccountEdit_accountInflight`); dataApi.updateRow("account", id, changedFields) in try/catch; after a successful save update the record cache and delete `__ppAccountList_accountCache` and `__ppAccountList_accountInflight` so the list refetches; one state object, one setData per outcome.
+- **Interactions:** Back buttons call Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_account-list" }); Save submits the form; Discard changes resets the form.
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-edit.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-edit.txt
new file mode 100644
index 000000000..4ea7ae51d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-edit.txt
@@ -0,0 +1 @@
+Edit Account
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-list.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-list.txt
new file mode 100644
index 000000000..29b855268
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/names/account-list.txt
@@ -0,0 +1 @@
+Accounts
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/prompt.txt b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/prompt.txt
new file mode 100644
index 000000000..81408ffee
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/prompt.txt
@@ -0,0 +1 @@
+Build two pages for tracking Account records — one for listing all accounts and one for editing a single account.
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/tool-results.json b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/tool-results.json
new file mode 100644
index 000000000..9a1300c8c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/tool-results.json
@@ -0,0 +1,97 @@
+[
+ {
+ "id": "interaction-mode",
+ "command": "node scripts\\resolve-interaction-mode.js",
+ "result": { "ok": true, "interactive": true, "reason": "default (attended)" }
+ },
+ {
+ "id": "plan-prepare-1",
+ "command": "node scripts\\genpage-plan-provenance.js prepare --plan genpage-plan.md",
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\account-tracking\\genpage-plan.md", "quarantinedPath": null }
+ },
+ {
+ "id": "plan-verify-1",
+ "command": "node scripts\\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md",
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\account-tracking\\genpage-plan.md", "kind": "create", "targets": ["account.tsx", "account.tsx"], "writtenHash": "e0fbb49f3c98f30d484fa069c3ebe304ec6eb093112131d3eca05d662b4b9ea8" }
+ },
+ {
+ "id": "page-files-1",
+ "command": "node scripts\\check-page-files.js --plan genpage-plan.md",
+ "artifact": ".genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md",
+ "result": { "ok": false, "workingDir": "D:\\work\\account-tracking", "files": ["account.tsx", "account.tsx"], "problems": [{ "file": "account.tsx", "code": "collision", "message": "\"account.tsx\" and \"account.tsx\" collide on a case-insensitive filesystem" }] },
+ "exitCode": 3
+ },
+ {
+ "id": "plan-prepare-2",
+ "command": "node scripts\\genpage-plan-provenance.js prepare --plan genpage-plan.md",
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\account-tracking\\genpage-plan.md", "quarantinedPath": "D:\\work\\account-tracking\\.genpage-provenance\\genpage-plan.stale-e0fbb49f3c98.md", "staleHash": "e0fbb49f3c98f30d484fa069c3ebe304ec6eb093112131d3eca05d662b4b9ea8" }
+ },
+ {
+ "id": "plan-verify-2",
+ "command": "node scripts\\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md",
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\account-tracking\\genpage-plan.md", "kind": "create", "targets": ["account-edit.tsx", "account-list.tsx"], "writtenHash": "5a6d56872fd01d5f200958bcbe4e74ca207ce3a4058e3c7caafc286f1d8effcf" }
+ },
+ {
+ "id": "page-files-2",
+ "command": "node scripts\\check-page-files.js --plan genpage-plan.md",
+ "artifact": "genpage-plan.md",
+ "result": { "ok": true, "workingDir": "D:\\work\\account-tracking", "files": ["account-list.tsx", "account-edit.tsx"], "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "stamp-list",
+ "command": "node scripts\\genpage-worker-output.js --stamp --file account-list.tsx",
+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\account-tracking\\account-list.tsx", "existed": false }
+ },
+ {
+ "id": "stamp-edit",
+ "command": "node scripts\\genpage-worker-output.js --stamp --file account-edit.tsx",
+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\account-tracking\\account-edit.tsx", "existed": false }
+ },
+ {
+ "id": "builder-list",
+ "command": "Task genpage-page-builder: Accounts, target file account-list.tsx",
+ "artifact": "before/account-list.tsx",
+ "result": "Page: Accounts\nFile: D:\\work\\account-tracking\\account-list.tsx\nStatus: Written"
+ },
+ {
+ "id": "builder-edit",
+ "command": "Task genpage-page-builder: Edit Account, target file account-edit.tsx",
+ "artifact": "before/account-edit.tsx",
+ "result": "Page: Edit Account\nFile: D:\\work\\account-tracking\\account-edit.tsx\nStatus: Written"
+ },
+ {
+ "id": "gate-list",
+ "command": "node scripts\\genpage-worker-output.js --file account-list.tsx",
+ "artifact": "before/account-list.tsx",
+ "result": { "ok": true, "filePath": "D:\\work\\account-tracking\\account-list.tsx", "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "gate-edit",
+ "command": "node scripts\\genpage-worker-output.js --file account-edit.tsx",
+ "artifact": "before/account-edit.tsx",
+ "result": { "ok": true, "filePath": "D:\\work\\account-tracking\\account-edit.tsx", "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "list-create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\\account-list.tsx --name-file names\\account-list.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "14141414-1414-4414-8414-141414141401", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "edit-create",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\\account-edit.tsx --name-file names\\account-edit.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap",
+ "result": { "ok": true, "pageId": "14141414-1414-4414-8414-141414141402", "appId": "11111111-1111-4111-8111-111111111111", "updated": false }
+ },
+ {
+ "id": "list-fixup",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 14141414-1414-4414-8414-141414141401 --code-file account-list.tsx --data-sources account --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model claude-sonnet-4.5",
+ "result": { "ok": true, "pageId": "14141414-1414-4414-8414-141414141401", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ },
+ {
+ "id": "edit-fixup",
+ "command": "node scripts\\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 14141414-1414-4414-8414-141414141402 --code-file account-edit.tsx --data-sources account --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model claude-sonnet-4.5",
+ "result": { "ok": true, "pageId": "14141414-1414-4414-8414-141414141402", "appId": "11111111-1111-4111-8111-111111111111", "updated": true }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/workflow-log.md b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/workflow-log.md
new file mode 100644
index 000000000..c4ddcf004
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/14-account-list-edit-collision/workflow-log.md
@@ -0,0 +1,157 @@
+# Workflow Log — Eval 14: Account list + edit pages, page-file collision caught in Phase 5a
+
+Synthetic trace constructed from the current SKILL.md phases, not a captured agent run.
+Commands run from the working directory; `scripts\` is `${PLUGIN_ROOT}\scripts`. `before\` in the
+Phase 6 commands is this fixture's snapshot of each page as authored and first uploaded (the
+working-directory file before Phase 6.5 rewrote it in place).
+
+## Phase 0 — Working directory setup
+- `node scripts\check-version.js` → no output (plugin up to date)
+- Working directory created: `D:\work\account-tracking` (kebab-case from "tracking Account records")
+
+## Phase 0.5 — Local-dev manifest
+- `node scripts\generate-page-manifest.js 'D:\work\account-tracking' 'account-tracking'` → exit 0; wrote package.json and genpage.d.ts (no --features)
+
+## Phase 1 — Plan (interactive steps in the main loop; discovery via genpage-planner)
+
+### Interaction mode
+- `node scripts\resolve-interaction-mode.js` → {"ok":true,"interactive":true,"reason":"default (attended)"} — attended run
+
+### Prereq checks (run separately, not chained with &&)
+- `node --version` → v20.20.2
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
+
+### Auth check
+- `pac auth list` → one profile, active (*): [email protected], https://contoso.crm.dynamics.com/
+- Active environment reported to user: "Working with environment: Contoso (https://contoso.crm.dynamics.com)"
+
+### Questions
+- AskUserQuestion: Create new page(s) or edit an existing one? → Create new page(s)
+- `pac model list-languages` → 1033 English en-US (RTL: No) only → no localization
+- Description question skipped: the /genpage arguments already describe the pages
+- Data source question skipped: the description names Account records → Dataverse entity: account
+- AskUserQuestion: Any specific requirements? → Two pages — list and edit
+
+### Entity detection
+- `pac model list-tables --search 'account'` → rows account, accountleads, accountlevelmonitoring; exact logical-name match `account` → exists
+- No entity creation required
+
+### App detection
+- `pac model list` → 2 apps (Contoso Sales, Contoso Service)
+- AskUserQuestion: Which model-driven app should the pages be added to? → Contoso Sales (11111111-1111-4111-8111-111111111111) — existing app selected
+
+### Solution selection
+- Code-only flow (existing entity, existing app) → solution selection question SKIPPED
+- Defaults recorded for the plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Connector / Custom API contracts
+- First planner invocation received `No connector bindings.` and `No custom API bindings.`; the planner returned no connector_discovery_required or custom_api_discovery_required action
+
+### Plan presentation 1 — approved (Pages table has 2 pages)
+- Task genpage-planner (discovery + plan) returned a 2-page plan
+- EnterPlanMode called with the plan; Pages (2 total):
+ - Accounts | account.tsx | List of all Account records with search, sortable columns and an Edit action per row | account
+ - Edit Account | account.tsx | Edit form for a single Account record opened from the Accounts list | account
+- ExitPlanMode called → approved
+- `node scripts\genpage-plan-provenance.js prepare --plan genpage-plan.md`
+ - Result: {"ok":true,"action":"prepare","quarantinedPath":null} (no earlier plan)
+- Approved plan body saved verbatim to `.approved-genpage-plan.md`
+- Task genpage-planner re-invoked with outcome approved plus the plan body and all discovery → wrote genpage-plan.md
+- `node scripts\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md`
+ - Result: ok:true, kind create, targets ["account.tsx","account.tsx"] — the written plan names exactly what was approved, so provenance passes; it does not judge whether the names are usable
+ - writtenHash: e0fbb49f3c98f30d484fa069c3ebe304ec6eb093112131d3eca05d662b4b9ea8
+
+## Phase 2 — Entity creation
+- SKIPPED: plan says "No entity creation required — all entities already exist."
+- check-auth.js not run (no entity work); entity builder not dispatched
+
+## Phase 3 — App creation/selection
+- SKIPPED: existing app Contoso Sales (11111111-1111-4111-8111-111111111111)
+
+## Phase 4 — RuntimeTypes
+- `pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-tracking/RuntimeTypes.ts'` → RuntimeTypes.ts written
+- Read RuntimeTypes.ts: account columns accountid, name, accountnumber, telephone1, emailaddress1, websiteurl, address1_line1, address1_city, address1_stateorprovince, address1_postalcode, address1_country, description, modifiedon verified
+
+## Phase 4.5 — Connector bindings
+- Plan says `No connector bindings.` → Connectors: none; no connectors.json, no --connectors
+
+## Phase 4.6 — Custom API bindings
+- `node scripts\lib\feature-flags.js custom-api` → disabled; plan body is exactly `No custom API bindings.` → continue with no actions.json
+
+## Phase 4.7 — Page telemetry
+- `node scripts\lib\feature-flags.js custom-telemetry` → disabled → Telemetry: disabled
+
+## Phase 5a — Plan validation: duplicate file name detected
+- Read genpage-plan.md ## Pages: 2 rows (Accounts, Edit Account); both have a ### subsection in ## Per-Page Specifications
+- `node scripts\check-page-files.js --plan genpage-plan.md`
+ - Result: exit 3, {"ok":false,"files":["account.tsx","account.tsx"],"problems":[{"file":"account.tsx","code":"collision","message":"\"account.tsx\" and \"account.tsx\" collide on a case-insensitive filesystem"}]}
+- Collision detected: both pages target the same file, so two parallel builders would overwrite each other (last writer wins) and the PAGEREF_ token for each page would be ambiguous
+- Dispatch HALTED: no target stamped, no page builder dispatched
+- Per SKILL.md 5a the orchestrator does not rename files in place (a renamed file is a page the user did not approve, and provenance compares page files); it re-plans instead
+
+### Re-plan with unique file names
+- Task genpage-planner re-invoked with the check-page-files problem, the approved plan body and all discovery, asking for unique page file names and nothing else changed
+- Planner returned the revised plan: Accounts → account-list.tsx, Edit Account → account-edit.tsx; per-page File values, Interactions and PAGEREF tokens (PAGEREF_account-edit, PAGEREF_account-list) updated to match; requirements, data binding and design unchanged
+- EnterPlanMode called with the revised plan (unique file names account-list.tsx / account-edit.tsx)
+- ExitPlanMode called → approved
+- `node scripts\genpage-plan-provenance.js prepare --plan genpage-plan.md`
+ - Result: ok:true; the colliding plan was quarantined to `.genpage-provenance\genpage-plan.stale-e0fbb49f3c98.md` (staleHash e0fbb49f3c98f30d484fa069c3ebe304ec6eb093112131d3eca05d662b4b9ea8)
+- Revised approved plan body saved verbatim to `.approved-genpage-plan.md` (replacing the earlier sidecar)
+- Task genpage-planner re-invoked with outcome approved plus the revised plan body and all discovery → rewrote genpage-plan.md
+- `node scripts\genpage-plan-provenance.js verify --plan genpage-plan.md --approved @.approved-genpage-plan.md`
+ - Result: ok:true, kind create, targets account-edit + account-list (unique)
+ - writtenHash: 5a6d56872fd01d5f200958bcbe4e74ca207ce3a4058e3c7caafc286f1d8effcf
+- `node scripts\check-page-files.js --plan genpage-plan.md`
+ - Result: exit 0, ok:true, files account-list + account-edit, no problems — genpage-plan.md now carries unique file names BEFORE any builder is dispatched
+
+## Phase 5c — Multi-page: two page builders in parallel
+- Plan has 2 pages → single-page fast path not taken
+- Data mode: dataverse; RuntimeTypes: D:\work\account-tracking\RuntimeTypes.ts; Connectors: none; Telemetry: disabled
+- `node scripts\genpage-worker-output.js --stamp --file account-list.tsx`
+ - Result: {"ok":true,"action":"stamp","existed":false}
+- `node scripts\genpage-worker-output.js --stamp --file account-edit.tsx`
+ - Result: {"ok":true,"action":"stamp","existed":false}
+- Two page builders dispatched via the Task tool in a SINGLE message (parallel), each with a distinct target file:
+- Task genpage-page-builder: Accounts, target file account-list.tsx
+- Task genpage-page-builder: Edit Account, target file account-edit.tsx
+- Both builders returned Status: Written; each read only its own ### subsection of the same genpage-plan.md and the shared RuntimeTypes.ts
+- Builder samples read: samples/9-list-with-caching.tsx (Accounts); samples/10-detail-with-pageinput.tsx and samples/3-account-crud-dataverse.tsx (Edit Account)
+- Both target files exist after the builders return; neither overwrote the other
+- `node scripts\genpage-worker-output.js --file account-list.tsx`
+ - Result: {"ok":true,"problems":[]}
+- `node scripts\genpage-worker-output.js --file account-edit.tsx`
+ - Result: {"ok":true,"problems":[]}
+- Grep `['"]?borderWidth['"]?\s*:` on both pages → no matches
+- Icon verification against references/verified-icons.txt (one Grep per name): SearchRegular, EditRegular, ArrowClockwiseRegular (Accounts); ArrowLeftRegular, SaveRegular, ArrowUndoRegular (Edit Account) — all present
+- Cross-page navigation authored as quoted placeholders: Accounts → "PAGEREF_account-edit" (data: { accountId }); Edit Account → "PAGEREF_account-list"
+
+## Phase 6 — Deploy
+- Cleared prompt.txt, agent-message.txt and the page-name files (none was a link or folder), then wrote them with the file tool
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\account-list.tsx --name-file names\account-list.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap`
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --code-file before\account-edit.tsx --name-file names\account-edit.txt --data-sources account --prompt-file prompt.txt --agent-message-file agent-message.txt --model claude-sonnet-4.5 --add-to-sitemap`
+- Prompt scope: full page description from plan's `## User Requirements` (create)
+- Result: account-list → page-id 14141414-1414-4414-8414-141414141401; account-edit → page-id 14141414-1414-4414-8414-141414141402; both success, each deployed under its own distinct file name
+
+## Phase 6.5 — Navigation fix-up
+- Filename-to-page-id map from the two Phase 6 results (keys sorted by length, descending): account-list → 14141414-1414-4414-8414-141414141401, account-edit → 14141414-1414-4414-8414-141414141402
+- Replaced the quoted pageId placeholder in each page; no placeholder was left unresolved
+- Both pages changed, so both re-upload with --page-id, no --add-to-sitemap, and the delta prompt
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 14141414-1414-4414-8414-141414141401 --code-file account-list.tsx --data-sources account --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model claude-sonnet-4.5`
+- Command: `node scripts\genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 14141414-1414-4414-8414-141414141402 --code-file account-edit.tsx --data-sources account --prompt-file fixup-prompt.txt --agent-message-file fixup-message.txt --model claude-sonnet-4.5`
+- Prompt scope: Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)
+- Result: both updates success with their own page ids
+
+## 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 | account-list.tsx | account | Deployed |
+| Edit Account | account-edit.tsx | account | Deployed |
+
+- App: Contoso Sales (11111111-1111-4111-8111-111111111111)
+- Entities created: none
+- Page-file collision: account.tsx assigned to both pages; refused by check-page-files.js in Phase 5a before dispatch; re-planned and re-approved as account-list.tsx / account-edit.tsx
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/account-list.tsx b/evals/model-apps/genpage/fixtures/16-account-list/account-list.tsx
new file mode 100644
index 000000000..dad0b11c1
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/account-list.tsx
@@ -0,0 +1,328 @@
+import { useEffect, useState } from 'react';
+import type {
+ TableRow,
+ ReadableTableRow,
+ GeneratedComponentProps,
+} 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 { BuildingRegular } from '@fluentui/react-icons';
+
+// Account List — a simple, sortable list of Account records.
+// Columns are the verified account columns from RuntimeTypes.ts. The primary contact
+// is a lookup, so the FK column is selected and its display name read from the
+// FormattedValue annotation (DataAPI rule 12).
+
+type AccountRow = TableRow<{
+ readonly accountid: string;
+ name?: string;
+ accountnumber?: string;
+ telephone1?: string;
+ address1_city?: string;
+ readonly _primarycontactid_value?: string;
+}>;
+
+type ReadableAccount = ReadableTableRow<AccountRow>;
+
+type AccountListState = {
+ 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 = '__ppAccountList_accountCache';
+const INFLIGHT_KEY = '__ppAccountList_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const PRIMARY_CONTACT_LABEL = '_primarycontactid_value@OData.Community.Display.V1.FormattedValue';
+
+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 primaryContactName(row: ReadableAccount): string {
+ const label = (row as unknown as Record<string, unknown>)[PRIMARY_CONTACT_LABEL];
+ return typeof label === 'string' ? label : '';
+}
+
+// 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 openAccount(accountId: string): void {
+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;
+ void xrm?.Navigation?.navigateTo({
+ pageType: 'entityrecord',
+ entityName: 'account',
+ entityId: accountId,
+ });
+}
+
+const columns: TableColumnDefinition<ReadableAccount>[] = [
+ createTableColumn<ReadableAccount>({
+ columnId: 'name',
+ compare: (a, b) => compareText(textOf(a.name), textOf(b.name)),
+ renderHeaderCell: () => 'Account name',
+ renderCell: (item) => (
+ <TableCellLayout truncate>
+ <Link
+ onClick={() => openAccount(item.accountid)}
+ title={item.name || 'Unnamed account'}
+ aria-label={`Open account ${item.name || 'Unnamed account'}`}
+ >
+ {item.name || 'Unnamed account'}
+ </Link>
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'accountnumber',
+ compare: (a, b) => compareText(textOf(a.accountnumber), textOf(b.accountnumber)),
+ renderHeaderCell: () => 'Account number',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={textOf(item.accountnumber)}>
+ {item.accountnumber || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'telephone1',
+ compare: (a, b) => compareText(textOf(a.telephone1), textOf(b.telephone1)),
+ renderHeaderCell: () => 'Main phone',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={textOf(item.telephone1)}>
+ {item.telephone1 || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'address1_city',
+ compare: (a, b) => compareText(textOf(a.address1_city), textOf(b.address1_city)),
+ renderHeaderCell: () => 'City',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={textOf(item.address1_city)}>
+ {item.address1_city || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'primarycontact',
+ compare: (a, b) => compareText(primaryContactName(a), primaryContactName(b)),
+ renderHeaderCell: () => 'Primary contact',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={primaryContactName(item)}>
+ {primaryContactName(item) || '—'}
+ </TableCellLayout>
+ ),
+ }),
+];
+
+const columnSizingOptions: TableColumnSizingOptions = {
+ name: { defaultWidth: 260, idealWidth: 260, minWidth: 180 },
+ accountnumber: { defaultWidth: 150, idealWidth: 150, minWidth: 110 },
+ telephone1: { defaultWidth: 160, idealWidth: 160, minWidth: 120 },
+ address1_city: { defaultWidth: 160, idealWidth: 160, minWidth: 110 },
+ primarycontact: { defaultWidth: 220, idealWidth: 220, minWidth: 150 },
+};
+
+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<AccountListState>(() => {
+ 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', 'accountnumber', 'telephone1', 'address1_city', '_primarycontactid_value'],
+ 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>
+ )}
+
+ <div className={styles.gridWrap}>
+ {data.records.length === 0 && !data.error ? (
+ <Text className={styles.empty} block>
+ No accounts found.
+ </Text>
+ ) : (
+ <DataGrid
+ items={data.records}
+ columns={columns}
+ getRowId={(row) => row.accountid}
+ sortable
+ resizableColumns
+ columnSizingOptions={columnSizingOptions}
+ focusMode="composite"
+ aria-label="Accounts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<ReadableAccount>>
+ {({ item, rowId }) => (
+ <DataGridRow<ReadableAccount> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/agent-message.txt b/evals/model-apps/genpage/fixtures/16-account-list/agent-message.txt
new file mode 100644
index 000000000..91f59976c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/agent-message.txt
@@ -0,0 +1 @@
+Created the Account List page: a sortable grid of Account records (name, account number, main phone, city and primary contact). Selecting an account name opens its Account form.
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/fixture.json b/evals/model-apps/genpage/fixtures/16-account-list/fixture.json
new file mode 100644
index 000000000..e75bbeffd
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/fixture.json
@@ -0,0 +1,21 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of a compliant attended create run for eval 16, not an agent capture. An existing Dataverse table (account) is shown as a single sortable list page added to an existing app; code-only, so no solution question, entity work or auth gate. 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 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"]
+}
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/genpage-plan.md b/evals/model-apps/genpage/fixtures/16-account-list/genpage-plan.md
new file mode 100644
index 000000000..331215cd3
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/genpage-plan.md
@@ -0,0 +1,61 @@
+# Genpage Plan
+
+## User Requirements
+Build a page showing Account records.
+
+- Data source: Dataverse entity account (already exists)
+- Specific requirements: simple account list
+
+## Working Directory
+D:/work/account-records
+
+## 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 |
+|------|------|---------|----------|
+| Account List | account-list.tsx | Simple sortable list of Account records with click-to-open | 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: Simple list — sortable column headers, record count, account name opens the Account form
+- Accessibility: WCAG AA defaults; grid has an accessible label and the name link announces its target
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Account List | 9-list-with-caching.tsx | Dataverse list page with DataGrid, window cache and in-flight de-dupe |
+| Account List | 1-account-grid.tsx | Account DataGrid with sortable columns |
+
+## Per-Page Specifications
+
+### Account List
+- **File:** account-list.tsx
+- **Purpose:** Simple sortable list of Account records with click-to-open
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** Accounts title with record count; sortable grid of account name, account number, main phone, city and primary contact; empty and error states.
+- **Components:** DataGrid (createTableColumn, sortable, resizableColumns, columnSizingOptions), TableCellLayout, Link, Text, Caption1, Spinner, MessageBar; BuildingRegular icon.
+- **Layout:** Flex column filling the page; header row with title opposite the count; only the grid area scrolls; no viewport units.
+- **Data Binding:** dataApi.queryTable('account') on mount selecting accountid, name, accountnumber, telephone1, address1_city, _primarycontactid_value, ordered by name asc, read via result.rows; primary contact label from the _primarycontactid_value FormattedValue annotation; window cache + in-flight de-dupe keyed for this page, single batched setData.
+- **Interactions:** Column header click sorts; selecting an account name opens the Account record with Xrm.Navigation.navigateTo (pageType entityrecord).
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/page-name.txt b/evals/model-apps/genpage/fixtures/16-account-list/page-name.txt
new file mode 100644
index 000000000..85714e082
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/page-name.txt
@@ -0,0 +1 @@
+Account List
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/prompt.txt b/evals/model-apps/genpage/fixtures/16-account-list/prompt.txt
new file mode 100644
index 000000000..34c5e9eb8
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/prompt.txt
@@ -0,0 +1,4 @@
+Build a page showing Account records.
+
+- Data source: Dataverse entity account (already exists)
+- Specific requirements: simple account list
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/tool-results.json b/evals/model-apps/genpage/fixtures/16-account-list/tool-results.json
new file mode 100644
index 000000000..dad851627
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/tool-results.json
@@ -0,0 +1,89 @@
+[
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/account-records' 'account-records'",
+ "exitCode": 0,
+ "result": { "workingDir": "D:\\work\\account-records", "slug": "account-records", "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": "pac model list-languages", "exitCode": 0, "result": "LCID Code Name RTL\n1033 en-US English No" },
+ { "id": "list-tables", "by": "genpage-planner", "command": "pac model list-tables --search 'account'", "exitCode": 0, "result": "Logical Name Display Name\naccount Account\naccountleads AccountLeads\nmsdyn_accountkpiitem Account KPI Item" },
+ { "id": "list-apps", "by": "genpage-planner", "command": "pac model list", "exitCode": 0, "result": "App ID Display Name Unique Name\n11111111-2222-3333-4444-555555555555 Sales Hub SalesHub\n44444444-5555-6666-7777-888888888888 Customer Service Hub CustomerServiceHub" },
+ {
+ "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, simple account list, app Sales Hub)",
+ "result": { "action": "plan", "pages": [{ "page": "Account List", "file": "account-list.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-records/genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\account-records\\genpage-plan.md", "quarantinedPath": null }
+ },
+ {
+ "id": "planner-write",
+ "command": "Task genpage-planner (approved: write genpage-plan.md)",
+ "result": { "action": "written", "plan": "D:/work/account-records/genpage-plan.md" }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/account-records/genpage-plan.md' --approved '@D:/work/account-records/.approved-genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\account-records\\genpage-plan.md", "kind": "create", "targets": ["account-list.tsx"], "writtenHash": "b3d9d84ab91f70a322f552788b5b54b7f319f8874c5244164279883f6e5bf10d" }
+ },
+ {
+ "id": "generate-types",
+ "command": "pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-records/RuntimeTypes.ts'",
+ "exitCode": 0,
+ "result": "Types written to D:/work/account-records/RuntimeTypes.ts"
+ },
+ { "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-records/genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "workingDir": "D:\\work\\account-records", "files": ["account-list.tsx"], "problems": [] }
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/account-records/account-list.tsx'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\account-records\\account-list.tsx", "existed": false }
+ },
+ { "id": "write-page", "command": "Write account-list.tsx", "artifact": "account-list.tsx" },
+ { "id": "icon-grep", "command": "Grep from \"@fluentui/react-icons\" account-list.tsx; Grep ^BuildingRegular$ references/verified-icons.txt", "result": "BuildingRegular: verified" },
+ { "id": "border-grep", "command": "Grep ['\"]?borderWidth['\"]?\\s*: account-list.tsx", "result": "no matches" },
+ {
+ "id": "gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-records/account-list.tsx'",
+ "artifact": "account-list.tsx",
+ "exitCode": 0,
+ "result": { "ok": true, "filePath": "D:\\work\\account-records\\account-list.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-list.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": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "appId": "11111111-2222-3333-4444-555555555555", "updated": false }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/16-account-list/workflow-log.md b/evals/model-apps/genpage/fixtures/16-account-list/workflow-log.md
new file mode 100644
index 000000000..7692c9b94
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/16-account-list/workflow-log.md
@@ -0,0 +1,129 @@
+# Workflow Log — Eval 16: Account list (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.
+
+## Phase 0 — Working directory
+- `$ARGUMENTS`: "Build a page showing Account records."
+- Working directory created: `mkdir -p 'account-records'` (kebab-case from "Account records")
+- Resolved working directory: D:/work/account-records
+- 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-records' 'account-records'`
+- 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
+- AskUserQuestion: Where should the page get its data? → Dataverse entity: account
+- AskUserQuestion: Any specific requirements for the page? → Simple account list
+
+### 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 `pac model list-languages` → English (1033) only, no RTL language
+- Planner ran `pac model list-tables --search 'account'` → exact logical-name match `account` (also listed: accountleads, msdyn_accountkpiitem — not exact matches, ignored); account already exists, so no entity creation
+- Planner ran `pac model list` → 2 apps: Sales Hub (11111111-2222-3333-4444-555555555555), Customer Service Hub (44444444-5555-6666-7777-888888888888)
+- 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 `pac model 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: Account List 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-records/genpage-plan.md'`
+- Result: `"ok":true`, nothing to quarantine (first run in this folder)
+- Saved the approved plan body verbatim to D:/work/account-records/.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-records/genpage-plan.md' --approved '@D:/work/account-records/.approved-genpage-plan.md'`
+- Result: `"ok":true`, kind create, targets [account-list.tsx], writtenHash b3d9d84ab91f70a322f552788b5b54b7f319f8874c5244164279883f6e5bf10d
+
+## 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
+- `pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-records/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified accountid, name, accountnumber, telephone1, address1_city and the `_primarycontactid_value` foreign key (display name comes from its FormattedValue annotation; `primarycontactidname` is not selectable)
+
+## 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 `### Account List` subsection
+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/account-records/genpage-plan.md'`
+- Result: `"ok":true` — account-list.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 samples 9-list-with-caching.tsx and 1-account-grid.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/account-records/account-list.tsx'`
+- Result: `"ok":true`, stamp recorded, no earlier file at the target
+- Wrote account-list.tsx with the file tool: sortable DataGrid (createTableColumn + compare, resizableColumns, columnSizingOptions), window cache + in-flight de-dupe gated on `dataReady`, single batched setData, result read via `.rows`, record open via Xrm.Navigation.navigateTo
+- Icon verification: Grep for `from "@fluentui/react-icons"` → one named import, BuildingRegular; Grep of references/verified-icons.txt for `^BuildingRegular$` → present
+- Grep `['"]?borderWidth['"]?\s*:` → no matches
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-records/account-list.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 ("Account List") 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-list.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 = aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee, 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 |
+|------|------|----------|--------|
+| Account List | account-list.tsx | account | Deployed |
+
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Page ID: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
+- Entities created: none
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/agent-message.txt b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/agent-message.txt
new file mode 100644
index 000000000..8f6249d93
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/agent-message.txt
@@ -0,0 +1 @@
+Added a search box that filters contacts by full name, company name or email, and header sorting on every column with Company name ascending as the default. The query, cache, columns and record navigation are unchanged.
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/config.json b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/config.json
new file mode 100644
index 000000000..c63e5f92d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/config.json
@@ -0,0 +1,4 @@
+{
+ "dataSources": ["contact"],
+ "model": "claude-sonnet-4-6"
+}
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/page.tsx b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/page.tsx
new file mode 100644
index 000000000..614834b38
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/page.tsx
@@ -0,0 +1,306 @@
+import { useEffect, useState } from 'react';
+import type {
+ TableRow,
+ ReadableTableRow,
+ GeneratedComponentProps,
+} 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 { PeopleRegular } from '@fluentui/react-icons';
+
+// Contacts Directory — every contact with its company, job title, email and business phone.
+// The company is the contact's Company Name lookup (parentcustomerid, account or contact),
+// so the FK column is selected and the label read from its FormattedValue annotation.
+
+type ContactRow = TableRow<{
+ readonly contactid: string;
+ fullname?: string;
+ jobtitle?: string;
+ emailaddress1?: string;
+ telephone1?: string;
+ readonly _parentcustomerid_value?: string;
+}>;
+
+type ReadableContact = ReadableTableRow<ContactRow>;
+
+type ContactsState = {
+ records: ReadableContact[];
+ loading: boolean;
+ error: string | null;
+};
+
+// Window cache + in-flight de-dupe so the host double-mount issues one query.
+const CACHE_KEY = '__ppContactsDirectory_contactCache';
+const INFLIGHT_KEY = '__ppContactsDirectory_contactInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const COMPANY_LABEL = '_parentcustomerid_value@OData.Community.Display.V1.FormattedValue';
+
+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 companyName(row: ReadableContact): string {
+ const label = (row as unknown as Record<string, unknown>)[COMPANY_LABEL];
+ return typeof label === 'string' ? label : '';
+}
+
+function openContact(contactId: string): void {
+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;
+ void xrm?.Navigation?.navigateTo({
+ pageType: 'entityrecord',
+ entityName: 'contact',
+ entityId: contactId,
+ });
+}
+
+const columns: TableColumnDefinition<ReadableContact>[] = [
+ createTableColumn<ReadableContact>({
+ columnId: 'fullname',
+ renderHeaderCell: () => 'Full name',
+ renderCell: (item) => (
+ <TableCellLayout truncate>
+ <Link
+ onClick={() => openContact(item.contactid)}
+ title={item.fullname || 'Unnamed contact'}
+ aria-label={`Open contact ${item.fullname || 'Unnamed contact'}`}
+ >
+ {item.fullname || 'Unnamed contact'}
+ </Link>
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'company',
+ renderHeaderCell: () => 'Company name',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={companyName(item)}>
+ {companyName(item) || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'jobtitle',
+ renderHeaderCell: () => 'Job title',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.jobtitle ?? ''}>
+ {item.jobtitle || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'emailaddress1',
+ renderHeaderCell: () => 'Email',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.emailaddress1 ?? ''}>
+ {item.emailaddress1 || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'telephone1',
+ renderHeaderCell: () => 'Business phone',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.telephone1 ?? ''}>
+ {item.telephone1 || '—'}
+ </TableCellLayout>
+ ),
+ }),
+];
+
+const columnSizingOptions: TableColumnSizingOptions = {
+ fullname: { defaultWidth: 220, idealWidth: 220, minWidth: 160 },
+ company: { defaultWidth: 220, idealWidth: 220, minWidth: 150 },
+ jobtitle: { defaultWidth: 180, idealWidth: 180, minWidth: 120 },
+ emailaddress1: { defaultWidth: 240, idealWidth: 240, minWidth: 170 },
+ telephone1: { defaultWidth: 160, idealWidth: 160, minWidth: 120 },
+};
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // directory page takes no record context
+ const styles = useStyles();
+
+ const [data, setData] = useState<ContactsState>(() => {
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ return { records: cached ?? [], loading: cached === undefined, error: null };
+ });
+
+ const dataReady = !!dataApi;
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ if (cached !== undefined) {
+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableContact[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi.queryTable('contact', {
+ select: ['contactid', 'fullname', '_parentcustomerid_value', 'jobtitle', 'emailaddress1', 'telephone1'],
+ orderBy: 'fullname asc',
+ pageSize: 250,
+ })
+ .then((result) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows as ReadableContact[];
+ })
+ .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 contacts.';
+ 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 contacts…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <div className={styles.titleGroup}>
+ <PeopleRegular className={styles.titleIcon} aria-hidden="true" />
+ <Text as="h1" size={600} weight="semibold">
+ Contacts
+ </Text>
+ </div>
+ <Caption1 className={styles.count} aria-live="polite">
+ {data.records.length === 1 ? '1 contact' : `${data.records.length} contacts`}
+ </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 contacts found.
+ </Text>
+ ) : (
+ <DataGrid
+ items={data.records}
+ columns={columns}
+ getRowId={(row) => row.contactid}
+ resizableColumns
+ columnSizingOptions={columnSizingOptions}
+ focusMode="composite"
+ aria-label="Contacts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<ReadableContact>>
+ {({ item, rowId }) => (
+ <DataGridRow<ReadableContact> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/prompt.txt b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/prompt.txt
new file mode 100644
index 000000000..3398d98ac
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/before/prompt.txt
@@ -0,0 +1 @@
+Build a contacts directory page that lists my contacts in a grid with full name, company, job title, email and business phone. Clicking a contact's name should open the contact record.
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/fixture.json b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/fixture.json
new file mode 100644
index 000000000..ee0bfd457
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/fixture.json
@@ -0,0 +1,20 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of a compliant attended edit run for eval 3, not an agent capture. The user routes to Edit existing, picks the Sales Hub app and its contacts page from pac model list / genpage list output, and the edit planner's approved genpage-edit-plan.md adds a SearchBox and header sorting with a Company name default. before/ is the downloaded <page-id>/ snapshot; the top-level page.tsx is the edited <working-dir>/<page-id>/page.tsx. The update upload uses --page-id without --add-to-sitemap, file transport and a delta-only prompt; bindings are preserved by omission.",
+ "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",
+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 2: Download Existing Page",
+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 3: Generate RuntimeTypes (Conditional)",
+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 4: Plan the Edit",
+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 5: Apply the Edit",
+ "plugins/model-apps/skills/genpage/edit-flow.md Edit Phase 6: Deploy Updated Page",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy and Prompt semantics",
+ "plugins/model-apps/agents/genpage-edit-planner.md Step 4: Write genpage-edit-plan.md",
+ "plugins/model-apps/references/rules.md DataAPI Rules and DataGrid Requirements"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": ["before/page.tsx", "before/config.json", "before/prompt.txt", "prompt.txt", "agent-message.txt"]
+}
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/genpage-edit-plan.md b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/genpage-edit-plan.md
new file mode 100644
index 000000000..6482bba90
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/genpage-edit-plan.md
@@ -0,0 +1,46 @@
+# Genpage Edit Plan
+
+## File Being Edited
+- **Absolute path:** D:/work/contacts-search-sort/22222222-3333-4444-5555-666666666666/page.tsx
+- **App ID:** 11111111-2222-3333-4444-555555555555
+- **Page ID:** 22222222-3333-4444-5555-666666666666
+
+## Working Directory
+D:/work/contacts-search-sort
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Original Page Context
+- **Original prompt (from prompt.txt):** Build a contacts directory page that lists my contacts in a grid with full name, company, job title, email and business phone. Clicking a contact's name should open the contact record.
+- **Original data sources (from config.json):** contact
+- **Current purpose:** Read-only directory of contacts in a resizable DataGrid (full name, company name, job title, email, business phone); the name opens the contact form. It has no search box and its columns cannot be sorted.
+
+## Entities Used
+contact
+
+## Requested Changes
+1. Add a search bar: a Fluent UI V9 `SearchBox` (aria-label "Search contacts", placeholder "Search name, company or email") in the header, opposite the title, beside the record count. It filters the already-loaded rows client-side, case-insensitively, on full name, company name (the `_parentcustomerid_value` FormattedValue label) and email. No new query is issued and the window cache is not touched.
+2. Add sorting: set `sortable` on the DataGrid with a controlled `sortState` / `onSortChange`, so column header clicks sort and toggle direction. Give every column a `compare`; the Company name column compares the FormattedValue label case-insensitively with blank companies last. Default sort is Company name ascending.
+3. Update the count caption to "Showing N of M contacts" while a search term is active, and show "No contacts match “<term>”." when the search filters out every row (the existing "No contacts found." stays for an empty table).
+4. Keep the derived filtered list (`useMemo`) and the new `useState` hooks above the loading early return (Rule 19).
+
+## Preservation Constraints
+- The query is unchanged: `queryTable('contact')` selecting contactid, fullname, `_parentcustomerid_value`, jobtitle, emailaddress1, telephone1, ordered by fullname asc, pageSize 250, read via `.rows`.
+- 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.
+- Company name is still read from the `_parentcustomerid_value@OData.Community.Display.V1.FormattedValue` annotation; `parentcustomeridname` is never selected.
+- Selecting a contact's full name still opens the contact record with `Xrm.Navigation.navigateTo` (pageType entityrecord).
+- All five columns, their headers, `resizableColumns` and `columnSizingOptions` are unchanged; loading spinner and error MessageBar are unchanged.
+- `export default GeneratedComponent` and the `const { dataApi, pageInput } = props;` signature are unchanged.
+- Connector bindings: none, unchanged — omit `--connectors`. Custom API bindings: none, unchanged — omit `--actions`. Data source stays `contact`.
+
+## Design Notes
+- New styles go in `makeStyles` with tokens (a `headerActions` row and a `search` slot); the search box goes full width under 480px via a media query nested in its slot.
+- The SearchBox carries its own search glyph; no new icon imports are needed.
+- Sorting is driven by the DataGrid header cells (keyboard accessible); the default Company name sort is visible in the header's sort indicator.
+
+## Relevant Samples
+| Purpose | Sample |
+|---------|--------|
+| SearchBox filtering a cached Dataverse DataGrid | 9-list-with-caching.tsx |
+| Sortable DataGrid columns with `compare` | 1-account-grid.tsx |
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/page.tsx b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/page.tsx
new file mode 100644
index 000000000..88f41ddf6
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/page.tsx
@@ -0,0 +1,380 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ TableRow,
+ ReadableTableRow,
+ GeneratedComponentProps,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Caption1,
+ Link,
+ SearchBox,
+ Spinner,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import type {
+ SortDirection,
+ TableColumnDefinition,
+ TableColumnId,
+ TableColumnSizingOptions,
+} from '@fluentui/react-components';
+import { PeopleRegular } from '@fluentui/react-icons';
+
+// Contacts Directory — every contact with its company, job title, email and business phone.
+// The company is the contact's Company Name lookup (parentcustomerid, account or contact),
+// so the FK column is selected and the label read from its FormattedValue annotation.
+
+type ContactRow = TableRow<{
+ readonly contactid: string;
+ fullname?: string;
+ jobtitle?: string;
+ emailaddress1?: string;
+ telephone1?: string;
+ readonly _parentcustomerid_value?: string;
+}>;
+
+type ReadableContact = ReadableTableRow<ContactRow>;
+
+type ContactsState = {
+ records: ReadableContact[];
+ loading: boolean;
+ error: string | null;
+};
+
+type GridSortState = {
+ sortColumn: TableColumnId | undefined;
+ sortDirection: SortDirection;
+};
+
+// Window cache + in-flight de-dupe so the host double-mount issues one query.
+const CACHE_KEY = '__ppContactsDirectory_contactCache';
+const INFLIGHT_KEY = '__ppContactsDirectory_contactInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const COMPANY_LABEL = '_parentcustomerid_value@OData.Community.Display.V1.FormattedValue';
+
+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,
+ },
+ headerActions: {
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ search: {
+ width: '280px',
+ maxWidth: '100%',
+ '@media (max-width: 480px)': {
+ width: '100%',
+ },
+ },
+ 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 companyName(row: ReadableContact): string {
+ const label = (row as unknown as Record<string, unknown>)[COMPANY_LABEL];
+ return typeof label === 'string' ? label : '';
+}
+
+// Case-insensitive compare that keeps blank values at the end of an ascending sort,
+// so contacts without a company do not crowd the top of the company-name order.
+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 matchesSearch(row: ReadableContact, term: string): boolean {
+ if (!term) return true;
+ return [row.fullname, companyName(row), row.emailaddress1]
+ .some((value) => (value ?? '').toLowerCase().includes(term));
+}
+
+function openContact(contactId: string): void {
+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;
+ void xrm?.Navigation?.navigateTo({
+ pageType: 'entityrecord',
+ entityName: 'contact',
+ entityId: contactId,
+ });
+}
+
+const columns: TableColumnDefinition<ReadableContact>[] = [
+ createTableColumn<ReadableContact>({
+ columnId: 'fullname',
+ compare: (a, b) => compareText(a.fullname ?? '', b.fullname ?? ''),
+ renderHeaderCell: () => 'Full name',
+ renderCell: (item) => (
+ <TableCellLayout truncate>
+ <Link
+ onClick={() => openContact(item.contactid)}
+ title={item.fullname || 'Unnamed contact'}
+ aria-label={`Open contact ${item.fullname || 'Unnamed contact'}`}
+ >
+ {item.fullname || 'Unnamed contact'}
+ </Link>
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'company',
+ compare: (a, b) => compareText(companyName(a), companyName(b)),
+ renderHeaderCell: () => 'Company name',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={companyName(item)}>
+ {companyName(item) || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'jobtitle',
+ compare: (a, b) => compareText(a.jobtitle ?? '', b.jobtitle ?? ''),
+ renderHeaderCell: () => 'Job title',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.jobtitle ?? ''}>
+ {item.jobtitle || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'emailaddress1',
+ compare: (a, b) => compareText(a.emailaddress1 ?? '', b.emailaddress1 ?? ''),
+ renderHeaderCell: () => 'Email',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.emailaddress1 ?? ''}>
+ {item.emailaddress1 || '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableContact>({
+ columnId: 'telephone1',
+ compare: (a, b) => compareText(a.telephone1 ?? '', b.telephone1 ?? ''),
+ renderHeaderCell: () => 'Business phone',
+ renderCell: (item) => (
+ <TableCellLayout truncate title={item.telephone1 ?? ''}>
+ {item.telephone1 || '—'}
+ </TableCellLayout>
+ ),
+ }),
+];
+
+const columnSizingOptions: TableColumnSizingOptions = {
+ fullname: { defaultWidth: 220, idealWidth: 220, minWidth: 160 },
+ company: { defaultWidth: 220, idealWidth: 220, minWidth: 150 },
+ jobtitle: { defaultWidth: 180, idealWidth: 180, minWidth: 120 },
+ emailaddress1: { defaultWidth: 240, idealWidth: 240, minWidth: 170 },
+ telephone1: { defaultWidth: 160, idealWidth: 160, minWidth: 120 },
+};
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // directory page takes no record context
+ const styles = useStyles();
+
+ const [data, setData] = useState<ContactsState>(() => {
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ return { records: cached ?? [], loading: cached === undefined, error: null };
+ });
+ const [search, setSearch] = useState('');
+ // Company name ascending by default; header clicks change column and direction.
+ const [sortState, setSortState] = useState<GridSortState>({
+ sortColumn: 'company',
+ sortDirection: 'ascending',
+ });
+
+ const dataReady = !!dataApi;
+
+ useEffect(() => {
+ if (!dataReady) return;
+
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ if (cached !== undefined) {
+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableContact[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi.queryTable('contact', {
+ select: ['contactid', 'fullname', '_parentcustomerid_value', 'jobtitle', 'emailaddress1', 'telephone1'],
+ orderBy: 'fullname asc',
+ pageSize: 250,
+ })
+ .then((result) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows as ReadableContact[];
+ })
+ .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 contacts.';
+ 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]);
+
+ // Above the loading early return so the hook count never changes between renders (Rule 19).
+ const term = search.trim().toLowerCase();
+ const visible = useMemo(
+ () => data.records.filter((row) => matchesSearch(row, term)),
+ [data.records, term],
+ );
+
+ if (data.loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.spinnerWrap}>
+ <Spinner labelPosition="below" label="Loading contacts…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <div className={styles.titleGroup}>
+ <PeopleRegular className={styles.titleIcon} aria-hidden="true" />
+ <Text as="h1" size={600} weight="semibold">
+ Contacts
+ </Text>
+ </div>
+ <div className={styles.headerActions}>
+ <SearchBox
+ className={styles.search}
+ placeholder="Search name, company or email"
+ value={search}
+ onChange={(_, d) => setSearch(d.value)}
+ aria-label="Search contacts"
+ />
+ <Caption1 className={styles.count} aria-live="polite">
+ {term
+ ? `Showing ${visible.length} of ${data.records.length} contacts`
+ : data.records.length === 1 ? '1 contact' : `${data.records.length} contacts`}
+ </Caption1>
+ </div>
+ </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 contacts found.
+ </Text>
+ ) : visible.length === 0 && term ? (
+ <Text className={styles.empty} block>
+ No contacts match “{search.trim()}”.
+ </Text>
+ ) : (
+ <DataGrid
+ items={visible}
+ columns={columns}
+ getRowId={(row) => row.contactid}
+ sortable
+ sortState={sortState}
+ onSortChange={(_, next) => setSortState(next)}
+ resizableColumns
+ columnSizingOptions={columnSizingOptions}
+ focusMode="composite"
+ aria-label="Contacts"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<ReadableContact>>
+ {({ item, rowId }) => (
+ <DataGridRow<ReadableContact> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/prompt.txt b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/prompt.txt
new file mode 100644
index 000000000..fe45e33fd
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/prompt.txt
@@ -0,0 +1 @@
+Add a search bar and column sorting by company name
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/tool-results.json b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/tool-results.json
new file mode 100644
index 000000000..3e2d4487e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/tool-results.json
@@ -0,0 +1,112 @@
+[
+ {
+ "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": "pac model list",
+ "exitCode": 0,
+ "result": "App ID Display Name Unique Name\n11111111-2222-3333-4444-555555555555 Sales Hub SalesHub\n44444444-5555-6666-7777-888888888888 Customer Service Hub CustomerServiceHub"
+ },
+ {
+ "id": "list-pages",
+ "command": "pac model genpage list --app-id '11111111-2222-3333-4444-555555555555'",
+ "exitCode": 0,
+ "result": "Page ID Name\n22222222-3333-4444-5555-666666666666 Contacts Directory\n33333333-4444-5555-6666-777777777777 Pipeline Snapshot"
+ },
+ {
+ "id": "download",
+ "command": "pac model genpage download --app-id '11111111-2222-3333-4444-555555555555' --page-id '22222222-3333-4444-5555-666666666666' --output-directory 'D:/work/contacts-search-sort'",
+ "exitCode": 0,
+ "result": "Downloaded page 22222222-3333-4444-5555-666666666666 to D:/work/contacts-search-sort/22222222-3333-4444-5555-666666666666 (page.tsx, page.js, config.json, prompt.txt)",
+ "artifacts": ["before/page.tsx", "before/config.json", "before/prompt.txt"]
+ },
+ {
+ "id": "generate-types",
+ "command": "pac model genpage generate-types --data-sources 'contact' --output-file 'D:/work/contacts-search-sort/RuntimeTypes.ts'",
+ "exitCode": 0,
+ "result": "Types written to D:/work/contacts-search-sort/RuntimeTypes.ts"
+ },
+ {
+ "id": "edit-planner-questions",
+ "command": "Task genpage-edit-planner (intent, app/page ids, envUrl, connector action preserve, Custom API action preserve)",
+ "result": {
+ "action": "needs_input",
+ "questions": [
+ { "id": "search-fields", "question": "Which fields should the search bar match?" },
+ { "id": "default-sort", "question": "Should the grid open sorted by company name, or sort only when a column header is clicked?" },
+ { "id": "new-schema", "question": "Do any of these changes require new Dataverse entities or columns?" }
+ ]
+ }
+ },
+ {
+ "id": "edit-planner-proposal",
+ "command": "Task genpage-edit-planner (answers: full name, company name and email; default company A to Z; code-only)",
+ "result": { "action": "plan", "currentStateFile": "22222222-3333-4444-5555-666666666666/page.tsx", "changes": 4, "connectorChanges": "none", "customApiChanges": "none" }
+ },
+ {
+ "id": "plan-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/contacts-search-sort/genpage-edit-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\contacts-search-sort\\genpage-edit-plan.md", "quarantinedPath": null }
+ },
+ {
+ "id": "edit-planner-write",
+ "command": "Task genpage-edit-planner (approved: write genpage-edit-plan.md)",
+ "result": { "action": "written", "plan": "D:/work/contacts-search-sort/genpage-edit-plan.md" }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/contacts-search-sort/genpage-edit-plan.md' --approved '@D:/work/contacts-search-sort/.approved-genpage-edit-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\contacts-search-sort\\genpage-edit-plan.md", "kind": "edit", "targets": ["22222222-3333-4444-5555-666666666666"], "writtenHash": "78e955c6e4a029c1443b5778d4467d54bd0748ebb0a722169c4ba2dd2f2c14ac" }
+ },
+ { "id": "apply-edit", "command": "Edit 22222222-3333-4444-5555-666666666666/page.tsx (15 targeted Edit operations)", "artifact": "page.tsx", "before": "before/page.tsx" },
+ { "id": "icon-grep", "command": "Grep from \"@fluentui/react-icons\" 22222222-3333-4444-5555-666666666666/page.tsx", "result": "PeopleRegular (unchanged, verified)" },
+ { "id": "border-grep", "command": "Grep ['\"]?borderWidth['\"]?\\s*: 22222222-3333-4444-5555-666666666666/page.tsx", "result": "no matches" },
+ { "id": "write-upload-text", "command": "Write prompt.txt, agent-message.txt", "artifacts": ["prompt.txt", "agent-message.txt"] },
+ {
+ "id": "update",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-3333-4444-555555555555' --page-id '22222222-3333-4444-5555-666666666666' --code-file '22222222-3333-4444-5555-666666666666/page.tsx' --data-sources 'contact' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt'",
+ "exitCode": 0,
+ "result": { "ok": true, "pageId": "22222222-3333-4444-5555-666666666666", "appId": "11111111-2222-3333-4444-555555555555", "updated": true }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/workflow-log.md b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/workflow-log.md
new file mode 100644
index 000000000..ab2002da8
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/3-contacts-edit-search-sort/workflow-log.md
@@ -0,0 +1,125 @@
+# Workflow Log — Eval 3: Edit the Sales Hub contacts page (search bar + company-name sorting)
+
+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`. Commands run from the
+working directory, so upload file arguments are relative to it. `before/` holds the downloaded
+`<page-id>/` snapshot (page.tsx, config.json, prompt.txt) taken before Edit Phase 5; the
+top-level page.tsx is the edited `<working-dir>/<page-id>/page.tsx` that was 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
+- `pac model list` → 2 model-driven apps:
+ - 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 Display 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
+- `pac model genpage list --app-id '11111111-2222-3333-4444-555555555555'` → 2 generative pages (non-zero, so the edit can continue):
+ - Contacts Directory — 22222222-3333-4444-5555-666666666666
+ - Pipeline Snapshot — 33333333-4444-5555-6666-777777777777
+- AskUserQuestion: Which page do you want to edit? (options are the page names + page-id GUIDs from that output) → Contacts Directory (the user confirmed page-id 22222222-3333-4444-5555-666666666666)
+
+### 1c. Selection restated
+- "Editing **Contacts Directory** (22222222-3333-4444-5555-666666666666) in app **Sales Hub** (11111111-2222-3333-4444-555555555555). Continuing to download the existing page code…"
+
+## Edit Phase 2 — Download
+- `pac model genpage download --app-id '11111111-2222-3333-4444-555555555555' --page-id '22222222-3333-4444-5555-666666666666' --output-directory 'D:/work/contacts-search-sort'`
+- Produced D:/work/contacts-search-sort/22222222-3333-4444-5555-666666666666/ with page.tsx, page.js, config.json, prompt.txt (snapshot kept in before/)
+
+## Edit Phase 3 — RuntimeTypes and bindings
+- Read 22222222-3333-4444-5555-666666666666/config.json: `dataSources` = ["contact"], model claude-sonnet-4-6; no `connectorBindings`, no `actionBindings`
+- dataSources contains contact → `pac model genpage generate-types --data-sources 'contact' --output-file 'D:/work/contacts-search-sort/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified contactid, fullname, jobtitle, emailaddress1, telephone1 and the `_parentcustomerid_value` foreign key (Company Name lookup, account or contact; its label comes from the FormattedValue annotation)
+- Connector action: preserve (no bindings) — genpage-connector-builder not dispatched, no connectors.json, `--connectors` will be omitted
+- Custom API action: preserve (no bindings) — genpage-customapi-builder not dispatched, no actions.json, `--actions` will be omitted
+
+## Edit Phase 4 — Plan the edit
+- Dispatched `Task genpage-edit-planner` with the edit intent, working directory, plugin root, app-id, page-id, envUrl https://contoso.crm.dynamics.com, download directory, connector action preserve (No connector bindings., none — omit --connectors) and Custom API action preserve (No custom API bindings., none — omit --actions)
+- The edit planner read page.tsx, config.json and prompt.txt from the 22222222-3333-4444-5555-666666666666/ folder, plus RuntimeTypes.ts
+- It returned `{ "action": "needs_input" }` with three questions (the change itself was already clear from the request, and the change is additive):
+- AskUserQuestion: Which fields should the search bar match? → Full name, company name and email
+- AskUserQuestion: Should the grid open sorted by company name, or sort only when a column header is clicked? → Open sorted by company name (A to Z); header clicks can change it
+- AskUserQuestion: Do any of these changes require new Dataverse entities or columns? → No, code-only changes
+- Re-invoked `Task genpage-edit-planner` with the three answers and everything it returned; it proposed the edit plan (Current State: Contacts Directory, data source contact; 4 changes; connectors and Custom APIs unchanged)
+- EnterPlanMode called — presented the proposed edit plan
+- ExitPlanMode → user approved the edit plan
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/contacts-search-sort/genpage-edit-plan.md'`
+- Result: `"ok":true`, nothing to quarantine
+- Saved the approved edit-plan body verbatim to D:/work/contacts-search-sort/.approved-genpage-edit-plan.md
+- Re-invoked `Task genpage-edit-planner` with the approval outcome, the exact approved body, the answers and the binding contracts
+- genpage-edit-plan.md written to the working directory root (not inside the 22222222-3333-4444-5555-666666666666/ folder)
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/contacts-search-sort/genpage-edit-plan.md' --approved '@D:/work/contacts-search-sort/.approved-genpage-edit-plan.md'`
+- Result: `"ok":true`, kind edit, targets [22222222-3333-4444-5555-666666666666], writtenHash 78e955c6e4a029c1443b5778d4467d54bd0748ebb0a722169c4ba2dd2f2c14ac
+
+## Edit Phase 5 — Apply the edit
+- Orchestrator read genpage-edit-plan.md, references/rules.md, RuntimeTypes.ts and 22222222-3333-4444-5555-666666666666/page.tsx (connectors.md not needed: no connector bindings)
+- Edits applied inline with the Edit tool on D:/work/contacts-search-sort/22222222-3333-4444-5555-666666666666/page.tsx — 15 targeted Edit operations, no full-file rewrite:
+ - imports: `useMemo`; `SearchBox`; `SortDirection` and `TableColumnId` types
+ - `GridSortState` type; `compareText` (case-insensitive, blank companies last) and `matchesSearch` helpers
+ - `compare` added to each of the five columns; Company name compares the `_parentcustomerid_value` FormattedValue label
+ - `headerActions` and `search` makeStyles slots (media query nested in the `search` slot)
+ - `search` state and `sortState` state defaulting to Company name ascending
+ - filtered `visible` rows via `useMemo`, placed above the loading early return
+ - header: Fluent UI V9 `SearchBox` (aria-label "Search contacts") beside the count, which reads "Showing N of M contacts" while searching
+ - DataGrid: `items={visible}`, `sortable`, `sortState`, `onSortChange` — sorting is driven by the column header cells; "No contacts match" state for an empty search result
+- Preservation Constraints checked against before/page.tsx: query, select list, cache/in-flight keys, `[dataReady]` deps, batched setData, FormattedValue company label, Xrm.Navigation.navigateTo record open, the five columns, sizing options and `export default GeneratedComponent` unchanged
+- Icon check: Grep for `from "@fluentui/react-icons"` → still only PeopleRegular (verified against references/verified-icons.txt); no icon added
+- Grep `['"]?borderWidth['"]?\s*:` → no matches
+
+## Edit Phase 6 — Deploy
+- Connectors unchanged → `--connectors` omitted; Custom APIs unchanged → `--actions` omitted; config.json dataSources non-empty → `--data-sources 'contact'`
+- Not renaming the page → no `--name-file`; the wrapper reads the page's current name and re-sends it
+- Checked prompt.txt and agent-message.txt in the working directory: none existed, none is a link
+- Wrote prompt.txt (the edit request only) and agent-message.txt (change summary) 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' --page-id '22222222-3333-4444-5555-666666666666' --code-file '22222222-3333-4444-5555-666666666666/page.tsx' --data-sources 'contact' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt'`
+- Prompt scope: delta only — "Add a search bar and column sorting by company name" (not the original page description)
+- `--add-to-sitemap` omitted: the page is already in the Sales Hub sitemap
+- Result: page-id = 22222222-3333-4444-5555-666666666666, status = success (`updated: true`, no warnings)
+
+## Edit Phase 7 — Verify
+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification
+
+## Edit Phase 8 — Summary
+
+| File | Changes | Status |
+|------|---------|--------|
+| 22222222-3333-4444-5555-666666666666/page.tsx | 4 planned changes (search bar, header sorting with Company name default, count/empty states, hook placement) | Deployed |
+
+- App: Sales Hub (11111111-2222-3333-4444-555555555555)
+- Page ID: 22222222-3333-4444-5555-666666666666
+- Entities created: none; bindings unchanged
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/agent-message.txt b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/agent-message.txt
new file mode 100644
index 000000000..89e3315fc
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/agent-message.txt
@@ -0,0 +1 @@
+Created a clean, minimal website analytics dashboard from mock data: four KPI figures, a D3 line chart of weekly visitors and page views, and D3 bar charts of visitors by age group and top country.
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/fixture.json b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/fixture.json
new file mode 100644
index 000000000..8876676bd
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/fixture.json
@@ -0,0 +1,16 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of an attended /genpage create run for eval 6, not an agent capture: a clean, minimal mock-data website analytics dashboard (weekly traffic trend plus age and country demographics) drawn with D3 only, deployed to an existing app. No entity work, no RuntimeTypes, no connector or Custom API bindings, and the upload omits --data-sources. Upload text travels by file through genpage-upload.js.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4: Generate RuntimeTypes (Conditional) — mock data pages skip",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 5b: Single-page fast path",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy — For mock data pages, omit --data-sources",
+ "plugins/model-apps/agents/genpage-planner.md Solution Selection — code-only flows skip the question",
+ "plugins/model-apps/references/rules.md Charts and Visualization"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": ["prompt.txt", "agent-message.txt", "page-name.txt"]
+}
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/genpage-plan.md b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/genpage-plan.md
new file mode 100644
index 000000000..dce0521ef
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/genpage-plan.md
@@ -0,0 +1,57 @@
+# Genpage Plan
+
+## User Requirements
+Create a simple analytics dashboard with mock data. I just want some charts showing website traffic trends and visitor demographics. Keep it clean and minimal.
+
+## Working Directory
+D:/work/website-traffic-analytics
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: Contoso Marketing Hub (11111111-2222-4333-8444-555555555555)
+- Languages: English (1033) only
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Website Analytics | traffic-dashboard.tsx | Minimal dashboard of weekly traffic trends and visitor demographics | mock data |
+
+## Entity Creation Required
+No entity creation required — all entities already exist.
+
+## Existing Entities
+None
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+- Styling: clean and minimal — default Fluent light theme, neutral cards, generous whitespace, no decorative icons or gradients
+- Features: four KPI figures with week-over-week change, one traffic trend chart, two demographic charts; no filters or drill-downs
+- Accessibility: WCAG AA defaults; every chart has role="img" with an aria-label and native SVG tooltips on data points
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Website Analytics | 8-dashboard-with-charts.tsx | KPI cards plus D3 charts with the animation guard |
+
+## Per-Page Specifications
+
+### Website Analytics
+- **File:** traffic-dashboard.tsx
+- **Purpose:** Minimal dashboard of weekly traffic trends and visitor demographics
+- **Entities:** mock data
+- **Needs caching:** false
+- **Key Features:** KPI row (visitors, page views, average session, bounce rate with week-over-week deltas); D3 line chart of weekly visitors and page views over the last 12 weeks; D3 bar charts of visitors by age group and by top country
+- **Components:** Card, CardHeader, Text from Fluent UI V9; D3.js for all charts; no icons
+- **Layout:** Flex column root; responsive KPI grid; chart grid with the trend chart full width and the two demographic charts side by side, stacking below 768px; no 100vh/100vw
+- **Data Binding:** Inline mock arrays (12 weekly traffic points, 6 age groups, 6 countries) and static session stats; no host fetch
+- **Interactions:** Native SVG tooltips on chart points and bars; one-time chart animation guarded by a window flag
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/page-name.txt b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/page-name.txt
new file mode 100644
index 000000000..365218134
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/page-name.txt
@@ -0,0 +1 @@
+Website Analytics
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/prompt.txt b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/prompt.txt
new file mode 100644
index 000000000..0e84b6142
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/prompt.txt
@@ -0,0 +1 @@
+Create a simple analytics dashboard with mock data. I just want some charts showing website traffic trends and visitor demographics. Keep it clean and minimal.
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/tool-results.json b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/tool-results.json
new file mode 100644
index 000000000..d1ba1a060
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/tool-results.json
@@ -0,0 +1,83 @@
+[
+ { "id": "plugin-check", "command": "node 'D:/repo/plugins/model-apps/scripts/check-version.js'", "result": { "stdout": "" }, "exitCode": 0 },
+ { "id": "mkdir", "command": "mkdir -p 'website-traffic-analytics'", "exitCode": 0 },
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/website-traffic-analytics' 'website-traffic-analytics' --features charts",
+ "result": { "workingDir": "D:/work/website-traffic-analytics", "slug": "website-traffic-analytics", "features": ["charts"], "files": { "package.json": { "wrote": true }, "genpage.d.ts": { "wrote": true } } },
+ "exitCode": 0
+ },
+ { "id": "interaction-mode", "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'", "result": { "ok": true, "interactive": true, "reason": "default (attended)" }, "exitCode": 0 },
+ { "id": "node-version", "command": "node --version", "result": { "stdout": "v20.20.2" }, "exitCode": 0 },
+ { "id": "pac-help", "command": "pac help", "result": { "stdout": "Microsoft PowerPlatform CLI\nVersion: 2.11.0" }, "exitCode": 0 },
+ {
+ "id": "pac-auth-list",
+ "command": "pac auth list",
+ "result": { "profiles": [{ "index": 1, "active": true, "kind": "UNIVERSAL", "user": "[email protected]", "environment": "Contoso Dev", "environmentUrl": "https://contoso.crm.dynamics.com/" }] },
+ "exitCode": 0
+ },
+ { "id": "ask-new-or-edit", "command": "AskUserQuestion: Create new page(s) or edit an existing one?", "result": { "answer": "Create new page(s)" } },
+ {
+ "id": "list-languages",
+ "command": "pac model list-languages",
+ "result": { "languages": [{ "lcid": 1033, "language": "English", "code": "en-US", "rtl": false }] },
+ "exitCode": 0
+ },
+ { "id": "ask-requirements", "command": "AskUserQuestion: Any specific requirements?", "result": { "answer": "Clean and minimal design" } },
+ {
+ "id": "app-list",
+ "command": "pac model list",
+ "result": { "apps": [
+ { "name": "Contoso Marketing Hub", "appId": "11111111-2222-4333-8444-555555555555" },
+ { "name": "Field Service Lite", "appId": "99999999-8888-4777-8666-555555555555" }
+ ] },
+ "exitCode": 0
+ },
+ { "id": "ask-app", "command": "AskUserQuestion: Which model-driven app should host the page?", "result": { "answer": "Contoso Marketing Hub (11111111-2222-4333-8444-555555555555)" } },
+ { "id": "plan-approval", "command": "EnterPlanMode", "result": { "outcome": "approved" } },
+ {
+ "id": "provenance-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/website-traffic-analytics/genpage-plan.md'",
+ "result": { "ok": true, "action": "prepare", "planPath": "D:/work/website-traffic-analytics/genpage-plan.md", "quarantinedPath": null },
+ "exitCode": 0
+ },
+ { "id": "planner-writeback", "command": "Task genpage-planner (approved; write genpage-plan.md)", "artifact": "genpage-plan.md" },
+ {
+ "id": "provenance-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/website-traffic-analytics/genpage-plan.md' --approved '@D:/work/website-traffic-analytics/.approved-genpage-plan.md'",
+ "result": { "ok": true, "action": "verify", "planPath": "D:/work/website-traffic-analytics/genpage-plan.md", "kind": "create", "targets": ["traffic-dashboard.tsx"], "writtenHash": "b6a01df32403a40ffa8e9a39d26e977c51b36e45856cc91891029fef6c110378" },
+ "exitCode": 0
+ },
+ { "id": "gate-custom-api", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api", "result": "disabled", "exitCode": 1 },
+ { "id": "gate-telemetry", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry", "result": "disabled", "exitCode": 1 },
+ {
+ "id": "check-page-files",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/website-traffic-analytics/genpage-plan.md'",
+ "result": { "ok": true, "workingDir": "D:/work/website-traffic-analytics", "files": ["traffic-dashboard.tsx"], "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/website-traffic-analytics/traffic-dashboard.tsx'",
+ "result": { "ok": true, "action": "stamp", "filePath": "D:/work/website-traffic-analytics/traffic-dashboard.tsx", "existed": false },
+ "exitCode": 0
+ },
+ { "id": "write-page", "command": "Write traffic-dashboard.tsx", "artifact": "traffic-dashboard.tsx" },
+ {
+ "id": "worker-gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/website-traffic-analytics/traffic-dashboard.tsx'",
+ "artifact": "traffic-dashboard.tsx",
+ "result": { "ok": true, "filePath": "D:/work/website-traffic-analytics/traffic-dashboard.tsx", "problems": [] },
+ "exitCode": 0
+ },
+ { "id": "write-prompt", "command": "Write prompt.txt", "artifact": "prompt.txt" },
+ { "id": "write-agent-message", "command": "Write agent-message.txt", "artifact": "agent-message.txt" },
+ { "id": "write-page-name", "command": "Write page-name.txt", "artifact": "page-name.txt" },
+ {
+ "id": "upload",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-4333-8444-555555555555' --code-file 'traffic-dashboard.tsx' --name-file 'page-name.txt' --prompt-file 'prompt.txt' --model 'claude-sonnet-4.5' --agent-message-file 'agent-message.txt' --add-to-sitemap",
+ "result": { "ok": true, "pageId": "33333333-4444-4555-8666-777777777777", "appId": "11111111-2222-4333-8444-555555555555", "updated": false },
+ "exitCode": 0
+ },
+ { "id": "ask-verify", "command": "AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright?", "result": { "answer": "Skip verification" } }
+]
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/traffic-dashboard.tsx b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/traffic-dashboard.tsx
new file mode 100644
index 000000000..0e96f4c75
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/traffic-dashboard.tsx
@@ -0,0 +1,418 @@
+import * as React from 'react';
+import { useEffect, useRef } from 'react';
+import { makeStyles, tokens, Text, Card, CardHeader } from '@fluentui/react-components';
+import * as d3 from 'd3';
+
+// ---------- Mock data (last 12 weeks) ----------
+
+interface WeeklyTraffic {
+ week: string;
+ visitors: number;
+ pageViews: number;
+}
+
+interface Share {
+ label: string;
+ percent: number;
+}
+
+const weeklyTraffic: WeeklyTraffic[] = [
+ { week: 'Jul 13', visitors: 17840, pageViews: 50120 },
+ { week: 'Jul 20', visitors: 18320, pageViews: 51870 },
+ { week: 'Jul 27', visitors: 17960, pageViews: 50340 },
+ { week: 'Aug 3', visitors: 19410, pageViews: 55260 },
+ { week: 'Aug 10', visitors: 20150, pageViews: 57410 },
+ { week: 'Aug 17', visitors: 19780, pageViews: 56030 },
+ { week: 'Aug 24', visitors: 21030, pageViews: 60280 },
+ { week: 'Aug 31', visitors: 21890, pageViews: 62950 },
+ { week: 'Sep 7', visitors: 22470, pageViews: 64170 },
+ { week: 'Sep 14', visitors: 22960, pageViews: 66020 },
+ { week: 'Sep 21', visitors: 23280, pageViews: 67340 },
+ { week: 'Sep 28', visitors: 24860, pageViews: 71290 },
+];
+
+const ageGroups: Share[] = [
+ { label: '18–24', percent: 18.6 },
+ { label: '25–34', percent: 31.2 },
+ { label: '35–44', percent: 22.4 },
+ { label: '45–54', percent: 14.1 },
+ { label: '55–64', percent: 8.9 },
+ { label: '65+', percent: 4.8 },
+];
+
+const topCountries: Share[] = [
+ { label: 'United States', percent: 38.4 },
+ { label: 'United Kingdom', percent: 11.7 },
+ { label: 'Germany', percent: 9.2 },
+ { label: 'India', percent: 8.5 },
+ { label: 'Canada', percent: 6.3 },
+ { label: 'Other', percent: 25.9 },
+];
+
+const sessionStats = {
+ avgSessionSeconds: 192,
+ avgSessionDeltaPct: -1.5,
+ bounceRatePct: 41.6,
+ bounceRateDeltaPct: -2.3,
+};
+
+// ---------- Styles ----------
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ header: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ },
+ subtitle: { color: tokens.colorNeutralForeground3 },
+ kpiRow: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
+ gap: tokens.spacingHorizontalM,
+ },
+ kpiCard: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXS,
+ padding: tokens.spacingHorizontalL,
+ },
+ kpiLabel: { color: tokens.colorNeutralForeground2 },
+ kpiValue: { fontSize: tokens.fontSizeHero800, fontWeight: tokens.fontWeightSemibold },
+ deltaGood: { color: tokens.colorPaletteGreenForeground1 },
+ deltaBad: { color: tokens.colorPaletteRedForeground1 },
+ chartGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ gap: tokens.spacingHorizontalL,
+ '@media (max-width: 768px)': { gridTemplateColumns: 'minmax(0, 1fr)' },
+ },
+ wideCard: {
+ gridColumnStart: 1,
+ gridColumnEnd: -1,
+ padding: tokens.spacingHorizontalL,
+ },
+ chartCard: { padding: tokens.spacingHorizontalL },
+ trendSvg: { width: '100%', height: '280px' },
+ barSvg: { width: '100%', height: '220px' },
+ legend: {
+ display: 'flex',
+ gap: tokens.spacingHorizontalL,
+ color: tokens.colorNeutralForeground2,
+ },
+ legendItem: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalXS,
+ },
+ swatch: {
+ display: 'inline-block',
+ width: '12px',
+ height: '3px',
+ borderRadius: tokens.borderRadiusSmall,
+ },
+ swatchVisitors: { backgroundColor: tokens.colorBrandStroke1 },
+ swatchPageViews: { backgroundColor: tokens.colorPaletteTealBorderActive },
+});
+
+// ---------- Helpers ----------
+
+function percentChange(current: number, previous: number): number {
+ return previous === 0 ? 0 : ((current - previous) / previous) * 100;
+}
+
+function formatCompact(value: number): string {
+ return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(value);
+}
+
+function formatDuration(totalSeconds: number): string {
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ return `${minutes}m ${seconds.toString().padStart(2, '0')}s`;
+}
+
+function formatDelta(deltaPct: number): string {
+ const sign = deltaPct >= 0 ? '+' : '';
+ return `${sign}${deltaPct.toFixed(1)}% vs last week`;
+}
+
+// ---------- KPI card ----------
+
+interface KpiCardProps {
+ label: string;
+ value: string;
+ deltaPct: number;
+ higherIsBetter: boolean;
+}
+
+const KpiCard = (props: KpiCardProps) => {
+ const styles = useStyles();
+ const improved = props.higherIsBetter ? props.deltaPct >= 0 : props.deltaPct <= 0;
+ return (
+ <Card className={styles.kpiCard} aria-label={`${props.label}: ${props.value}, ${formatDelta(props.deltaPct)}`}>
+ <Text className={styles.kpiLabel}>{props.label}</Text>
+ <Text className={styles.kpiValue}>{props.value}</Text>
+ <Text size={200} className={improved ? styles.deltaGood : styles.deltaBad}>
+ {formatDelta(props.deltaPct)}
+ </Text>
+ </Card>
+ );
+};
+
+// ---------- Traffic trend (D3 line chart) ----------
+
+const TREND_ANIM_KEY = '__ppTrafficTrendAnimated';
+
+type TrafficMetric = 'visitors' | 'pageViews';
+
+const trendSeries: { key: TrafficMetric; label: string; color: string }[] = [
+ { key: 'pageViews', label: 'Page views', color: tokens.colorPaletteTealBorderActive },
+ { key: 'visitors', label: 'Visitors', color: tokens.colorBrandStroke1 },
+];
+
+const TrafficTrendChart = () => {
+ const styles = useStyles();
+ const svgRef = useRef<SVGSVGElement>(null);
+
+ useEffect(() => {
+ const node = svgRef.current;
+ if (!node) return;
+ const svg = d3.select(node);
+ const w = window as unknown as Record<string, boolean>;
+ // Animation guard (rules.md Charts): animate once per session, never replay on remount.
+ if (w[TREND_ANIM_KEY] && svg.selectAll('path.trend-line').size() > 0) return;
+ const shouldAnimate = !w[TREND_ANIM_KEY];
+ w[TREND_ANIM_KEY] = true;
+ svg.selectAll('*').remove();
+
+ const rect = node.getBoundingClientRect();
+ const width = rect.width || 640;
+ const height = rect.height || 280;
+ const margin = { top: 12, right: 16, bottom: 28, left: 48 };
+ const innerW = width - margin.left - margin.right;
+ const innerH = height - margin.top - margin.bottom;
+ const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
+
+ const x = d3.scalePoint<string>().domain(weeklyTraffic.map((d) => d.week)).range([0, innerW]);
+ const y = d3.scaleLinear()
+ .domain([0, (d3.max(weeklyTraffic, (d) => d.pageViews) ?? 0) * 1.1])
+ .nice()
+ .range([innerH, 0]);
+
+ g.append('g')
+ .attr('transform', `translate(0,${innerH})`)
+ .call(d3.axisBottom(x).tickValues(x.domain().filter((_, i) => i % 2 === 0)))
+ .style('color', tokens.colorNeutralForeground3);
+ g.append('g')
+ .call(d3.axisLeft(y).ticks(4).tickFormat((d) => formatCompact(d as number)))
+ .style('color', tokens.colorNeutralForeground3);
+
+ for (const series of trendSeries) {
+ const line = d3.line<WeeklyTraffic>()
+ .x((d) => x(d.week) ?? 0)
+ .y((d) => y(d[series.key]))
+ .curve(d3.curveMonotoneX);
+
+ const path = g.append('path')
+ .datum(weeklyTraffic)
+ .attr('class', 'trend-line')
+ .attr('fill', 'none')
+ .attr('stroke-width', 2)
+ .style('stroke', series.color)
+ .attr('d', line);
+
+ g.selectAll(`circle.${series.key}`)
+ .data(weeklyTraffic)
+ .enter()
+ .append('circle')
+ .attr('class', series.key)
+ .attr('cx', (d) => x(d.week) ?? 0)
+ .attr('cy', (d) => y(d[series.key]))
+ .attr('r', 3)
+ .style('fill', series.color)
+ .append('title')
+ .text((d) => `${series.label}, week of ${d.week}: ${d[series.key].toLocaleString('en-US')}`);
+
+ if (shouldAnimate) {
+ const length = (path.node() as SVGPathElement).getTotalLength();
+ path.attr('stroke-dasharray', `${length} ${length}`)
+ .attr('stroke-dashoffset', length)
+ .transition()
+ .duration(500)
+ .attr('stroke-dashoffset', 0);
+ }
+ }
+ }, []);
+
+ return <svg ref={svgRef} className={styles.trendSvg} role="img" aria-label="Weekly visitors and page views over the last 12 weeks" />;
+};
+
+// ---------- Demographics (D3 horizontal bar chart) ----------
+
+interface ShareBarChartProps {
+ data: Share[];
+ animKey: string;
+ ariaLabel: string;
+}
+
+const ShareBarChart = (props: ShareBarChartProps) => {
+ const styles = useStyles();
+ const svgRef = useRef<SVGSVGElement>(null);
+ const { data, animKey, ariaLabel } = props;
+
+ useEffect(() => {
+ const node = svgRef.current;
+ if (!node) return;
+ const svg = d3.select(node);
+ const w = window as unknown as Record<string, boolean>;
+ if (w[animKey] && svg.selectAll('rect.bar').size() > 0) return;
+ const shouldAnimate = !w[animKey];
+ w[animKey] = true;
+ svg.selectAll('*').remove();
+
+ const rect = node.getBoundingClientRect();
+ const width = rect.width || 360;
+ const height = rect.height || 220;
+ const margin = { top: 4, right: 48, bottom: 4, left: 112 };
+ const innerW = width - margin.left - margin.right;
+ const innerH = height - margin.top - margin.bottom;
+ const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
+
+ const y = d3.scaleBand<string>().domain(data.map((d) => d.label)).range([0, innerH]).padding(0.3);
+ const x = d3.scaleLinear().domain([0, d3.max(data, (d) => d.percent) ?? 0]).range([0, innerW]);
+
+ g.selectAll('text.bar-label')
+ .data(data)
+ .enter()
+ .append('text')
+ .attr('class', 'bar-label')
+ .attr('x', -8)
+ .attr('y', (d) => (y(d.label) ?? 0) + y.bandwidth() / 2)
+ .attr('dy', '0.35em')
+ .attr('text-anchor', 'end')
+ .attr('font-size', '12px')
+ .style('fill', tokens.colorNeutralForeground2)
+ .text((d) => d.label);
+
+ const bars = g.selectAll('rect.bar')
+ .data(data)
+ .enter()
+ .append('rect')
+ .attr('class', 'bar')
+ .attr('x', 0)
+ .attr('y', (d) => y(d.label) ?? 0)
+ .attr('height', y.bandwidth())
+ .attr('rx', 2)
+ .style('fill', tokens.colorBrandBackground)
+ .attr('width', (d) => (shouldAnimate ? 0 : x(d.percent)));
+ bars.append('title').text((d) => `${d.label}: ${d.percent.toFixed(1)}% of visitors`);
+ if (shouldAnimate) {
+ bars.transition().duration(400).attr('width', (d) => x(d.percent));
+ }
+
+ g.selectAll('text.bar-value')
+ .data(data)
+ .enter()
+ .append('text')
+ .attr('class', 'bar-value')
+ .attr('x', (d) => x(d.percent) + 6)
+ .attr('y', (d) => (y(d.label) ?? 0) + y.bandwidth() / 2)
+ .attr('dy', '0.35em')
+ .attr('font-size', '12px')
+ .style('fill', tokens.colorNeutralForeground1)
+ .text((d) => `${d.percent.toFixed(1)}%`);
+ }, [data, animKey]);
+
+ return <svg ref={svgRef} className={styles.barSvg} role="img" aria-label={ariaLabel} />;
+};
+
+// ---------- Page ----------
+
+const GeneratedComponent = (props: { pageInput?: { data?: Record<string, unknown> } }) => {
+ const { pageInput } = props;
+ // pageInput is destructured per rules but unused on a mock dashboard.
+ void pageInput;
+ const styles = useStyles();
+
+ const thisWeek = weeklyTraffic[weeklyTraffic.length - 1];
+ const lastWeek = weeklyTraffic[weeklyTraffic.length - 2];
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <Text as="h1" size={700} weight="semibold">Website analytics</Text>
+ <Text className={styles.subtitle}>Week of {thisWeek.week} · sample data</Text>
+ </header>
+
+ <section className={styles.kpiRow} aria-label="Traffic summary">
+ <KpiCard
+ label="Visitors"
+ value={formatCompact(thisWeek.visitors)}
+ deltaPct={percentChange(thisWeek.visitors, lastWeek.visitors)}
+ higherIsBetter
+ />
+ <KpiCard
+ label="Page views"
+ value={formatCompact(thisWeek.pageViews)}
+ deltaPct={percentChange(thisWeek.pageViews, lastWeek.pageViews)}
+ higherIsBetter
+ />
+ <KpiCard
+ label="Avg. session"
+ value={formatDuration(sessionStats.avgSessionSeconds)}
+ deltaPct={sessionStats.avgSessionDeltaPct}
+ higherIsBetter
+ />
+ <KpiCard
+ label="Bounce rate"
+ value={`${sessionStats.bounceRatePct.toFixed(1)}%`}
+ deltaPct={sessionStats.bounceRateDeltaPct}
+ higherIsBetter={false}
+ />
+ </section>
+
+ <section className={styles.chartGrid} aria-label="Traffic charts">
+ <Card className={styles.wideCard}>
+ <CardHeader
+ header={<Text weight="semibold">Traffic trend</Text>}
+ description="Weekly visitors and page views, last 12 weeks"
+ />
+ <div className={styles.legend} aria-hidden="true">
+ <span className={styles.legendItem}>
+ <span className={`${styles.swatch} ${styles.swatchVisitors}`} />
+ <Text size={200}>Visitors</Text>
+ </span>
+ <span className={styles.legendItem}>
+ <span className={`${styles.swatch} ${styles.swatchPageViews}`} />
+ <Text size={200}>Page views</Text>
+ </span>
+ </div>
+ <TrafficTrendChart />
+ </Card>
+ <Card className={styles.chartCard}>
+ <CardHeader
+ header={<Text weight="semibold">Visitors by age</Text>}
+ description="Share of visitors, last 12 weeks"
+ />
+ <ShareBarChart data={ageGroups} animKey="__ppTrafficAgeAnimated" ariaLabel="Share of visitors by age group" />
+ </Card>
+ <Card className={styles.chartCard}>
+ <CardHeader
+ header={<Text weight="semibold">Top countries</Text>}
+ description="Share of visitors, last 12 weeks"
+ />
+ <ShareBarChart data={topCountries} animKey="__ppTrafficCountryAnimated" ariaLabel="Share of visitors by country" />
+ </Card>
+ </section>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/workflow-log.md b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/workflow-log.md
new file mode 100644
index 000000000..56a75418d
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/6-traffic-analytics-mock/workflow-log.md
@@ -0,0 +1,109 @@
+# Workflow Log — Eval 6: Website traffic analytics (mock data)
+
+Synthetic trace: constructed to show what a compliant attended `/genpage` create run of this prompt
+records under the current SKILL.md. It is not a captured agent session. Every command below has an
+associated result, in order, in `tool-results.json`.
+
+## Phase 0 — Working directory
+- `node 'D:/repo/plugins/model-apps/scripts/check-version.js'` → no output (plugin is current)
+- `mkdir -p 'website-traffic-analytics'` (kebab-case derived from "website traffic analytics dashboard")
+- Working directory: D:/work/website-traffic-analytics (every later command runs from this directory)
+
+## Phase 0.5 — Local-dev manifest
+- `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/website-traffic-analytics' 'website-traffic-analytics' --features charts`
+- Exit 0; wrote package.json (adds d3 and @types/d3 for the charts feature) and genpage.d.ts
+
+## Phase 1 — Plan
+
+### Interaction mode
+- `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'` → {"ok":true,"interactive":true,"reason":"default (attended)"} — attended run, questions go through AskUserQuestion
+
+### 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 check
+- `pac auth list` → one profile, active (*): [email protected]
+- Active environment: https://contoso.crm.dynamics.com (reported to user: "Working with environment: Contoso Dev")
+
+### Requirements (orchestrator asks; genpage-planner runs discovery headless)
+- AskUserQuestion: Create new page(s) or edit an existing one? → Create new page(s)
+- `pac model list-languages` → 1033 English en-US, RTL: No (English only, no localization)
+- Data source question skipped: $ARGUMENTS already states "with mock data" → Mock data
+- AskUserQuestion: Any specific requirements? → Clean and minimal design
+- Entity detection not needed (mock data — no Dataverse tables requested)
+- Connector discovery not needed: mock data, no connector source; list-connections.js was not run and the contract stays `No connector bindings.`
+- Custom API discovery not needed: no server-side operation; contract stays `No custom API bindings.`
+
+### App selection
+- `pac model list` → 2 apps: Contoso Marketing Hub (11111111-2222-4333-8444-555555555555), Field Service Lite (99999999-8888-4777-8666-555555555555)
+- AskUserQuestion: Which model-driven app should host the page? → Contoso Marketing Hub (11111111-2222-4333-8444-555555555555)
+
+### Solution selection
+- Code-only flow (mock data, no new entities, existing app) → solution selection question SKIPPED
+- Default values written to plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Plan approval
+- EnterPlanMode called with the plan: one page "Website Analytics" (traffic-dashboard.tsx), mock data, KPI row + D3 trend chart + two D3 demographic bar charts, existing app Contoso Marketing Hub
+- ExitPlanMode → approved
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/website-traffic-analytics/genpage-plan.md'` → {"ok":true,"action":"prepare","quarantinedPath":null}
+- Approved plan body saved to D:/work/website-traffic-analytics/.approved-genpage-plan.md
+- genpage-planner re-invoked with the approval outcome; it wrote genpage-plan.md (conforms to references/plan-schema.md)
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/website-traffic-analytics/genpage-plan.md' --approved '@D:/work/website-traffic-analytics/.approved-genpage-plan.md'` → ok:true, targets [traffic-dashboard.tsx], writtenHash b6a01df32403a40ffa8e9a39d26e977c51b36e45856cc91891029fef6c110378
+
+## Phase 2 — Entity creation
+- SKIPPED (mock data — `## Entity Creation Required` is the no-entity sentinel)
+- check-auth.js not run (no entity work); genpage-entity-builder not invoked
+
+## Phase 3 — App creation/selection
+- SKIPPED: existing app Contoso Marketing Hub (11111111-2222-4333-8444-555555555555) selected; no app is created
+
+## Phase 4 — RuntimeTypes
+- SKIPPED (mock data page — no Dataverse entities, so no RuntimeTypes.ts)
+
+## Phase 4.5 — Connector bindings
+- SKIPPED: plan says `No connector bindings.`; no connectors.json → Connectors: none
+
+## Phase 4.6 — Custom API bindings
+- `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api` → disabled (exit 1)
+- Plan body is exactly `No custom API bindings.` → continue with no actions.json
+
+## Phase 4.7 — Page telemetry
+- `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry` → disabled (exit 1) → Telemetry: disabled
+
+## Phase 5a — Plan validation
+- `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/website-traffic-analytics/genpage-plan.md'` → {"ok":true,"files":["traffic-dashboard.tsx"],"problems":[]}
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → fast path taken: inlined build, no Task subagent dispatched for genpage-page-builder
+- Data mode: mock; Connectors: none; Telemetry: disabled
+- Read ${PLUGIN_ROOT}/references/rules.md
+- Read sample: plugins/model-apps/samples/8-dashboard-with-charts.tsx (KPI cards + D3 charts + animation guard)
+- connectors.md, custom-api.md, data-caching.md, localization.md and page-telemetry.md not read (no bindings, Needs caching: false, English only, telemetry disabled)
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/website-traffic-analytics/traffic-dashboard.tsx'` → {"ok":true,"action":"stamp","existed":false}
+- Wrote traffic-dashboard.tsx: inline mock arrays (12 weekly points, 6 age groups, 6 countries), D3.js only for the three charts, no chart library, no icons
+- Icon check: Grep `from "@fluentui/react-icons"` in traffic-dashboard.tsx → no matches; the page imports no icons, so nothing to verify against verified-icons.txt
+- Grep `['"]?borderWidth['"]?\s*:` in traffic-dashboard.tsx → no matches
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/website-traffic-analytics/traffic-dashboard.tsx'` → {"ok":true,"problems":[]} (exit 0)
+
+## Phase 6 — Deploy
+- No connectors.json and no actions.json → no `upload --help` pre-flight needed
+- Cleared any earlier prompt.txt / agent-message.txt / page-name.txt (none existed, none was a link)
+- Wrote prompt.txt (full `## User Requirements`), agent-message.txt and page-name.txt ("Website Analytics") with the file-writing tool
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '11111111-2222-4333-8444-555555555555' --code-file 'traffic-dashboard.tsx' --name-file 'page-name.txt' --prompt-file 'prompt.txt' --model 'claude-sonnet-4.5' --agent-message-file 'agent-message.txt' --add-to-sitemap`
+- Mock data page, so the upload carries no data-sources flag and no connectors/actions files
+- Prompt scope: full page description from plan's `## User Requirements` (create)
+- Result: page-id = 33333333-4444-4555-8666-777777777777, status = success ({"ok":true,"updated":false})
+
+## Phase 7 — Browser verification
+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification
+
+## Phase 8 — Summary
+
+| Page | File | Entities | Status |
+|------|------|----------|--------|
+| Website Analytics | traffic-dashboard.tsx | mock data | Deployed |
+
+- App: Contoso Marketing Hub (11111111-2222-4333-8444-555555555555)
+- Entities created: none
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/account-metrics.tsx b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/account-metrics.tsx
new file mode 100644
index 000000000..96701322e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/account-metrics.tsx
@@ -0,0 +1,609 @@
+import * as React from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import type { TableRow, ReadableTableRow, GeneratedComponentProps } from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Card,
+ CardHeader,
+ Button,
+ Spinner,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import {
+ ArrowClockwiseRegular,
+ BuildingRegular,
+ CalendarRegular,
+ MoneyRegular,
+ PeopleTeamRegular,
+} from '@fluentui/react-icons';
+import * as d3 from 'd3';
+
+// Columns verified against RuntimeTypes.ts (generate-types --data-sources 'account').
+type AccountRow = TableRow<{
+ readonly accountid: string;
+ name?: string;
+ industrycode?: number;
+ revenue?: number;
+ numberofemployees?: number;
+ address1_city?: string;
+ readonly createdon?: string;
+}>;
+
+type ReadableAccount = ReadableTableRow<AccountRow>;
+type AccountDataApi = GeneratedComponentProps['dataApi'];
+
+interface AccountSnapshot {
+ rows: ReadableAccount[];
+ truncated: boolean;
+}
+
+interface BarDatum {
+ label: string;
+ value: number;
+}
+
+interface AccountMetrics {
+ activeCount: number;
+ totalRevenue: number;
+ averageEmployees: number;
+ newLast90Days: number;
+}
+
+interface XrmLike {
+ Navigation?: {
+ navigateTo: (pageInput: Record<string, unknown>, options?: Record<string, unknown>) => Promise<unknown>;
+ };
+}
+
+// ---------- Window cache + in-flight de-dupe (references/data-caching.md) ----------
+// Keys are scoped to this page + query so another page reading `account` never shares them.
+const CACHE_KEY = '__ppAccountMetrics_accountCache';
+const INFLIGHT_KEY = '__ppAccountMetrics_accountInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+const PAGE_SIZE = 500;
+const MAX_ACCOUNTS = 5000;
+const FORMATTED = '@OData.Community.Display.V1.FormattedValue';
+const EMPTY_SNAPSHOT: AccountSnapshot = { rows: [], truncated: false };
+
+async function fetchActiveAccounts(dataApi: AccountDataApi): Promise<AccountSnapshot> {
+ let page = await dataApi.queryTable('account', {
+ select: ['accountid', 'name', 'industrycode', 'revenue', 'numberofemployees', 'address1_city', 'createdon'],
+ filter: 'statecode eq 0',
+ orderBy: 'revenue desc',
+ pageSize: PAGE_SIZE,
+ });
+ const rows = [...(page.rows as unknown as ReadableAccount[])];
+ while (page.hasMoreRows && page.loadMoreRows && rows.length < MAX_ACCOUNTS) {
+ page = await page.loadMoreRows();
+ rows.push(...(page.rows as unknown as ReadableAccount[]));
+ }
+ return { rows, truncated: page.hasMoreRows };
+}
+
+function loadAccounts(dataApi: AccountDataApi): Promise<AccountSnapshot> {
+ const pending = winAny[INFLIGHT_KEY] as Promise<AccountSnapshot> | undefined;
+ if (pending) return pending;
+ const inflight: Promise<AccountSnapshot> = fetchActiveAccounts(dataApi)
+ .then((snapshot) => {
+ winAny[CACHE_KEY] = snapshot;
+ return snapshot;
+ })
+ // Clear only if still ours — a manual refresh may already have replaced it.
+ .finally(() => {
+ if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY];
+ });
+ winAny[INFLIGHT_KEY] = inflight;
+ return inflight;
+}
+
+// ---------- Derivations ----------
+
+function formattedValue(row: ReadableAccount, column: string): string | undefined {
+ const value = (row as unknown as Record<string, unknown>)[`${column}${FORMATTED}`];
+ return typeof value === 'string' && value ? value : undefined;
+}
+
+function toDate(value: unknown): Date | null {
+ if (value instanceof Date) return value;
+ if (typeof value !== 'string' || !value) return null;
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
+}
+
+function industryLabel(row: ReadableAccount): string {
+ return formattedValue(row, 'industrycode') ?? 'Not specified';
+}
+
+function computeMetrics(rows: ReadableAccount[], now: Date): AccountMetrics {
+ const cutoff = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
+ const withEmployees = rows.filter((r) => typeof r.numberofemployees === 'number');
+ return {
+ activeCount: rows.length,
+ totalRevenue: d3.sum(rows, (r) => r.revenue ?? 0),
+ averageEmployees: withEmployees.length ? d3.mean(withEmployees, (r) => r.numberofemployees ?? 0) ?? 0 : 0,
+ newLast90Days: rows.filter((r) => {
+ const created = toDate(r.createdon);
+ return created !== null && created >= cutoff;
+ }).length,
+ };
+}
+
+function industryBreakdown(rows: ReadableAccount[]): BarDatum[] {
+ const counts = d3.rollups(rows, (group) => group.length, industryLabel)
+ .map(([label, value]) => ({ label, value }))
+ .sort((a, b) => b.value - a.value);
+ if (counts.length <= 8) return counts;
+ const rest = d3.sum(counts.slice(7), (d) => d.value);
+ return [...counts.slice(0, 7), { label: 'All other industries', value: rest }];
+}
+
+function newAccountsByMonth(rows: ReadableAccount[], now: Date): BarDatum[] {
+ const monthKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}`;
+ const counts = d3.rollup(
+ rows.map((r) => toDate(r.createdon)).filter((d): d is Date => d !== null),
+ (group) => group.length,
+ monthKey,
+ );
+ const months: BarDatum[] = [];
+ for (let offset = 11; offset >= 0; offset -= 1) {
+ const month = new Date(now.getFullYear(), now.getMonth() - offset, 1);
+ months.push({
+ label: month.toLocaleString('en-US', { month: 'short', year: '2-digit' }),
+ value: counts.get(monthKey(month)) ?? 0,
+ });
+ }
+ return months;
+}
+
+function formatCompact(value: number): string {
+ return new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(value);
+}
+
+function openAccount(accountId: string): void {
+ const xrm = (window as unknown as { Xrm?: XrmLike }).Xrm;
+ xrm?.Navigation?.navigateTo({ pageType: 'entityrecord', entityName: 'account', entityId: accountId }, { target: 1 })
+ .catch(() => undefined);
+}
+
+// ---------- Styles ----------
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ titleBlock: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXS },
+ subtitle: { color: tokens.colorNeutralForeground3 },
+ centered: { display: 'flex', justifyContent: 'center', padding: tokens.spacingVerticalXXL },
+ kpiRow: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
+ gap: tokens.spacingHorizontalM,
+ },
+ kpiCard: { padding: tokens.spacingHorizontalL, display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXS },
+ kpiLabel: { color: tokens.colorNeutralForeground2 },
+ kpiValue: { fontSize: tokens.fontSizeHero800, fontWeight: tokens.fontWeightSemibold },
+ chartGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ gap: tokens.spacingHorizontalL,
+ '@media (max-width: 900px)': { gridTemplateColumns: 'minmax(0, 1fr)' },
+ },
+ card: { padding: tokens.spacingHorizontalL },
+ chartSvg: { width: '100%', height: '260px' },
+ emptyChart: { color: tokens.colorNeutralForeground3, padding: tokens.spacingVerticalL },
+ nameCell: { overflow: 'hidden', minWidth: 0 },
+ nameButton: {
+ display: 'block',
+ maxWidth: '100%',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ textAlign: 'start',
+ },
+});
+
+// ---------- KPI card ----------
+
+interface KpiCardProps {
+ icon: React.ReactElement;
+ label: string;
+ value: string;
+}
+
+const KpiCard = (props: KpiCardProps) => {
+ const styles = useStyles();
+ return (
+ <Card className={styles.kpiCard} aria-label={`${props.label}: ${props.value}`}>
+ <CardHeader image={props.icon} header={<Text className={styles.kpiLabel}>{props.label}</Text>} />
+ <Text className={styles.kpiValue}>{props.value}</Text>
+ </Card>
+ );
+};
+
+// ---------- D3 charts ----------
+// The window flag stores the data signature the chart last drew: the first draw animates, a remount
+// with the same data returns early, and a refresh with new data redraws without replaying the animation.
+
+function chartGuard(svgNode: SVGSVGElement, animKey: string, signature: string): { skip: boolean; animate: boolean } {
+ const w = window as unknown as Record<string, string | undefined>;
+ if (w[animKey] === signature && d3.select(svgNode).selectAll('rect.bar').size() > 0) {
+ return { skip: true, animate: false };
+ }
+ const animate = w[animKey] === undefined;
+ w[animKey] = signature;
+ return { skip: false, animate };
+}
+
+interface ChartProps {
+ data: BarDatum[];
+ animKey: string;
+ ariaLabel: string;
+ unit: string;
+}
+
+const IndustryBarChart = (props: ChartProps) => {
+ const styles = useStyles();
+ const svgRef = useRef<SVGSVGElement>(null);
+ const { data, animKey, ariaLabel, unit } = props;
+ const signature = data.map((d) => `${d.label}:${d.value}`).join('|');
+
+ useEffect(() => {
+ const node = svgRef.current;
+ if (!node) return;
+ const guard = chartGuard(node, animKey, signature);
+ if (guard.skip) return;
+ const svg = d3.select(node);
+ svg.selectAll('*').remove();
+
+ const rect = node.getBoundingClientRect();
+ const width = rect.width || 420;
+ const height = rect.height || 260;
+ const margin = { top: 4, right: 40, bottom: 4, left: 150 };
+ const innerW = width - margin.left - margin.right;
+ const innerH = height - margin.top - margin.bottom;
+ const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
+
+ const y = d3.scaleBand<string>().domain(data.map((d) => d.label)).range([0, innerH]).padding(0.25);
+ const x = d3.scaleLinear().domain([0, d3.max(data, (d) => d.value) ?? 0]).range([0, innerW]);
+
+ g.selectAll('text.bar-label')
+ .data(data)
+ .enter()
+ .append('text')
+ .attr('class', 'bar-label')
+ .attr('x', -8)
+ .attr('y', (d) => (y(d.label) ?? 0) + y.bandwidth() / 2)
+ .attr('dy', '0.35em')
+ .attr('text-anchor', 'end')
+ .attr('font-size', '12px')
+ .style('fill', tokens.colorNeutralForeground2)
+ .text((d) => (d.label.length > 22 ? `${d.label.slice(0, 21)}…` : d.label));
+
+ const bars = g.selectAll('rect.bar')
+ .data(data)
+ .enter()
+ .append('rect')
+ .attr('class', 'bar')
+ .attr('x', 0)
+ .attr('y', (d) => y(d.label) ?? 0)
+ .attr('height', y.bandwidth())
+ .attr('rx', 2)
+ .style('fill', tokens.colorBrandBackground)
+ .attr('width', (d) => (guard.animate ? 0 : x(d.value)));
+ bars.append('title').text((d) => `${d.label}: ${d.value.toLocaleString('en-US')} ${unit}`);
+ if (guard.animate) bars.transition().duration(400).attr('width', (d) => x(d.value));
+
+ g.selectAll('text.bar-value')
+ .data(data)
+ .enter()
+ .append('text')
+ .attr('class', 'bar-value')
+ .attr('x', (d) => x(d.value) + 6)
+ .attr('y', (d) => (y(d.label) ?? 0) + y.bandwidth() / 2)
+ .attr('dy', '0.35em')
+ .attr('font-size', '12px')
+ .style('fill', tokens.colorNeutralForeground1)
+ .text((d) => d.value.toLocaleString('en-US'));
+ }, [signature, animKey]);
+
+ return <svg ref={svgRef} className={styles.chartSvg} role="img" aria-label={ariaLabel} />;
+};
+
+const MonthlyColumnChart = (props: ChartProps) => {
+ const styles = useStyles();
+ const svgRef = useRef<SVGSVGElement>(null);
+ const { data, animKey, ariaLabel, unit } = props;
+ const signature = data.map((d) => `${d.label}:${d.value}`).join('|');
+
+ useEffect(() => {
+ const node = svgRef.current;
+ if (!node) return;
+ const guard = chartGuard(node, animKey, signature);
+ if (guard.skip) return;
+ const svg = d3.select(node);
+ svg.selectAll('*').remove();
+
+ const rect = node.getBoundingClientRect();
+ const width = rect.width || 420;
+ const height = rect.height || 260;
+ const margin = { top: 12, right: 12, bottom: 28, left: 36 };
+ const innerW = width - margin.left - margin.right;
+ const innerH = height - margin.top - margin.bottom;
+ const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
+
+ const x = d3.scaleBand<string>().domain(data.map((d) => d.label)).range([0, innerW]).padding(0.2);
+ const y = d3.scaleLinear().domain([0, Math.max(1, d3.max(data, (d) => d.value) ?? 0)]).nice().range([innerH, 0]);
+
+ g.append('g')
+ .attr('transform', `translate(0,${innerH})`)
+ .call(d3.axisBottom(x).tickValues(x.domain().filter((_, i) => i % 2 === 1)))
+ .style('color', tokens.colorNeutralForeground3);
+ g.append('g')
+ .call(d3.axisLeft(y).ticks(4).tickFormat(d3.format('d')))
+ .style('color', tokens.colorNeutralForeground3);
+
+ const bars = g.selectAll('rect.bar')
+ .data(data)
+ .enter()
+ .append('rect')
+ .attr('class', 'bar')
+ .attr('x', (d) => x(d.label) ?? 0)
+ .attr('width', x.bandwidth())
+ .attr('rx', 2)
+ .style('fill', tokens.colorPaletteTealBorderActive)
+ .attr('y', (d) => (guard.animate ? innerH : y(d.value)))
+ .attr('height', (d) => (guard.animate ? 0 : innerH - y(d.value)));
+ bars.append('title').text((d) => `${d.label}: ${d.value.toLocaleString('en-US')} ${unit}`);
+ if (guard.animate) {
+ bars.transition()
+ .duration(400)
+ .attr('y', (d) => y(d.value))
+ .attr('height', (d) => innerH - y(d.value));
+ }
+ }, [signature, animKey]);
+
+ return <svg ref={svgRef} className={styles.chartSvg} role="img" aria-label={ariaLabel} />;
+};
+
+// ---------- Top accounts grid ----------
+
+const topAccountColumns = [
+ createTableColumn<ReadableAccount>({
+ columnId: 'name',
+ compare: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
+ renderHeaderCell: () => 'Account',
+ renderCell: (item) => <TableCellLayout>{item.name ?? '(no name)'}</TableCellLayout>,
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'industry',
+ compare: (a, b) => industryLabel(a).localeCompare(industryLabel(b)),
+ renderHeaderCell: () => 'Industry',
+ renderCell: (item) => <TableCellLayout>{industryLabel(item)}</TableCellLayout>,
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'city',
+ compare: (a, b) => (a.address1_city ?? '').localeCompare(b.address1_city ?? ''),
+ renderHeaderCell: () => 'City',
+ renderCell: (item) => <TableCellLayout>{item.address1_city ?? '—'}</TableCellLayout>,
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'employees',
+ compare: (a, b) => (a.numberofemployees ?? 0) - (b.numberofemployees ?? 0),
+ renderHeaderCell: () => 'Employees',
+ renderCell: (item) => (
+ <TableCellLayout>{item.numberofemployees !== undefined ? item.numberofemployees.toLocaleString('en-US') : '—'}</TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableAccount>({
+ columnId: 'revenue',
+ compare: (a, b) => (a.revenue ?? 0) - (b.revenue ?? 0),
+ renderHeaderCell: () => 'Annual revenue',
+ renderCell: (item) => (
+ <TableCellLayout>{formattedValue(item, 'revenue') ?? (item.revenue !== undefined ? formatCompact(item.revenue) : '—')}</TableCellLayout>
+ ),
+ }),
+];
+
+const topAccountSizing = {
+ name: { defaultWidth: 240, minWidth: 160 },
+ industry: { defaultWidth: 180, minWidth: 120 },
+ city: { defaultWidth: 140, minWidth: 100 },
+ employees: { defaultWidth: 120, minWidth: 90 },
+ revenue: { defaultWidth: 150, minWidth: 110 },
+};
+
+const TopAccountsGrid = (props: { accounts: ReadableAccount[] }) => {
+ const styles = useStyles();
+ return (
+ <DataGrid
+ items={props.accounts}
+ columns={topAccountColumns}
+ getRowId={(item) => item.accountid}
+ sortable
+ resizableColumns
+ columnSizingOptions={topAccountSizing}
+ aria-label="Top accounts by annual revenue"
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<ReadableAccount>>
+ {({ item, rowId }) => (
+ <DataGridRow<ReadableAccount> key={rowId}>
+ {({ renderCell, columnId }) =>
+ columnId === 'name' ? (
+ <DataGridCell>
+ <TableCellLayout className={styles.nameCell}>
+ <Button
+ appearance="transparent"
+ className={styles.nameButton}
+ title={item.name}
+ aria-label={`Open account ${item.name ?? ''}`}
+ onClick={() => openAccount(item.accountid)}
+ >
+ {item.name ?? '(no name)'}
+ </Button>
+ </TableCellLayout>
+ </DataGridCell>
+ ) : (
+ <DataGridCell>{renderCell(item)}</DataGridCell>
+ )
+ }
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ );
+};
+
+// ---------- Page ----------
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // dashboard takes no page input; destructured per rules
+ const styles = useStyles();
+ const dataReady = !!dataApi;
+ const [reloadKey, setReloadKey] = useState(0);
+ const [data, setData] = useState<{ snapshot: AccountSnapshot; loading: boolean; error: string | null }>(() => {
+ const cached = winAny[CACHE_KEY] as AccountSnapshot | undefined;
+ return { snapshot: cached ?? EMPTY_SNAPSHOT, loading: cached === undefined, error: null };
+ });
+
+ useEffect(() => {
+ if (!dataReady) return;
+ const cached = winAny[CACHE_KEY] as AccountSnapshot | undefined;
+ if (cached !== undefined) {
+ if (data.snapshot !== cached || data.loading) setData({ snapshot: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ try {
+ const snapshot = await loadAccounts(dataApi);
+ if (!cancelled) setData({ snapshot, loading: false, error: null });
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load accounts.';
+ setData({ snapshot: EMPTY_SNAPSHOT, loading: false, error: message });
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // Readiness and manual refresh only — never `dataApi`, which is a new reference every render (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ // All hooks stay above the early returns below (Rule 19).
+ const rows = data.snapshot.rows;
+ const metrics = useMemo(() => computeMetrics(rows, new Date()), [rows]);
+ const industries = useMemo(() => industryBreakdown(rows), [rows]);
+ const monthly = useMemo(() => newAccountsByMonth(rows, new Date()), [rows]);
+ const topAccounts = useMemo(
+ () => rows.filter((r) => typeof r.revenue === 'number').sort((a, b) => (b.revenue ?? 0) - (a.revenue ?? 0)).slice(0, 10),
+ [rows],
+ );
+
+ const refresh = () => {
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ snapshot: data.snapshot, loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ };
+
+ if (data.loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.centered}>
+ <Spinner labelPosition="below" label="Loading account metrics…" />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <div className={styles.titleBlock}>
+ <Text as="h1" size={700} weight="semibold">Account metrics</Text>
+ <Text className={styles.subtitle}>Active accounts in this environment</Text>
+ </div>
+ <Button icon={<ArrowClockwiseRegular />} onClick={refresh}>Refresh</Button>
+ </header>
+
+ {data.error && (
+ <MessageBar intent="error">
+ <MessageBarBody>{data.error}</MessageBarBody>
+ </MessageBar>
+ )}
+ {data.snapshot.truncated && (
+ <MessageBar intent="info">
+ <MessageBarBody>Metrics cover the first {MAX_ACCOUNTS.toLocaleString('en-US')} active accounts.</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <section className={styles.kpiRow} aria-label="Account summary">
+ <KpiCard icon={<BuildingRegular />} label="Active accounts" value={metrics.activeCount.toLocaleString('en-US')} />
+ <KpiCard icon={<MoneyRegular />} label="Total annual revenue" value={formatCompact(metrics.totalRevenue)} />
+ <KpiCard icon={<PeopleTeamRegular />} label="Average employees" value={Math.round(metrics.averageEmployees).toLocaleString('en-US')} />
+ <KpiCard icon={<CalendarRegular />} label="New in last 90 days" value={metrics.newLast90Days.toLocaleString('en-US')} />
+ </section>
+
+ <section className={styles.chartGrid} aria-label="Account charts">
+ <Card className={styles.card}>
+ <CardHeader header={<Text weight="semibold">Accounts by industry</Text>} description="Active accounts per industry" />
+ {rows.length ? (
+ <IndustryBarChart data={industries} animKey="__ppAccountMetricsIndustryAnimated" ariaLabel="Active accounts by industry" unit="accounts" />
+ ) : (
+ <Text className={styles.emptyChart}>No active accounts yet.</Text>
+ )}
+ </Card>
+ <Card className={styles.card}>
+ <CardHeader header={<Text weight="semibold">New accounts by month</Text>} description="Accounts created in the last 12 months" />
+ {rows.length ? (
+ <MonthlyColumnChart data={monthly} animKey="__ppAccountMetricsMonthlyAnimated" ariaLabel="New accounts created per month over the last 12 months" unit="new accounts" />
+ ) : (
+ <Text className={styles.emptyChart}>No active accounts yet.</Text>
+ )}
+ </Card>
+ </section>
+
+ <Card className={styles.card}>
+ <CardHeader header={<Text weight="semibold">Top accounts by annual revenue</Text>} description="Select an account to open its record" />
+ {topAccounts.length ? (
+ <TopAccountsGrid accounts={topAccounts} />
+ ) : (
+ <Text className={styles.emptyChart}>No accounts have annual revenue recorded.</Text>
+ )}
+ </Card>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/agent-message.txt b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/agent-message.txt
new file mode 100644
index 000000000..dedab10af
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/agent-message.txt
@@ -0,0 +1 @@
+Created the Account Metrics Dashboard on the account table in the new Account Metrics app: KPI cards, D3 charts of accounts by industry and new accounts per month, and the top 10 accounts by annual revenue.
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/fixture.json b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/fixture.json
new file mode 100644
index 000000000..7ba862397
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/fixture.json
@@ -0,0 +1,18 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of an attended /genpage create run for eval 8, not an agent capture: pac model list returns zero apps, the maker chooses to create a new app named Account Metrics, the solution question is asked because a new app is metadata work (dominant prefix cnt, choice ContosoCore recorded in ## Environment), Phase 3 runs pac model create with --solution and --publish, and the returned app-id is the --app-id of the Phase 6 genpage-upload.js deploy of an account dashboard.",
+ "contracts": [
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 1: Plan",
+ "plugins/model-apps/agents/genpage-planner.md App Detection — 0 apps: create a new one, or cancel",
+ "plugins/model-apps/agents/genpage-planner.md Solution Selection and Dominant-prefix detection",
+ "plugins/model-apps/references/plan-schema.md ## Environment — App: create new, Solution, Publisher Prefix",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 3: App Creation/Selection — --solution and --publish are mandatory; store the new app-id for Phase 6",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 4: Generate RuntimeTypes (Conditional)",
+ "plugins/model-apps/skills/genpage/SKILL.md Phase 6: Deploy — For Dataverse entity pages (first upload — create)",
+ "plugins/model-apps/references/data-caching.md Pattern 1 — List / array cache"
+ ],
+ "expectedOutcome": "deployed",
+ "toolResults": "tool-results.json",
+ "artifacts": ["prompt.txt", "agent-message.txt", "page-name.txt"]
+}
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/genpage-plan.md b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/genpage-plan.md
new file mode 100644
index 000000000..796c5f842
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/genpage-plan.md
@@ -0,0 +1,58 @@
+# Genpage Plan
+
+## User Requirements
+Create a dashboard page with account metrics. I don't have any model-driven apps yet.
+
+## Working Directory
+D:/work/account-metrics-dashboard
+
+## Plugin Root
+D:/repo/plugins/model-apps
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- App: create new: Account Metrics
+- Languages: English (1033) only
+- Solution: ContosoCore
+- Publisher Prefix: cnt
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Account Metrics Dashboard | account-metrics.tsx | Dashboard of active-account KPIs, industry and monthly-growth charts, and top accounts by revenue | 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 light theme, KPI cards on top, charts in two columns that stack on narrow widths
+- Features: account metrics dashboard — active account count, total annual revenue, average employees, accounts created in the last 90 days; accounts by industry; new accounts per month; top 10 accounts by annual revenue with click-to-open; manual refresh
+- Accessibility: WCAG AA defaults; charts expose role="img" with aria-labels and SVG tooltips; grid rows are keyboard reachable
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Account Metrics Dashboard | 8-dashboard-with-charts.tsx | KPI cards plus D3 charts with the animation guard |
+| Account Metrics Dashboard | 9-list-with-caching.tsx | Dataverse read with window cache, in-flight de-dupe and a sized DataGrid |
+
+## Per-Page Specifications
+
+### Account Metrics Dashboard
+- **File:** account-metrics.tsx
+- **Purpose:** Dashboard of active-account KPIs, industry and monthly-growth charts, and top accounts by revenue
+- **Entities:** account
+- **Needs caching:** true
+- **Key Features:** Four KPI cards (active accounts, total annual revenue, average employees, new in last 90 days); D3 horizontal bar chart of active accounts by industry; D3 column chart of accounts created per month over the last 12 months; top 10 accounts by annual revenue in a sortable DataGrid; refresh button
+- **Components:** Card, CardHeader, Text, Button, Spinner, MessageBar, DataGrid with createTableColumn; BuildingRegular, MoneyRegular, PeopleTeamRegular, CalendarRegular, ArrowClockwiseRegular icons; D3.js for charts
+- **Layout:** Flex column root; responsive KPI grid; two-column chart grid stacking below 900px; full-width grid card; no 100vh/100vw
+- **Data Binding:** One dataApi.queryTable('account') on mount — select accountid, name, industrycode, revenue, numberofemployees, address1_city, createdon; filter statecode eq 0; order by revenue desc; page size 500 with loadMoreRows up to 5,000 rows; window cache + in-flight de-dupe keyed to this page; industry label from the industrycode FormattedValue annotation
+- **Interactions:** Selecting an account name opens the account record via Xrm.Navigation.navigateTo; column sorting and resizing; Refresh clears the cache and in-flight promise and refetches
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/page-name.txt b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/page-name.txt
new file mode 100644
index 000000000..7a9f764ce
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/page-name.txt
@@ -0,0 +1 @@
+Account Metrics Dashboard
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/prompt.txt b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/prompt.txt
new file mode 100644
index 000000000..93eb36f8a
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/prompt.txt
@@ -0,0 +1 @@
+Create a dashboard page with account metrics. I don't have any model-driven apps yet.
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/tool-results.json b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/tool-results.json
new file mode 100644
index 000000000..5422a74cf
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/tool-results.json
@@ -0,0 +1,135 @@
+[
+ { "id": "plugin-check", "command": "node 'D:/repo/plugins/model-apps/scripts/check-version.js'", "result": { "stdout": "" }, "exitCode": 0 },
+ { "id": "mkdir", "command": "mkdir -p 'account-metrics-dashboard'", "exitCode": 0 },
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/account-metrics-dashboard' 'account-metrics-dashboard' --features charts",
+ "result": { "workingDir": "D:/work/account-metrics-dashboard", "slug": "account-metrics-dashboard", "features": ["charts"], "files": { "package.json": { "wrote": true }, "genpage.d.ts": { "wrote": true } } },
+ "exitCode": 0
+ },
+ { "id": "interaction-mode", "command": "node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'", "result": { "ok": true, "interactive": true, "reason": "default (attended)" }, "exitCode": 0 },
+ { "id": "node-version", "command": "node --version", "result": { "stdout": "v20.20.2" }, "exitCode": 0 },
+ { "id": "pac-help", "command": "pac help", "result": { "stdout": "Microsoft PowerPlatform CLI\nVersion: 2.11.0" }, "exitCode": 0 },
+ {
+ "id": "pac-auth-list",
+ "command": "pac auth list",
+ "result": { "profiles": [{ "index": 1, "active": true, "kind": "UNIVERSAL", "user": "[email protected]", "environment": "Contoso Dev", "environmentUrl": "https://contoso.crm.dynamics.com/" }] },
+ "exitCode": 0
+ },
+ { "id": "ask-new-or-edit", "command": "AskUserQuestion: Create new page(s) or edit an existing one?", "result": { "answer": "Create new page(s)" } },
+ {
+ "id": "list-languages",
+ "command": "pac model list-languages",
+ "result": { "languages": [{ "lcid": 1033, "language": "English", "code": "en-US", "rtl": false }] },
+ "exitCode": 0
+ },
+ { "id": "ask-data-source", "command": "AskUserQuestion: Will the page use Dataverse entities or mock data?", "result": { "answer": "Dataverse entity: account" } },
+ { "id": "ask-requirements", "command": "AskUserQuestion: Any specific requirements?", "result": { "answer": "Account metrics dashboard" } },
+ {
+ "id": "list-tables-account",
+ "command": "pac model list-tables --search 'account'",
+ "result": { "rows": [
+ { "logicalName": "account", "type": "Standard" },
+ { "logicalName": "accountleads", "type": "Standard" },
+ { "logicalName": "adx_accountaccessright", "type": "Custom" },
+ { "logicalName": "msdyn_accountkpiitem", "type": "Custom" }
+ ], "exactMatches": ["account"] },
+ "exitCode": 0
+ },
+ {
+ "id": "list-tables-all",
+ "command": "pac model list-tables",
+ "result": {
+ "customTables": ["adx_accountaccessright", "cnt_milestone", "cnt_project", "cnt_timesheet", "msdyn_accountkpiitem", "new_importbatch"],
+ "prefixCountsExcludingSystem": { "cnt": 3, "new": 1 },
+ "detectedPrefix": "cnt",
+ "detectedTableCount": 3
+ },
+ "exitCode": 0
+ },
+ { "id": "app-list", "command": "pac model list", "result": { "apps": [] }, "exitCode": 0 },
+ {
+ "id": "ask-create-app",
+ "command": "AskUserQuestion: No model-driven apps found. Would you like to create a new one, or cancel?",
+ "result": { "options": ["Create a new app", "Cancel"], "answer": "Create a new app" }
+ },
+ { "id": "ask-app-name", "command": "AskUserQuestion: What should the new model-driven app be called?", "result": { "answer": "Account Metrics" } },
+ {
+ "id": "list-solutions",
+ "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'",
+ "result": { "status": 200, "data": { "value": [
+ { "uniquename": "ContosoCore", "friendlyname": "Contoso Core", "publisherid": { "customizationprefix": "cnt" } }
+ ] } },
+ "exitCode": 0
+ },
+ {
+ "id": "ask-solution",
+ "command": "AskUserQuestion: Your environment has 3 custom tables using prefix cnt. Which solution should the new app go in?",
+ "result": {
+ "options": [
+ "Continue in 'Contoso Core' (prefix: cnt) — matches your existing custom tables [RECOMMENDED]",
+ "Create a new solution under Default Publisher (prefix: new)",
+ "Use Default Solution (prefix: new) ⚠ different prefix from existing work"
+ ],
+ "answer": "Continue in 'Contoso Core' (prefix: cnt)"
+ }
+ },
+ { "id": "plan-approval", "command": "EnterPlanMode", "result": { "outcome": "approved" } },
+ {
+ "id": "provenance-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/account-metrics-dashboard/genpage-plan.md'",
+ "result": { "ok": true, "action": "prepare", "planPath": "D:/work/account-metrics-dashboard/genpage-plan.md", "quarantinedPath": null },
+ "exitCode": 0
+ },
+ { "id": "planner-writeback", "command": "Task genpage-planner (approved; write genpage-plan.md)", "artifact": "genpage-plan.md" },
+ {
+ "id": "provenance-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/account-metrics-dashboard/genpage-plan.md' --approved '@D:/work/account-metrics-dashboard/.approved-genpage-plan.md'",
+ "result": { "ok": true, "action": "verify", "planPath": "D:/work/account-metrics-dashboard/genpage-plan.md", "kind": "create", "targets": ["account-metrics.tsx"], "writtenHash": "687cee2e0829863a72ee0126e5c61ba3cf49d1ea1726fe77d8f1293918ca4c15" },
+ "exitCode": 0
+ },
+ {
+ "id": "app-create",
+ "command": "pac model create --name 'Account Metrics' --solution 'ContosoCore' --publish",
+ "result": { "ok": true, "name": "Account Metrics", "appId": "44444444-5555-4666-8777-888888888888", "solution": "ContosoCore", "published": true },
+ "exitCode": 0
+ },
+ {
+ "id": "generate-types",
+ "command": "pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-metrics-dashboard/RuntimeTypes.ts'",
+ "result": { "outputFile": "D:/work/account-metrics-dashboard/RuntimeTypes.ts", "tables": ["account"] },
+ "exitCode": 0
+ },
+ { "id": "gate-custom-api", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api", "result": "disabled", "exitCode": 1 },
+ { "id": "gate-telemetry", "command": "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry", "result": "disabled", "exitCode": 1 },
+ {
+ "id": "check-page-files",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/account-metrics-dashboard/genpage-plan.md'",
+ "result": { "ok": true, "workingDir": "D:/work/account-metrics-dashboard", "files": ["account-metrics.tsx"], "problems": [] },
+ "exitCode": 0
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/account-metrics-dashboard/account-metrics.tsx'",
+ "result": { "ok": true, "action": "stamp", "filePath": "D:/work/account-metrics-dashboard/account-metrics.tsx", "existed": false },
+ "exitCode": 0
+ },
+ { "id": "write-page", "command": "Write account-metrics.tsx", "artifact": "account-metrics.tsx" },
+ {
+ "id": "worker-gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-metrics-dashboard/account-metrics.tsx'",
+ "artifact": "account-metrics.tsx",
+ "result": { "ok": true, "filePath": "D:/work/account-metrics-dashboard/account-metrics.tsx", "problems": [] },
+ "exitCode": 0
+ },
+ { "id": "write-prompt", "command": "Write prompt.txt", "artifact": "prompt.txt" },
+ { "id": "write-agent-message", "command": "Write agent-message.txt", "artifact": "agent-message.txt" },
+ { "id": "write-page-name", "command": "Write page-name.txt", "artifact": "page-name.txt" },
+ {
+ "id": "upload",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '44444444-5555-4666-8777-888888888888' --code-file 'account-metrics.tsx' --name-file 'page-name.txt' --data-sources 'account' --prompt-file 'prompt.txt' --model 'claude-sonnet-4.5' --agent-message-file 'agent-message.txt' --add-to-sitemap",
+ "result": { "ok": true, "pageId": "66666666-7777-4888-8999-aaaaaaaaaaaa", "appId": "44444444-5555-4666-8777-888888888888", "updated": false },
+ "exitCode": 0
+ },
+ { "id": "ask-verify", "command": "AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright?", "result": { "answer": "Skip verification" } }
+]
diff --git a/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/workflow-log.md b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/workflow-log.md
new file mode 100644
index 000000000..22dd69b44
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/8-account-metrics-new-app/workflow-log.md
@@ -0,0 +1,132 @@
+# Workflow Log — Eval 8: Account metrics dashboard in a new app
+
+Synthetic trace: constructed to show what a compliant attended `/genpage` create run of this prompt
+records under the current SKILL.md when the environment has no model-driven apps. It is not a
+captured agent session. Every command below has an associated result, in order, in
+`tool-results.json`.
+
+## Phase 0 — Working directory
+- `node 'D:/repo/plugins/model-apps/scripts/check-version.js'` → no output (plugin is current)
+- `mkdir -p 'account-metrics-dashboard'` (kebab-case derived from "account metrics dashboard")
+- Working directory: D:/work/account-metrics-dashboard (every later command runs from this directory)
+
+## Phase 0.5 — Local-dev manifest
+- `node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/account-metrics-dashboard' 'account-metrics-dashboard' --features charts`
+- Exit 0; wrote package.json (adds d3 and @types/d3 for the charts feature) and genpage.d.ts
+
+## Phase 1 — Plan
+
+### Interaction mode
+- `node 'D:/repo/plugins/model-apps/scripts/resolve-interaction-mode.js'` → {"ok":true,"interactive":true,"reason":"default (attended)"} — attended run, questions go through AskUserQuestion
+
+### 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 check
+- `pac auth list` → one profile, active (*): [email protected]
+- Active environment: https://contoso.crm.dynamics.com (reported to user: "Working with environment: Contoso Dev")
+
+### Requirements (orchestrator asks; genpage-planner runs discovery headless)
+- AskUserQuestion: Create new page(s) or edit an existing one? → Create new page(s)
+- `pac model list-languages` → 1033 English en-US, RTL: No (English only, no localization)
+- AskUserQuestion: Will the page use Dataverse entities or mock data? → Dataverse entity: account
+- AskUserQuestion: Any specific requirements? → Account metrics dashboard
+- Connector discovery not needed: Dataverse only, no connector source; the contract stays `No connector bindings.`
+- Custom API discovery not needed: plain Dataverse reads; the contract stays `No custom API bindings.`
+
+### Entity detection
+- `pac model list-tables --search 'account'` → 4 rows (account, accountleads, adx_accountaccessright, msdyn_accountkpiitem); exact logical-name match: `account` exists
+- Plan records no entity creation required
+
+### Dominant prefix detection
+- `pac model list-tables` → Custom tables after excluding system prefixes (adx, msdyn): cnt_milestone, cnt_project, cnt_timesheet, new_importbatch
+- Dominant prefix: `cnt` (3 of 4 custom tables, 75%, at least 3 tables) → detectedPrefix = cnt
+
+### App detection
+- `pac model list` → no model-driven apps found (0 apps returned)
+- AskUserQuestion: No model-driven apps found. Would you like to create a new one, or cancel? → Create a new app
+- AskUserQuestion: What should the new model-driven app be called? → Account Metrics
+- Decision recorded for the plan: create new app "Account Metrics" (Phase 3 will run app creation)
+
+### Solution selection
+- A new app will be created, so the build needs metadata work → solution selection question asked
+- `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'`
+- Solutions query (GET /solutions, unmanaged and visible only) → status 200, 1 custom solution: ContosoCore ("Contoso Core", publisher prefix cnt)
+- Options ordered with the dominant prefix first: (1) Continue in 'Contoso Core' (prefix: cnt) — matches your existing custom tables [RECOMMENDED]; (2) Create a new solution under Default Publisher (prefix: new); (3) Use Default Solution (prefix: new) ⚠ different prefix from existing work
+- AskUserQuestion: Your environment has 3 custom tables using prefix cnt. Which solution should the new app go in? → Continue in 'Contoso Core' (prefix: cnt)
+- Recorded in plan ## Environment: `Solution: ContosoCore`, `Publisher Prefix: cnt` (matches the dominant prefix, so no mismatch warning)
+
+### Plan approval
+- EnterPlanMode called with the plan: one page "Account Metrics Dashboard" (account-metrics.tsx) on `account`, new app "Account Metrics" in solution ContosoCore, KPI cards + D3 industry and monthly charts + top-accounts grid
+- ExitPlanMode → approved
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/account-metrics-dashboard/genpage-plan.md'` → {"ok":true,"action":"prepare","quarantinedPath":null}
+- Approved plan body saved to D:/work/account-metrics-dashboard/.approved-genpage-plan.md
+- genpage-planner re-invoked with the approval outcome; it wrote genpage-plan.md (conforms to references/plan-schema.md; `App: create new: Account Metrics`)
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/account-metrics-dashboard/genpage-plan.md' --approved '@D:/work/account-metrics-dashboard/.approved-genpage-plan.md'` → ok:true, targets [account-metrics.tsx], writtenHash 687cee2e0829863a72ee0126e5c61ba3cf49d1ea1726fe77d8f1293918ca4c15
+
+## Phase 2 — Entity creation
+- SKIPPED (account exists — `## Entity Creation Required` is the no-entity sentinel)
+- check-auth.js not run (no entity work); genpage-entity-builder not invoked
+
+## Phase 3 — App creation
+- Plan decision: create new app "Account Metrics"; `Solution: ContosoCore` read from ## Environment and passed verbatim
+- Command: pac model create --name 'Account Metrics' --solution 'ContosoCore' --publish
+- Result: app created and published in solution ContosoCore; app-id = 44444444-5555-4666-8777-888888888888
+- Stored app-id 44444444-5555-4666-8777-888888888888 for Phase 6
+
+## Phase 4 — RuntimeTypes
+- `pac model genpage generate-types --data-sources 'account' --output-file 'D:/work/account-metrics-dashboard/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified account columns accountid, name, industrycode (choice), revenue, numberofemployees, address1_city, createdon, statecode
+
+## Phase 4.5 — Connector bindings
+- SKIPPED: plan says `No connector bindings.`; no connectors.json → Connectors: none
+
+## Phase 4.6 — Custom API bindings
+- `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api` → disabled (exit 1)
+- Plan body is exactly `No custom API bindings.` → continue with no actions.json
+
+## Phase 4.7 — Page telemetry
+- `node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-telemetry` → disabled (exit 1) → Telemetry: disabled
+
+## Phase 5a — Plan validation
+- `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/account-metrics-dashboard/genpage-plan.md'` → {"ok":true,"files":["account-metrics.tsx"],"problems":[]}
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → fast path taken: inlined build, no Task subagent dispatched for genpage-page-builder
+- Data mode: dataverse; Connectors: none; Telemetry: disabled
+- Read ${PLUGIN_ROOT}/references/rules.md
+- Read samples: plugins/model-apps/samples/8-dashboard-with-charts.tsx and plugins/model-apps/samples/9-list-with-caching.tsx
+- Read ${PLUGIN_ROOT}/references/data-caching.md (Needs caching: true)
+- Read genpage-plan.md and RuntimeTypes.ts
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/account-metrics-dashboard/account-metrics.tsx'` → {"ok":true,"action":"stamp","existed":false}
+- Wrote account-metrics.tsx: one queryTable('account') read behind a window cache + in-flight de-dupe with readiness-only deps, try/catch around the load, industry label from the FormattedValue annotation, D3 charts with a window animation guard, sized and sortable DataGrid, Xrm.Navigation.navigateTo to open an account
+- Icon check: Grep `from "@fluentui/react-icons"` in account-metrics.tsx, then one Grep per name in ${PLUGIN_ROOT}/references/verified-icons.txt: ArrowClockwiseRegular, BuildingRegular, CalendarRegular, MoneyRegular, PeopleTeamRegular — all present
+- Grep `['"]?borderWidth['"]?\s*:` in account-metrics.tsx → no matches
+- `node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/account-metrics-dashboard/account-metrics.tsx'` → {"ok":true,"problems":[]} (exit 0)
+
+## Phase 6 — Deploy
+- No connectors.json and no actions.json → no `upload --help` pre-flight needed
+- Cleared any earlier prompt.txt / agent-message.txt / page-name.txt (none existed, none was a link)
+- Wrote prompt.txt (full `## User Requirements`), agent-message.txt and page-name.txt ("Account Metrics Dashboard") with the file-writing tool
+- Command: `node 'D:/repo/plugins/model-apps/scripts/genpage-upload.js' --env 'https://contoso.crm.dynamics.com' --app-id '44444444-5555-4666-8777-888888888888' --code-file 'account-metrics.tsx' --name-file 'page-name.txt' --data-sources 'account' --prompt-file 'prompt.txt' --model 'claude-sonnet-4.5' --agent-message-file 'agent-message.txt' --add-to-sitemap`
+- --app-id is the app-id stored from Phase 3 (the newly created Account Metrics app)
+- Prompt scope: full page description from plan's `## User Requirements` (create)
+- Result: page-id = 66666666-7777-4888-8999-aaaaaaaaaaaa, appId = 44444444-5555-4666-8777-888888888888, status = success ({"ok":true,"updated":false})
+
+## Phase 6.5 / 6.7
+- Phase 6.5 not applicable (single page, no PAGEREF_ tokens)
+- Phase 6.7 not applicable (plan has no `## Solution Packaging` section)
+
+## Phase 7 — Browser verification
+- AskUserQuestion: Would you like to verify the page(s) in the browser using Playwright? → Skip verification
+
+## Phase 8 — Summary
+
+| Page | File | Entities | Status |
+|------|------|----------|--------|
+| Account Metrics Dashboard | account-metrics.tsx | account | Deployed |
+
+- App: Account Metrics (44444444-5555-4666-8777-888888888888) — created in this run in solution ContosoCore
+- Entities created: none
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/RuntimeTypes.ts
new file mode 100644
index 000000000..c4c1fb036
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/RuntimeTypes.ts
@@ -0,0 +1,94 @@
+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
+export interface TableRegistrations extends BaseTableRegistrations {
+ "cr_milestone": cr_milestone,
+ "cr_project": cr_project,
+}
+export interface EnumRegistrations extends BaseEnumRegistrations {
+ "cr_milestone-cr_status": cr_milestone_cr_status,
+ "cr_milestone-statecode": cr_milestone_statecode,
+ "cr_milestone-statuscode": cr_milestone_statuscode,
+ "cr_project-cr_status": cr_project_cr_status,
+ "cr_project-statecode": cr_project_statecode,
+ "cr_project-statuscode": cr_project_statuscode,
+}
+export type cr_milestone = TableRow<{
+ // Primary Key Column
+ readonly cr_milestoneid: string,
+ _cr_project_value: `/cr_project(${string})`,
+ cr_duedate: Date,
+ cr_name: string,
+ cr_percentcomplete: number,
+ readonly cr_projectname: string,
+ cr_status: cr_milestone_cr_status,
+ 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_milestone_statecode,
+ statuscode: cr_milestone_statuscode,
+}>
+export type cr_project = TableRow<{
+ // Primary Key Column
+ readonly cr_projectid: string,
+ cr_budget: number,
+ readonly cr_budget_base: number,
+ cr_manager: string,
+ cr_name: string,
+ cr_startdate: Date,
+ cr_status: cr_project_cr_status,
+ cr_targetdate: Date,
+ readonly createdbyname: string,
+ readonly createdbyyominame: string,
+ readonly createdonbehalfbyname: string,
+ readonly createdonbehalfbyyominame: string,
+ readonly exchangerate: number,
+ readonly modifiedbyname: string,
+ readonly modifiedbyyominame: string,
+ readonly modifiedonbehalfbyname: string,
+ readonly modifiedonbehalfbyyominame: string,
+ readonly owningbusinessunitname: string,
+ statecode: cr_project_statecode,
+ statuscode: cr_project_statuscode,
+ readonly _transactioncurrencyid_value: `/transactioncurrency(${string})`,
+ readonly transactioncurrencyidname: string,
+}>
+
+const enum cr_milestone_cr_status {
+"Not Started" = 100000000,
+"In Progress" = 100000001,
+"Completed" = 100000002,
+"Blocked" = 100000003,
+}
+const enum cr_milestone_statecode {
+"Active" = 0,
+"Inactive" = 1,
+}
+const enum cr_milestone_statuscode {
+"Active" = 1,
+"Inactive" = 2,
+}
+const enum cr_project_cr_status {
+"Planning" = 100000000,
+"Active" = 100000001,
+"On Hold" = 100000002,
+"Completed" = 100000003,
+}
+const enum cr_project_statecode {
+"Active" = 0,
+"Inactive" = 1,
+}
+const enum cr_project_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/9-project-tracker-new-entities/agent-message.txt b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/agent-message.txt
new file mode 100644
index 000000000..2ed1a4785
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/agent-message.txt
@@ -0,0 +1 @@
+Project tracker over the new cr_project and cr_milestone tables: portfolio summary tiles (active projects, open, due-soon and overdue milestones), searchable project cards with status badges and milestone progress, and a sortable milestone grid for the selected project with All / Open / Overdue tabs. Milestones are grouped by their cr_project lookup; rows open their Dataverse records; window cache with in-flight de-dupe and a refresh button.
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/fixture.json b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/fixture.json
new file mode 100644
index 000000000..a95372010
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/fixture.json
@@ -0,0 +1,25 @@
+{
+ "contractVersion": 2,
+ "provenance": "synthetic",
+ "description": "Constructed trace of a compliant attended create run for eval 9, not an agent capture. Two new related tables (cr_project, and cr_milestone with a cr_project lookup) are confirmed absent, 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 realistic rows whose milestones bind their projects through the $parent/match convention. One Dataverse page is uploaded with both tables as data sources. 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/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/9-project-tracker-new-entities/genpage-entity-creation-log.md b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/genpage-entity-creation-log.md
new file mode 100644
index 000000000..c0aeb3b0e
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/genpage-entity-creation-log.md
@@ -0,0 +1,82 @@
+# Entity Creation Log
+
+## Environment
+- URL: https://contoso.crm.dynamics.com
+- Solution: ContosoProjects
+- Publisher Prefix: cr
+
+## Created Tables
+
+### Project
+- Schema Name: cr_Project
+- Resolved Full Name: cr_project
+- Metadata ID: n/a (SDK does not surface metadata ids)
+
+### Milestone
+- Schema Name: cr_Milestone
+- Resolved Full Name: cr_milestone
+- Metadata ID: n/a (SDK does not surface metadata ids)
+
+## Created Columns
+
+| Table | Display Name | Schema Name | Resolved Full Name | Metadata ID |
+|-------|--------------|-------------|--------------------|-------------|
+| cr_project | Project Manager | cr_Manager | cr_manager | n/a |
+| cr_project | Start Date | cr_StartDate | cr_startdate | n/a |
+| cr_project | Target Date | cr_TargetDate | cr_targetdate | n/a |
+| cr_project | Budget | cr_Budget | cr_budget | n/a |
+| cr_project | Status | cr_Status | cr_status | n/a |
+| cr_milestone | Due Date | cr_DueDate | cr_duedate | n/a |
+| cr_milestone | Percent Complete | cr_PercentComplete | cr_percentcomplete | n/a |
+| cr_milestone | Status | cr_Status | cr_status | n/a |
+
+## Created Relationships
+
+| Type | From | To | Lookup Schema Name | Resolved Full Name |
+|------|------|-----|--------------------|-------------------|
+| 1:N | cr_project | cr_milestone | cr_Project | cr_project |
+
+- Relationship Schema Name: cr_project_cr_milestone
+- Order: cr_project → cr_milestone → 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/project-tracker/provision-input.json --apply
+node "${PLUGIN_ROOT}/scripts/provision-entities.js" --env "$ENV_URL" --input @D:/work/project-tracker/provision-input.json --apply --sample-data
+```
+
+## Sample Data
+
+The user confirmed sample data ("Yes, add sample data"), which the prompt had asked for. Rows were
+seeded by the `--sample-data` run above; each milestone binds its parent project with
+`"$parent": { "entity": "cr_Project", "match": { "cr_name": "<project name>" } }`, so the SDK created
+the projects first and wired every `cr_project` lookup to the matching row.
+
+| Table | Records |
+|-------|---------|
+| cr_project | 4 |
+| cr_milestone | 12 |
+
+### Created Record IDs (cr_project)
+
+- 44444444-0000-4000-8000-000000000001 — Contoso Website Redesign (Active; Avery Chen; 2026-07-06 → 2026-12-18; 185,000)
+- 44444444-0000-4000-8000-000000000002 — Warehouse Scanner Rollout (On Hold; Priya Natarajan; 2026-08-03 → 2027-02-26; 92,000)
+- 44444444-0000-4000-8000-000000000003 — Customer Portal Migration (Planning; Diego Ramirez; 2026-10-19 → 2027-04-30; 240,000)
+- 44444444-0000-4000-8000-000000000004 — Q3 Sales Enablement Program (Completed; Hannah Okafor; 2026-06-01 → 2026-09-30; 38,500)
+
+### Created Record IDs (cr_milestone)
+
+- 55555555-0000-4000-8000-000000000001 — Discovery and stakeholder interviews → Contoso Website Redesign (Completed, 100%, due 2026-07-31)
+- 55555555-0000-4000-8000-000000000002 — Design system and wireframes approved → Contoso Website Redesign (Completed, 100%, due 2026-09-25)
+- 55555555-0000-4000-8000-000000000003 — Content migration complete → Contoso Website Redesign (In Progress, 45%, due 2026-11-13)
+- 55555555-0000-4000-8000-000000000004 — Launch and DNS cutover → Contoso Website Redesign (Not Started, 0%, due 2026-12-18)
+- 55555555-0000-4000-8000-000000000005 — Pilot at Redmond distribution center → Warehouse Scanner Rollout (Completed, 100%, due 2026-09-11)
+- 55555555-0000-4000-8000-000000000006 — Handheld device procurement → Warehouse Scanner Rollout (Blocked, 70%, due 2026-10-02)
+- 55555555-0000-4000-8000-000000000007 — Regional rollout wave 1 → Warehouse Scanner Rollout (In Progress, 10%, due 2026-12-04)
+- 55555555-0000-4000-8000-000000000008 — Requirements sign-off → Customer Portal Migration (In Progress, 20%, due 2026-11-06)
+- 55555555-0000-4000-8000-000000000009 — Identity provider integration → Customer Portal Migration (Not Started, 0%, due 2027-01-22)
+- 55555555-0000-4000-8000-000000000010 — Curriculum finalized → Q3 Sales Enablement Program (Completed, 100%, due 2026-06-26)
+- 55555555-0000-4000-8000-000000000011 — Regional workshops delivered → Q3 Sales Enablement Program (Completed, 100%, due 2026-09-18)
+- 55555555-0000-4000-8000-000000000012 — Certification results published → Q3 Sales Enablement Program (Completed, 100%, due 2026-09-30)
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/genpage-plan.md b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/genpage-plan.md
new file mode 100644
index 000000000..7e84a0806
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/genpage-plan.md
@@ -0,0 +1,105 @@
+# Genpage Plan
+
+## User Requirements
+Build a project tracker page. I need new cr_project and cr_milestone entities with sample data to test the page.
+
+## Working Directory
+D:/work/project-tracker
+
+## 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: ContosoProjects
+- Publisher Prefix: cr
+
+## Pages
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Project Tracker | project-tracker.tsx | Track projects and their milestones: portfolio summary, selectable project list, and a milestone grid for the selected project | cr_project, cr_milestone |
+
+## Entity Creation Required
+
+### project
+[The full logical name is constructed by the entity-builder as `cr_project`. Display name: "Project".]
+
+- Display Name: Project
+- Display Plural: Projects
+- Primary Name Suffix: name
+- Columns:
+
+ | Suffix | Type | Required | Notes |
+ |--------|------|----------|-------|
+ | manager | string | yes | Project manager display name (max 100) |
+ | startdate | datetime | yes | Date only — planned start |
+ | targetdate | datetime | yes | Date only — planned finish |
+ | budget | money | no | Approved budget |
+- Choice Columns:
+
+ | Column Suffix | Options |
+ |---------------|---------|
+ | status | Planning (100000000), Active (100000001), On Hold (100000002), Completed (100000003) |
+- Relationships:
+
+ | Type | Related Table | Lookup Suffix | Cascade |
+ |------|---------------|---------------|---------|
+ | none | none | none | none |
+
+### milestone
+[The full logical name is constructed by the entity-builder as `cr_milestone`. Display name: "Milestone".]
+
+- Display Name: Milestone
+- Display Plural: Milestones
+- Primary Name Suffix: name
+- Columns:
+
+ | Suffix | Type | Required | Notes |
+ |--------|------|----------|-------|
+ | duedate | datetime | yes | Date only — milestone due date |
+ | percentcomplete | int | no | 0-100 |
+- Choice Columns:
+
+ | Column Suffix | Options |
+ |---------------|---------|
+ | status | Not Started (100000000), In Progress (100000001), Completed (100000002), Blocked (100000003) |
+- Relationships:
+
+ | Type | Related Table | Lookup Suffix | Cascade |
+ |------|---------------|---------------|---------|
+ | 1:N lookup | project | project | RemoveLink |
+
+## Existing Entities
+None
+
+## Connector Bindings
+No connector bindings.
+
+## Custom API Bindings
+No custom API bindings.
+
+## Design Preferences
+- Styling: Fluent UI V9 tokens; status shown as colored badges (project: Planning / Active / On Hold / Completed; milestone: Not Started / In Progress / Completed / Blocked); overdue milestones flagged with a warning icon and danger-colored date
+- Features: portfolio summary tiles (active projects, open milestones, due in the next 30 days, overdue); project search by name or manager; project cards with milestone progress; milestone grid filtered to All / Open / Overdue; refresh button; open project and milestone records
+- Accessibility: WCAG AA; keyboard-reachable project cards and grid actions; every icon-only button has an aria-label
+- Sample data: realistic projects and milestones (not lorem ipsum); every milestone belongs to a project through the cr_milestone → cr_project lookup
+
+## Relevant Samples
+| Page | Sample | Reason |
+|------|--------|--------|
+| Project Tracker | 9-list-with-caching.tsx | Dataverse list with window cache + in-flight de-dupe, DataGrid with createTableColumn and column sizing |
+
+## Per-Page Specifications
+
+### Project Tracker
+- **File:** project-tracker.tsx
+- **Purpose:** Track projects and their milestones: portfolio summary, selectable project list, and a milestone grid for the selected project
+- **Entities:** cr_project, cr_milestone
+- **Needs caching:** true
+- **Key Features:** Summary tiles (active projects, open milestones, due in the next 30 days, overdue); project list searchable by name or manager, each card showing status badge, manager, target date and milestone progress; selecting a project shows its details (dates, budget, progress) and its milestones in a sortable grid with All / Open / Overdue tabs; overdue = due before today and not Completed; refresh clears the cache and reloads
+- **Components:** Fluent UI V9 — Card, Badge, ProgressBar, SearchBox, TabList/Tab, DataGrid (createTableColumn, sortable, resizableColumns + columnSizingOptions), Button, Spinner, MessageBar, Text; icons BriefcaseRegular, PersonRegular, CalendarLtrRegular, FlagRegular, WarningRegular, OpenRegular, ArrowClockwiseRegular (unsized, verified)
+- **Layout:** Flex-column root; header with title and refresh action opposite; responsive summary tile grid (4 → 2 → 1 columns); two-pane body (project list left, selected project + milestones right) that stacks below 900px; only the list and grid panes scroll
+- **Data Binding:** One Promise.all of queryTable("cr_project") selecting cr_projectid, cr_name, cr_manager, cr_startdate, cr_targetdate, cr_budget, cr_status and queryTable("cr_milestone") selecting cr_milestoneid, cr_name, cr_duedate, cr_percentcomplete, cr_status, _cr_project_value; results read via .rows; milestones grouped by the _cr_project_value GUID and the project label read from its @OData.Community.Display.V1.FormattedValue annotation; single batched setData; window cache + in-flight de-dupe keyed by page (`__ppProjectTracker_…`), readiness-gated effect deps
+- **Interactions:** Click a project card to select it (first project selected by default); search filters cards; tabs filter milestones; grid columns sort; "Open project" / "Open milestone" use Xrm.Navigation.navigateTo with pageType "entityrecord"; refresh evicts cache + in-flight promise and refetches
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/page-name.txt b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/page-name.txt
new file mode 100644
index 000000000..2b96f88ff
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/page-name.txt
@@ -0,0 +1 @@
+Project Tracker
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/project-tracker.tsx b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/project-tracker.tsx
new file mode 100644
index 000000000..7cf26e009
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/project-tracker.tsx
@@ -0,0 +1,809 @@
+import { useEffect, useMemo, useState } from 'react';
+import type {
+ ReadableTableRow,
+ GeneratedComponentProps,
+ cr_project,
+ cr_milestone,
+} from './RuntimeTypes';
+import {
+ makeStyles,
+ mergeClasses,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ Badge,
+ ProgressBar,
+ SearchBox,
+ Card,
+ TabList,
+ Tab,
+ MessageBar,
+ MessageBarBody,
+ DataGrid,
+ DataGridHeader,
+ DataGridHeaderCell,
+ DataGridBody,
+ DataGridRow,
+ DataGridCell,
+ TableCellLayout,
+ createTableColumn,
+} from '@fluentui/react-components';
+import type { TableColumnDefinition } from '@fluentui/react-components';
+import {
+ ArrowClockwiseRegular,
+ BriefcaseRegular,
+ CalendarLtrRegular,
+ FlagRegular,
+ OpenRegular,
+ PersonRegular,
+ WarningRegular,
+} from '@fluentui/react-icons';
+
+type ReadableProject = ReadableTableRow<cr_project>;
+type ReadableMilestone = ReadableTableRow<cr_milestone>;
+
+type BadgeColor = 'brand' | 'danger' | 'informative' | 'subtle' | 'success' | 'warning';
+type MilestoneView = 'all' | 'open' | 'overdue';
+
+// ── Choice codes (verified against RuntimeTypes cr_project_cr_status / cr_milestone_cr_status) ──
+const PROJECT_PLANNING = 100000000;
+const PROJECT_ACTIVE = 100000001;
+const PROJECT_ON_HOLD = 100000002;
+const PROJECT_COMPLETED = 100000003;
+
+const MILESTONE_NOT_STARTED = 100000000;
+const MILESTONE_IN_PROGRESS = 100000001;
+const MILESTONE_COMPLETED = 100000002;
+const MILESTONE_BLOCKED = 100000003;
+
+const PROJECT_STATUS: Record<number, { label: string; color: BadgeColor }> = {
+ [PROJECT_PLANNING]: { label: 'Planning', color: 'informative' },
+ [PROJECT_ACTIVE]: { label: 'Active', color: 'brand' },
+ [PROJECT_ON_HOLD]: { label: 'On Hold', color: 'warning' },
+ [PROJECT_COMPLETED]: { label: 'Completed', color: 'success' },
+};
+
+const MILESTONE_STATUS: Record<number, { label: string; color: BadgeColor }> = {
+ [MILESTONE_NOT_STARTED]: { label: 'Not Started', color: 'subtle' },
+ [MILESTONE_IN_PROGRESS]: { label: 'In Progress', color: 'brand' },
+ [MILESTONE_COMPLETED]: { label: 'Completed', color: 'success' },
+ [MILESTONE_BLOCKED]: { label: 'Blocked', color: 'danger' },
+};
+
+const FORMATTED = '@OData.Community.Display.V1.FormattedValue';
+const DUE_SOON_DAYS = 30;
+
+// ── Window cache + in-flight de-dupe (references/data-caching.md, Pattern 1) ──
+// Keys are scoped to this page so another page querying cr_project with a different
+// select can never read these rows.
+const CACHE_KEY = '__ppProjectTracker_projectMilestoneCache';
+const INFLIGHT_KEY = '__ppProjectTracker_projectMilestoneInflight';
+const winAny = window as unknown as Record<string, unknown>;
+
+interface TrackerData {
+ projects: ReadableProject[];
+ milestones: ReadableMilestone[];
+}
+
+interface ProjectStats {
+ total: number;
+ completed: number;
+ overdue: number;
+ progress: number;
+}
+
+interface TrackerState extends TrackerData {
+ loading: boolean;
+ error: string | null;
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function loadTracker(dataApi: GeneratedComponentProps['dataApi']): Promise<TrackerData> {
+ // Both reads in one round of Promise.all so the page settles with a single setData.
+ return Promise.all([
+ dataApi.queryTable('cr_project', {
+ select: ['cr_projectid', 'cr_name', 'cr_manager', 'cr_startdate', 'cr_targetdate', 'cr_budget', 'cr_status'],
+ orderBy: 'cr_targetdate asc',
+ pageSize: 250,
+ }),
+ dataApi.queryTable('cr_milestone', {
+ select: ['cr_milestoneid', 'cr_name', 'cr_duedate', 'cr_percentcomplete', 'cr_status', '_cr_project_value'],
+ orderBy: 'cr_duedate asc',
+ pageSize: 500,
+ }),
+ ]).then(([projectResult, milestoneResult]) => ({
+ projects: projectResult.rows as ReadableProject[],
+ milestones: milestoneResult.rows as ReadableMilestone[],
+ }));
+}
+
+function formatted(row: object, field: string): string {
+ const value = (row as Record<string, unknown>)[`${field}${FORMATTED}`];
+ return typeof value === 'string' ? value : '';
+}
+
+// A read lookup carries the parent GUID; the writable form is "/cr_project(<guid>)". Normalize both.
+function lookupKey(value: unknown): string {
+ if (typeof value !== 'string') return '';
+ const wrapped = /\(([0-9a-fA-F-]{36})\)/.exec(value);
+ return (wrapped ? wrapped[1] : value).toLowerCase();
+}
+
+// Date-only columns arrive as "YYYY-MM-DD"; parse them as local dates so they never shift a day.
+function toDate(value: unknown): Date | null {
+ if (value instanceof Date) return isNaN(value.getTime()) ? null : value;
+ if (typeof value !== 'string' || !value) return null;
+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ const parsed = dateOnly
+ ? new Date(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]))
+ : new Date(value);
+ return isNaN(parsed.getTime()) ? null : parsed;
+}
+
+function formatDate(value: unknown): string {
+ const date = toDate(value);
+ return date ? date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '—';
+}
+
+function startOfToday(): Date {
+ const today = new Date();
+ today.setHours(0, 0, 0, 0);
+ return today;
+}
+
+function isMilestoneOverdue(milestone: ReadableMilestone, today: Date): boolean {
+ if (Number(milestone.cr_status) === MILESTONE_COMPLETED) return false;
+ const due = toDate(milestone.cr_duedate);
+ return due !== null && due.getTime() < today.getTime();
+}
+
+function isMilestoneDueSoon(milestone: ReadableMilestone, today: Date): boolean {
+ if (Number(milestone.cr_status) === MILESTONE_COMPLETED) return false;
+ const due = toDate(milestone.cr_duedate);
+ if (!due) return false;
+ const days = (due.getTime() - today.getTime()) / 86400000;
+ return days >= 0 && days <= DUE_SOON_DAYS;
+}
+
+function projectStatus(project: ReadableProject): { label: string; color: BadgeColor } {
+ const known = PROJECT_STATUS[Number(project.cr_status)];
+ return { label: formatted(project, 'cr_status') || known?.label || 'Unknown', color: known?.color ?? 'subtle' };
+}
+
+function milestoneStatus(milestone: ReadableMilestone): { label: string; color: BadgeColor } {
+ const known = MILESTONE_STATUS[Number(milestone.cr_status)];
+ return { label: formatted(milestone, 'cr_status') || known?.label || 'Unknown', color: known?.color ?? 'subtle' };
+}
+
+function computeStats(milestones: ReadableMilestone[], today: Date): ProjectStats {
+ const total = milestones.length;
+ const completed = milestones.filter((m) => Number(m.cr_status) === MILESTONE_COMPLETED).length;
+ const overdue = milestones.filter((m) => isMilestoneOverdue(m, today)).length;
+ const percentSum = milestones.reduce((sum, m) => sum + Math.min(100, Math.max(0, Number(m.cr_percentcomplete ?? 0))), 0);
+ return { total, completed, overdue, progress: total === 0 ? 0 : percentSum / (total * 100) };
+}
+
+function openRecord(entityName: 'cr_project' | 'cr_milestone', entityId: string) {
+ const xrm = (window as unknown as {
+ Xrm?: { Navigation?: { navigateTo: (pageInput: Record<string, unknown>) => unknown } };
+ }).Xrm;
+ xrm?.Navigation?.navigateTo({ pageType: 'entityrecord', entityName, entityId });
+}
+
+function buildMilestoneColumns(today: Date): TableColumnDefinition<ReadableMilestone>[] {
+ return [
+ createTableColumn<ReadableMilestone>({
+ columnId: 'name',
+ compare: (a, b) => (a.cr_name ?? '').localeCompare(b.cr_name ?? ''),
+ renderHeaderCell: () => 'Milestone',
+ renderCell: (item) => (
+ <TableCellLayout media={<FlagRegular />} truncate title={item.cr_name ?? ''}>
+ {item.cr_name ?? '—'}
+ </TableCellLayout>
+ ),
+ }),
+ createTableColumn<ReadableMilestone>({
+ columnId: 'duedate',
+ compare: (a, b) => (toDate(a.cr_duedate)?.getTime() ?? 0) - (toDate(b.cr_duedate)?.getTime() ?? 0),
+ renderHeaderCell: () => 'Due date',
+ renderCell: (item) => <DueDateCell milestone={item} today={today} />,
+ }),
+ createTableColumn<ReadableMilestone>({
+ columnId: 'status',
+ compare: (a, b) => Number(a.cr_status) - Number(b.cr_status),
+ renderHeaderCell: () => 'Status',
+ renderCell: (item) => {
+ const status = milestoneStatus(item);
+ return (
+ <TableCellLayout>
+ <Badge appearance="tint" color={status.color}>{status.label}</Badge>
+ </TableCellLayout>
+ );
+ },
+ }),
+ createTableColumn<ReadableMilestone>({
+ columnId: 'progress',
+ compare: (a, b) => Number(a.cr_percentcomplete ?? 0) - Number(b.cr_percentcomplete ?? 0),
+ renderHeaderCell: () => 'Progress',
+ renderCell: (item) => <ProgressCell percent={Number(item.cr_percentcomplete ?? 0)} />,
+ }),
+ createTableColumn<ReadableMilestone>({
+ columnId: 'open',
+ renderHeaderCell: () => '',
+ renderCell: (item) => (
+ <Button
+ appearance="subtle"
+ icon={<OpenRegular />}
+ aria-label={`Open milestone ${item.cr_name ?? ''}`}
+ onClick={() => openRecord('cr_milestone', item.cr_milestoneid)}
+ />
+ ),
+ }),
+ ];
+}
+
+// ── Styles ────────────────────────────────────────────────────────────────────
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ height: '100%',
+ boxSizing: 'border-box',
+ '@media (max-width: 600px)': {
+ padding: tokens.spacingHorizontalM,
+ },
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: tokens.spacingHorizontalM,
+ flexWrap: 'wrap',
+ },
+ titleBlock: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ },
+ subtle: {
+ color: tokens.colorNeutralForeground3,
+ },
+ summary: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
+ gap: tokens.spacingHorizontalM,
+ '@media (max-width: 1024px)': {
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ },
+ '@media (max-width: 480px)': {
+ gridTemplateColumns: '1fr',
+ },
+ },
+ tile: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalM,
+ padding: tokens.spacingHorizontalM,
+ borderRadius: tokens.borderRadiusLarge,
+ backgroundColor: tokens.colorNeutralBackground2,
+ },
+ tileIcon: {
+ display: 'flex',
+ fontSize: tokens.fontSizeBase600,
+ color: tokens.colorBrandForeground1,
+ },
+ tileIconDanger: {
+ color: tokens.colorPaletteRedForeground1,
+ },
+ tileText: {
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ body: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(260px, 1fr) minmax(0, 2fr)',
+ gap: tokens.spacingHorizontalL,
+ flex: 1,
+ minHeight: 0,
+ '@media (max-width: 900px)': {
+ gridTemplateColumns: '1fr',
+ },
+ },
+ pane: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ minHeight: 0,
+ minWidth: 0,
+ },
+ projectList: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalS,
+ overflowY: 'auto',
+ minHeight: 0,
+ paddingRight: tokens.spacingHorizontalXS,
+ },
+ projectCard: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalS,
+ cursor: 'pointer',
+ },
+ projectCardSelected: {
+ outlineStyle: 'solid',
+ outlineWidth: tokens.strokeWidthThick,
+ outlineColor: tokens.colorBrandStroke1,
+ },
+ cardTitleRow: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: tokens.spacingHorizontalS,
+ },
+ cardTitle: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ minWidth: 0,
+ },
+ metaRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ color: tokens.colorNeutralForeground3,
+ flexWrap: 'wrap',
+ },
+ detail: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalL,
+ borderRadius: tokens.borderRadiusLarge,
+ backgroundColor: tokens.colorNeutralBackground1,
+ boxShadow: tokens.shadow4,
+ minHeight: 0,
+ minWidth: 0,
+ },
+ detailFacts: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
+ gap: tokens.spacingHorizontalM,
+ '@media (max-width: 768px)': {
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ },
+ },
+ fact: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalXXS,
+ },
+ gridScroll: {
+ overflow: 'auto',
+ minHeight: 0,
+ flex: 1,
+ },
+ dateCell: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalXS,
+ },
+ overdue: {
+ color: tokens.colorPaletteRedForeground1,
+ fontWeight: tokens.fontWeightSemibold,
+ },
+ progressCell: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalS,
+ width: '100%',
+ },
+ progressBar: {
+ flex: 1,
+ },
+ empty: {
+ padding: tokens.spacingVerticalXL,
+ textAlign: 'center',
+ color: tokens.colorNeutralForeground3,
+ },
+ spinnerWrap: {
+ display: 'flex',
+ justifyContent: 'center',
+ padding: tokens.spacingVerticalXXL,
+ },
+});
+
+// ── Sub-components ────────────────────────────────────────────────────────────
+
+function SummaryTile(props: { label: string; value: number; icon: JSX.Element; danger?: boolean }) {
+ const styles = useStyles();
+ return (
+ <div className={styles.tile}>
+ <span className={mergeClasses(styles.tileIcon, props.danger && styles.tileIconDanger)} aria-hidden="true">
+ {props.icon}
+ </span>
+ <div className={styles.tileText}>
+ <Text size={600} weight="semibold">{props.value}</Text>
+ <Text size={200} className={styles.subtle}>{props.label}</Text>
+ </div>
+ </div>
+ );
+}
+
+function ProjectCard(props: {
+ project: ReadableProject;
+ stats: ProjectStats;
+ selected: boolean;
+ onSelect: (projectId: string) => void;
+}) {
+ const styles = useStyles();
+ const { project, stats, selected, onSelect } = props;
+ const status = projectStatus(project);
+ return (
+ <Card
+ className={mergeClasses(styles.projectCard, selected && styles.projectCardSelected)}
+ onClick={() => onSelect(project.cr_projectid)}
+ aria-current={selected ? 'true' : undefined}
+ aria-label={`${project.cr_name ?? 'Project'}, ${status.label}`}
+ >
+ <div className={styles.cardTitleRow}>
+ <Text weight="semibold" className={styles.cardTitle} title={project.cr_name ?? ''}>
+ {project.cr_name ?? '—'}
+ </Text>
+ <Badge appearance="filled" color={status.color}>{status.label}</Badge>
+ </div>
+ <div className={styles.metaRow}>
+ <PersonRegular aria-hidden="true" />
+ <Text size={200}>{project.cr_manager ?? 'Unassigned'}</Text>
+ <CalendarLtrRegular aria-hidden="true" />
+ <Text size={200}>Target {formatDate(project.cr_targetdate)}</Text>
+ </div>
+ <ProgressBar
+ value={stats.progress}
+ thickness="large"
+ color={stats.overdue > 0 ? 'error' : 'brand'}
+ aria-label={`${Math.round(stats.progress * 100)}% complete`}
+ />
+ <Text size={200} className={styles.subtle}>
+ {stats.completed} of {stats.total} milestones complete
+ {stats.overdue > 0 ? ` · ${stats.overdue} overdue` : ''}
+ </Text>
+ </Card>
+ );
+}
+
+function DueDateCell(props: { milestone: ReadableMilestone; today: Date }) {
+ const styles = useStyles();
+ const overdue = isMilestoneOverdue(props.milestone, props.today);
+ return (
+ <TableCellLayout>
+ <span className={mergeClasses(styles.dateCell, overdue && styles.overdue)}>
+ {overdue ? <WarningRegular aria-label="Overdue" /> : <CalendarLtrRegular aria-hidden="true" />}
+ {formatDate(props.milestone.cr_duedate)}
+ </span>
+ </TableCellLayout>
+ );
+}
+
+function ProgressCell(props: { percent: number }) {
+ const styles = useStyles();
+ const percent = Math.min(100, Math.max(0, props.percent));
+ return (
+ <TableCellLayout>
+ <div className={styles.progressCell}>
+ <ProgressBar
+ className={styles.progressBar}
+ value={percent / 100}
+ color={percent === 100 ? 'success' : 'brand'}
+ aria-label={`${percent}% complete`}
+ />
+ <Text size={200}>{percent}%</Text>
+ </div>
+ </TableCellLayout>
+ );
+}
+
+// ── Component ─────────────────────────────────────────────────────────────────
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ void pageInput; // tracker list page takes no input; destructured per rules
+ const styles = useStyles();
+
+ const [data, setData] = useState<TrackerState>(() => {
+ const cached = winAny[CACHE_KEY] as TrackerData | undefined;
+ return {
+ projects: cached?.projects ?? [],
+ milestones: cached?.milestones ?? [],
+ loading: cached === undefined,
+ error: null,
+ };
+ });
+ const [reloadKey, setReloadKey] = useState(0);
+ const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
+ const [search, setSearch] = useState('');
+ const [view, setView] = useState<MilestoneView>('all');
+
+ const dataReady = !!dataApi;
+
+ useEffect(() => {
+ if (!dataReady) return; // wait until the host hands us the DataAPI
+
+ // The window cache is authoritative: the host's second mount may have resolved it
+ // between this render and this effect.
+ const cached = winAny[CACHE_KEY] as TrackerData | undefined;
+ if (cached !== undefined) {
+ if (data.projects !== cached.projects || data.milestones !== cached.milestones) {
+ setData({ projects: cached.projects, milestones: cached.milestones, loading: false, error: null });
+ }
+ return;
+ }
+ let cancelled = false;
+
+ // Share one in-flight fetch across the host double-mount instead of querying twice.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<TrackerData> | undefined;
+ if (!inflight) {
+ inflight = loadTracker(dataApi)
+ .then((result) => {
+ winAny[CACHE_KEY] = result;
+ return result;
+ })
+ // Clear only if still ours — a refresh may have replaced it.
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((result) => {
+ if (!cancelled) setData({ projects: result.projects, milestones: result.milestones, loading: false, error: null });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Unable to load projects and milestones.';
+ setData({ projects: [], milestones: [], loading: false, error: message });
+ });
+
+ return () => { cancelled = true; };
+ // Readiness + explicit reload only — never `dataApi` (a new reference every render).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, reloadKey]);
+
+ // Every derived value is computed above the early returns (Rule 19).
+ const today = useMemo(() => startOfToday(), [data.milestones]);
+
+ const milestonesByProject = useMemo(() => {
+ const map = new Map<string, ReadableMilestone[]>();
+ for (const milestone of data.milestones) {
+ const key = lookupKey(milestone._cr_project_value);
+ if (!key) continue;
+ const list = map.get(key) ?? [];
+ list.push(milestone);
+ map.set(key, list);
+ }
+ return map;
+ }, [data.milestones]);
+
+ const statsByProject = useMemo(() => {
+ const map = new Map<string, ProjectStats>();
+ for (const project of data.projects) {
+ const key = lookupKey(project.cr_projectid);
+ map.set(key, computeStats(milestonesByProject.get(key) ?? [], today));
+ }
+ return map;
+ }, [data.projects, milestonesByProject, today]);
+
+ const summary = useMemo(() => ({
+ active: data.projects.filter((p) => Number(p.cr_status) === PROJECT_ACTIVE).length,
+ open: data.milestones.filter((m) => Number(m.cr_status) !== MILESTONE_COMPLETED).length,
+ dueSoon: data.milestones.filter((m) => isMilestoneDueSoon(m, today)).length,
+ overdue: data.milestones.filter((m) => isMilestoneOverdue(m, today)).length,
+ }), [data.projects, data.milestones, today]);
+
+ const filteredProjects = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ if (!term) return data.projects;
+ return data.projects.filter((p) =>
+ (p.cr_name ?? '').toLowerCase().includes(term) || (p.cr_manager ?? '').toLowerCase().includes(term));
+ }, [data.projects, search]);
+
+ const selectedProject = useMemo(() => {
+ const chosen = selectedProjectId
+ ? filteredProjects.find((p) => lookupKey(p.cr_projectid) === selectedProjectId)
+ : undefined;
+ return chosen ?? filteredProjects[0] ?? null;
+ }, [filteredProjects, selectedProjectId]);
+
+ const selectedKey = selectedProject ? lookupKey(selectedProject.cr_projectid) : '';
+ const selectedStats = statsByProject.get(selectedKey) ?? { total: 0, completed: 0, overdue: 0, progress: 0 };
+
+ const visibleMilestones = useMemo(() => {
+ const list = milestonesByProject.get(selectedKey) ?? [];
+ if (view === 'open') return list.filter((m) => Number(m.cr_status) !== MILESTONE_COMPLETED);
+ if (view === 'overdue') return list.filter((m) => isMilestoneOverdue(m, today));
+ return list;
+ }, [milestonesByProject, selectedKey, view, today]);
+
+ const columns = useMemo(() => buildMilestoneColumns(today), [today]);
+
+ const handleRefresh = () => {
+ // Evict both the resolved cache and any pending promise, then re-run the effect.
+ delete winAny[CACHE_KEY];
+ delete winAny[INFLIGHT_KEY];
+ setData({ projects: data.projects, milestones: data.milestones, loading: true, error: null });
+ setReloadKey((key) => key + 1);
+ };
+
+ if (data.loading) {
+ return (
+ <div className={styles.root}>
+ <div className={styles.spinnerWrap}>
+ <Spinner labelPosition="below" label="Loading projects and milestones…" />
+ </div>
+ </div>
+ );
+ }
+
+ const selectedStatus = selectedProject ? projectStatus(selectedProject) : null;
+ const budget = selectedProject
+ ? formatted(selectedProject, 'cr_budget')
+ || (typeof selectedProject.cr_budget === 'number' ? selectedProject.cr_budget.toLocaleString() : '—')
+ : '—';
+
+ return (
+ <div className={styles.root}>
+ <header className={styles.header}>
+ <div className={styles.titleBlock}>
+ <Text as="h1" size={700} weight="semibold">Project tracker</Text>
+ <Text size={300} className={styles.subtle}>
+ {data.projects.length} projects · {data.milestones.length} milestones
+ </Text>
+ </div>
+ <Button appearance="secondary" icon={<ArrowClockwiseRegular />} onClick={handleRefresh}>
+ Refresh
+ </Button>
+ </header>
+
+ {data.error && (
+ <MessageBar intent="error">
+ <MessageBarBody>{data.error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ <section className={styles.summary} aria-label="Portfolio summary">
+ <SummaryTile label="Active projects" value={summary.active} icon={<BriefcaseRegular />} />
+ <SummaryTile label="Open milestones" value={summary.open} icon={<FlagRegular />} />
+ <SummaryTile label={`Due in the next ${DUE_SOON_DAYS} days`} value={summary.dueSoon} icon={<CalendarLtrRegular />} />
+ <SummaryTile label="Overdue milestones" value={summary.overdue} icon={<WarningRegular />} danger={summary.overdue > 0} />
+ </section>
+
+ <div className={styles.body}>
+ <section className={styles.pane} aria-label="Projects">
+ <SearchBox
+ placeholder="Search by project or manager"
+ value={search}
+ onChange={(_, d) => setSearch(d.value ?? '')}
+ aria-label="Search projects"
+ />
+ <div className={styles.projectList}>
+ {filteredProjects.length === 0 ? (
+ <Text className={styles.empty}>No projects match your search.</Text>
+ ) : (
+ filteredProjects.map((project) => {
+ const key = lookupKey(project.cr_projectid);
+ return (
+ <ProjectCard
+ key={key}
+ project={project}
+ stats={statsByProject.get(key) ?? { total: 0, completed: 0, overdue: 0, progress: 0 }}
+ selected={key === selectedKey}
+ onSelect={(id) => setSelectedProjectId(lookupKey(id))}
+ />
+ );
+ })
+ )}
+ </div>
+ </section>
+
+ <section className={styles.detail} aria-label="Selected project">
+ {selectedProject && selectedStatus ? (
+ <>
+ <div className={styles.cardTitleRow}>
+ <div className={styles.titleBlock}>
+ <Text as="h2" size={500} weight="semibold">{selectedProject.cr_name ?? '—'}</Text>
+ <div className={styles.metaRow}>
+ <Badge appearance="filled" color={selectedStatus.color}>{selectedStatus.label}</Badge>
+ <PersonRegular aria-hidden="true" />
+ <Text size={200}>{selectedProject.cr_manager ?? 'Unassigned'}</Text>
+ </div>
+ </div>
+ <Button
+ appearance="subtle"
+ icon={<OpenRegular />}
+ onClick={() => openRecord('cr_project', selectedProject.cr_projectid)}
+ >
+ Open project
+ </Button>
+ </div>
+
+ <div className={styles.detailFacts}>
+ <div className={styles.fact}>
+ <Text size={200} className={styles.subtle}>Start</Text>
+ <Text weight="semibold">{formatDate(selectedProject.cr_startdate)}</Text>
+ </div>
+ <div className={styles.fact}>
+ <Text size={200} className={styles.subtle}>Target</Text>
+ <Text weight="semibold">{formatDate(selectedProject.cr_targetdate)}</Text>
+ </div>
+ <div className={styles.fact}>
+ <Text size={200} className={styles.subtle}>Budget</Text>
+ <Text weight="semibold">{budget}</Text>
+ </div>
+ <div className={styles.fact}>
+ <Text size={200} className={styles.subtle}>Progress</Text>
+ <Text weight="semibold">
+ {Math.round(selectedStats.progress * 100)}% · {selectedStats.completed}/{selectedStats.total} done
+ </Text>
+ </div>
+ </div>
+
+ <TabList
+ selectedValue={view}
+ onTabSelect={(_, d) => setView(d.value as MilestoneView)}
+ aria-label="Milestone filter"
+ >
+ <Tab value="all">All milestones</Tab>
+ <Tab value="open">Open</Tab>
+ <Tab value="overdue">Overdue ({selectedStats.overdue})</Tab>
+ </TabList>
+
+ <div className={styles.gridScroll}>
+ {visibleMilestones.length === 0 ? (
+ <Text className={styles.empty}>No milestones in this view.</Text>
+ ) : (
+ <DataGrid
+ items={visibleMilestones}
+ columns={columns}
+ getRowId={(row) => row.cr_milestoneid}
+ sortable
+ resizableColumns
+ columnSizingOptions={{
+ name: { defaultWidth: 260, minWidth: 160 },
+ duedate: { defaultWidth: 140, minWidth: 110 },
+ status: { defaultWidth: 130, minWidth: 100 },
+ progress: { defaultWidth: 180, minWidth: 120 },
+ open: { defaultWidth: 56, minWidth: 48 },
+ }}
+ aria-label={`Milestones for ${selectedProject.cr_name ?? 'project'}`}
+ >
+ <DataGridHeader>
+ <DataGridRow>
+ {({ renderHeaderCell }) => <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>}
+ </DataGridRow>
+ </DataGridHeader>
+ <DataGridBody<ReadableMilestone>>
+ {({ item, rowId }) => (
+ <DataGridRow<ReadableMilestone> key={rowId}>
+ {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
+ </DataGridRow>
+ )}
+ </DataGridBody>
+ </DataGrid>
+ )}
+ </div>
+ </>
+ ) : (
+ <Text className={styles.empty}>Select a project to see its milestones.</Text>
+ )}
+ </section>
+ </div>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/prompt.txt b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/prompt.txt
new file mode 100644
index 000000000..349a0e8ed
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/prompt.txt
@@ -0,0 +1 @@
+Build a project tracker page. I need new cr_project and cr_milestone entities with sample data to test the page.
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/provision-input.json b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/provision-input.json
new file mode 100644
index 000000000..4f9835da7
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/provision-input.json
@@ -0,0 +1,77 @@
+{
+ "solution": {
+ "uniqueName": "ContosoProjects",
+ "publisherPrefix": "cr"
+ },
+ "entities": [
+ {
+ "schemaName": "cr_Project",
+ "displayName": "Project",
+ "pluralName": "Projects",
+ "description": "A tracked project with an owner, schedule, budget and status.",
+ "primaryAttribute": {
+ "schemaName": "cr_Name",
+ "displayName": "Project Name",
+ "maxLength": 100
+ },
+ "columns": [
+ { "schemaName": "cr_Manager", "displayName": "Project Manager", "type": "Text", "maxLength": 100, "required": true },
+ { "schemaName": "cr_StartDate", "displayName": "Start Date", "type": "DateTime", "dateFormat": "DateOnly", "required": true },
+ { "schemaName": "cr_TargetDate", "displayName": "Target Date", "type": "DateTime", "dateFormat": "DateOnly", "required": true },
+ { "schemaName": "cr_Budget", "displayName": "Budget", "type": "Money", "precision": 2, "minValue": 0 },
+ { "schemaName": "cr_Status", "displayName": "Status", "type": "Choice", "options": ["Planning", "Active", "On Hold", "Completed"] }
+ ]
+ },
+ {
+ "schemaName": "cr_Milestone",
+ "displayName": "Milestone",
+ "pluralName": "Milestones",
+ "description": "A dated checkpoint that belongs to one project.",
+ "primaryAttribute": {
+ "schemaName": "cr_Name",
+ "displayName": "Milestone Name",
+ "maxLength": 100
+ },
+ "columns": [
+ { "schemaName": "cr_DueDate", "displayName": "Due Date", "type": "DateTime", "dateFormat": "DateOnly", "required": true },
+ { "schemaName": "cr_PercentComplete", "displayName": "Percent Complete", "type": "Integer", "minValue": 0, "maxValue": 100 },
+ { "schemaName": "cr_Status", "displayName": "Status", "type": "Choice", "options": ["Not Started", "In Progress", "Completed", "Blocked"] }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "type": "OneToMany",
+ "schemaName": "cr_project_cr_milestone",
+ "referenced": "cr_Project",
+ "referencing": "cr_Milestone",
+ "lookup": {
+ "schemaName": "cr_Project",
+ "displayName": "Project"
+ },
+ "cascadeDelete": "RemoveLink"
+ }
+ ],
+ "sampleData": {
+ "cr_Project": [
+ { "cr_name": "Contoso Website Redesign", "cr_manager": "Avery Chen", "cr_startdate": "2026-07-06", "cr_targetdate": "2026-12-18", "cr_budget": 185000, "cr_status": "Active" },
+ { "cr_name": "Warehouse Scanner Rollout", "cr_manager": "Priya Natarajan", "cr_startdate": "2026-08-03", "cr_targetdate": "2027-02-26", "cr_budget": 92000, "cr_status": "On Hold" },
+ { "cr_name": "Customer Portal Migration", "cr_manager": "Diego Ramirez", "cr_startdate": "2026-10-19", "cr_targetdate": "2027-04-30", "cr_budget": 240000, "cr_status": "Planning" },
+ { "cr_name": "Q3 Sales Enablement Program", "cr_manager": "Hannah Okafor", "cr_startdate": "2026-06-01", "cr_targetdate": "2026-09-30", "cr_budget": 38500, "cr_status": "Completed" }
+ ],
+ "cr_Milestone": [
+ { "cr_name": "Discovery and stakeholder interviews", "cr_duedate": "2026-07-31", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Contoso Website Redesign" } } },
+ { "cr_name": "Design system and wireframes approved", "cr_duedate": "2026-09-25", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Contoso Website Redesign" } } },
+ { "cr_name": "Content migration complete", "cr_duedate": "2026-11-13", "cr_percentcomplete": 45, "cr_status": "In Progress", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Contoso Website Redesign" } } },
+ { "cr_name": "Launch and DNS cutover", "cr_duedate": "2026-12-18", "cr_percentcomplete": 0, "cr_status": "Not Started", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Contoso Website Redesign" } } },
+ { "cr_name": "Pilot at Redmond distribution center", "cr_duedate": "2026-09-11", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Warehouse Scanner Rollout" } } },
+ { "cr_name": "Handheld device procurement", "cr_duedate": "2026-10-02", "cr_percentcomplete": 70, "cr_status": "Blocked", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Warehouse Scanner Rollout" } } },
+ { "cr_name": "Regional rollout wave 1", "cr_duedate": "2026-12-04", "cr_percentcomplete": 10, "cr_status": "In Progress", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Warehouse Scanner Rollout" } } },
+ { "cr_name": "Requirements sign-off", "cr_duedate": "2026-11-06", "cr_percentcomplete": 20, "cr_status": "In Progress", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Customer Portal Migration" } } },
+ { "cr_name": "Identity provider integration", "cr_duedate": "2027-01-22", "cr_percentcomplete": 0, "cr_status": "Not Started", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Customer Portal Migration" } } },
+ { "cr_name": "Curriculum finalized", "cr_duedate": "2026-06-26", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Q3 Sales Enablement Program" } } },
+ { "cr_name": "Regional workshops delivered", "cr_duedate": "2026-09-18", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Q3 Sales Enablement Program" } } },
+ { "cr_name": "Certification results published", "cr_duedate": "2026-09-30", "cr_percentcomplete": 100, "cr_status": "Completed", "$parent": { "entity": "cr_Project", "match": { "cr_name": "Q3 Sales Enablement Program" } } }
+ ]
+ }
+}
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/tool-results.json b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/tool-results.json
new file mode 100644
index 000000000..bfcc97212
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/tool-results.json
@@ -0,0 +1,278 @@
+[
+ {
+ "id": "manifest",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/generate-page-manifest.js' 'D:/work/project-tracker' 'project-tracker'",
+ "exitCode": 0,
+ "result": { "workingDir": "D:\\work\\project-tracker", "slug": "project-tracker", "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 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 7 existing custom tables using prefix cr. Which solution should the new tables (cr_project, cr_milestone) go in?", "options": ["Continue in 'ContosoProjects' (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_project", "cr_milestone"],
+ "detectedPrefix": "cr",
+ "detectedTableCount": 7,
+ "solutions": [{ "uniquename": "ContosoProjects", "prefix": "cr" }, { "uniquename": "FieldSurveys", "prefix": "new" }]
+ }
+ }
+ },
+ { "id": "list-languages", "by": "genpage-planner", "command": "pac model list-languages", "exitCode": 0, "result": "LCID Code Name RTL\n1033 en-US English No" },
+ { "id": "list-tables-search", "by": "genpage-planner", "command": "pac model list-tables --search 'cr_project,cr_milestone'", "exitCode": 0, "result": "No tables found matching the specified criteria." },
+ {
+ "id": "list-tables-prefix-scan",
+ "by": "genpage-planner",
+ "command": "pac model list-tables",
+ "exitCode": 0,
+ "result": "1712 tables. Type=Custom rows: cr_contractor, cr_costcenter, cr_expense, cr_invoice, cr_resource, cr_timesheet, cr_vendor, new_feedback, new_survey"
+ },
+ {
+ "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": "ContosoProjects", "friendlyname": "Contoso Projects", "publisherid": { "customizationprefix": "cr" } },
+ { "uniquename": "FieldSurveys", "friendlyname": "Field Surveys", "publisherid": { "customizationprefix": "new" } }
+ ] } }
+ },
+ { "id": "list-apps", "by": "genpage-planner", "command": "pac model list", "exitCode": 0, "result": "App ID Display Name Unique Name\n11111111-2222-3333-4444-555555555555 Contoso Operations Hub ContosoOperationsHub\n44444444-5555-6666-7777-888888888888 Field Service Desk FieldServiceDesk" },
+ {
+ "id": "planner-proposal",
+ "command": "Task genpage-planner (answers: create, cr_project + cr_milestone (new), project tracker with milestones and sample data, app Contoso Operations Hub, solution ContosoProjects)",
+ "result": {
+ "action": "plan",
+ "pages": [{ "page": "Project Tracker", "file": "project-tracker.tsx", "entities": ["cr_project", "cr_milestone"] }],
+ "entityCreationRequired": true,
+ "entities": [
+ { "suffix": "project", "resolved": "cr_project", "columns": ["manager", "startdate", "targetdate", "budget"], "choices": ["status"] },
+ { "suffix": "milestone", "resolved": "cr_milestone", "columns": ["duedate", "percentcomplete"], "choices": ["status"], "relationships": [{ "type": "1:N lookup", "relatedTable": "project", "lookupSuffix": "project" }] }
+ ],
+ "app": { "name": "Contoso Operations Hub", "appId": "11111111-2222-3333-4444-555555555555" },
+ "solution": { "uniqueName": "ContosoProjects", "publisherPrefix": "cr" }
+ }
+ },
+ {
+ "id": "plan-prepare",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' prepare --plan 'D:/work/project-tracker/genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "prepare", "planPath": "D:\\work\\project-tracker\\genpage-plan.md", "quarantinedPath": null }
+ },
+ {
+ "id": "planner-write",
+ "command": "Task genpage-planner (approved: write genpage-plan.md)",
+ "result": { "action": "written", "plan": "D:/work/project-tracker/genpage-plan.md" }
+ },
+ {
+ "id": "plan-verify",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-plan-provenance.js' verify --plan 'D:/work/project-tracker/genpage-plan.md' --approved '@D:/work/project-tracker/.approved-genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "verify", "planPath": "D:\\work\\project-tracker\\genpage-plan.md", "kind": "create", "targets": ["project-tracker.tsx"], "writtenHash": "e0a1f584bfc4462d2995c45ff9817963b1f03ce672dac1a5e8f72268538fbcaf" }
+ },
+ {
+ "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/project-tracker/genpage-plan.md, working dir D:/work/project-tracker, 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_project (6 columns, parent of cr_milestone), cr_milestone (5 columns, lookup cr_project). Would you like me to add sample data for testing?", "options": [{ "label": "Yes, add sample data", "description": "Seed realistic projects and milestones linked through the cr_project lookup" }, { "label": "No, skip", "description": "Leave both tables empty" }], "multiSelect": false }
+ ],
+ "discovered": { "provisioned": ["cr_project", "cr_milestone"], "relationship": "cr_project_cr_milestone", "log": "D:/work/project-tracker/genpage-entity-creation-log.md", "input": "D:/work/project-tracker/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/project-tracker/provision-input.json' --apply",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "solution": "ContosoProjects",
+ "entities": [
+ { "schemaName": "cr_Project", "logicalName": "cr_project", "entitySetName": "cr_projects" },
+ { "schemaName": "cr_Milestone", "logicalName": "cr_milestone", "entitySetName": "cr_milestones" }
+ ],
+ "columns": [
+ { "table": "cr_project", "schemaName": "cr_Manager", "logicalName": "cr_manager" },
+ { "table": "cr_project", "schemaName": "cr_StartDate", "logicalName": "cr_startdate" },
+ { "table": "cr_project", "schemaName": "cr_TargetDate", "logicalName": "cr_targetdate" },
+ { "table": "cr_project", "schemaName": "cr_Budget", "logicalName": "cr_budget" },
+ { "table": "cr_project", "schemaName": "cr_Status", "logicalName": "cr_status" },
+ { "table": "cr_milestone", "schemaName": "cr_DueDate", "logicalName": "cr_duedate" },
+ { "table": "cr_milestone", "schemaName": "cr_PercentComplete", "logicalName": "cr_percentcomplete" },
+ { "table": "cr_milestone", "schemaName": "cr_Status", "logicalName": "cr_status" }
+ ],
+ "relationships": [
+ { "kind": "1n", "schemaName": "cr_project_cr_milestone", "lookupLogicalName": "cr_project" }
+ ],
+ "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": "Project", "logicalName": "cr_project", "columns": 6, "relationships": "parent of cr_milestone", "sampleRecords": 4 },
+ { "table": "Milestone", "logicalName": "cr_milestone", "columns": 5, "relationships": "lookup cr_project → cr_project", "sampleRecords": 12 }
+ ],
+ "log": "D:/work/project-tracker/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/project-tracker/provision-input.json' --apply --sample-data",
+ "artifact": "provision-input.json",
+ "exitCode": 0,
+ "result": {
+ "ok": true,
+ "solution": "ContosoProjects",
+ "entities": [
+ { "schemaName": "cr_Project", "logicalName": "cr_project", "entitySetName": "cr_projects" },
+ { "schemaName": "cr_Milestone", "logicalName": "cr_milestone", "entitySetName": "cr_milestones" }
+ ],
+ "columns": [
+ { "table": "cr_project", "schemaName": "cr_Manager", "logicalName": "cr_manager" },
+ { "table": "cr_project", "schemaName": "cr_StartDate", "logicalName": "cr_startdate" },
+ { "table": "cr_project", "schemaName": "cr_TargetDate", "logicalName": "cr_targetdate" },
+ { "table": "cr_project", "schemaName": "cr_Budget", "logicalName": "cr_budget" },
+ { "table": "cr_project", "schemaName": "cr_Status", "logicalName": "cr_status" },
+ { "table": "cr_milestone", "schemaName": "cr_DueDate", "logicalName": "cr_duedate" },
+ { "table": "cr_milestone", "schemaName": "cr_PercentComplete", "logicalName": "cr_percentcomplete" },
+ { "table": "cr_milestone", "schemaName": "cr_Status", "logicalName": "cr_status" }
+ ],
+ "relationships": [
+ { "kind": "1n", "schemaName": "cr_project_cr_milestone", "lookupLogicalName": "cr_project" }
+ ],
+ "records": {
+ "cr_Project": [
+ "44444444-0000-4000-8000-000000000001",
+ "44444444-0000-4000-8000-000000000002",
+ "44444444-0000-4000-8000-000000000003",
+ "44444444-0000-4000-8000-000000000004"
+ ],
+ "cr_Milestone": [
+ "55555555-0000-4000-8000-000000000001",
+ "55555555-0000-4000-8000-000000000002",
+ "55555555-0000-4000-8000-000000000003",
+ "55555555-0000-4000-8000-000000000004",
+ "55555555-0000-4000-8000-000000000005",
+ "55555555-0000-4000-8000-000000000006",
+ "55555555-0000-4000-8000-000000000007",
+ "55555555-0000-4000-8000-000000000008",
+ "55555555-0000-4000-8000-000000000009",
+ "55555555-0000-4000-8000-000000000010",
+ "55555555-0000-4000-8000-000000000011",
+ "55555555-0000-4000-8000-000000000012"
+ ]
+ }
+ }
+ },
+ {
+ "id": "generate-types",
+ "command": "pac model genpage generate-types --data-sources 'cr_project,cr_milestone' --output-file 'D:/work/project-tracker/RuntimeTypes.ts'",
+ "artifact": "RuntimeTypes.ts",
+ "exitCode": 0,
+ "result": "Types written to D:/work/project-tracker/RuntimeTypes.ts"
+ },
+ { "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/project-tracker/genpage-plan.md'",
+ "exitCode": 0,
+ "result": { "ok": true, "workingDir": "D:\\work\\project-tracker", "files": ["project-tracker.tsx"], "problems": [] }
+ },
+ {
+ "id": "stamp",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --stamp --file 'D:/work/project-tracker/project-tracker.tsx'",
+ "exitCode": 0,
+ "result": { "ok": true, "action": "stamp", "filePath": "D:\\work\\project-tracker\\project-tracker.tsx", "existed": false }
+ },
+ { "id": "write-page", "command": "Write project-tracker.tsx", "artifact": "project-tracker.tsx" },
+ {
+ "id": "icon-grep",
+ "command": "Grep from \"@fluentui/react-icons\" project-tracker.tsx; Grep ^ArrowClockwiseRegular$|^BriefcaseRegular$|^CalendarLtrRegular$|^FlagRegular$|^OpenRegular$|^PersonRegular$|^WarningRegular$ references/verified-icons.txt",
+ "result": "ArrowClockwiseRegular, BriefcaseRegular, CalendarLtrRegular, FlagRegular, OpenRegular, PersonRegular, WarningRegular: all verified"
+ },
+ { "id": "border-grep", "command": "Grep ['\"]?borderWidth['\"]?\\s*: project-tracker.tsx", "result": "no matches" },
+ {
+ "id": "gate",
+ "command": "node 'D:/repo/plugins/model-apps/scripts/genpage-worker-output.js' --file 'D:/work/project-tracker/project-tracker.tsx'",
+ "artifact": "project-tracker.tsx",
+ "exitCode": 0,
+ "result": { "ok": true, "filePath": "D:\\work\\project-tracker\\project-tracker.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 'project-tracker.tsx' --name-file 'page-name.txt' --data-sources 'cr_project,cr_milestone' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap",
+ "exitCode": 0,
+ "pacExecutable": "pac.exe",
+ "pacWrites": 1,
+ "result": { "ok": true, "pageId": "66666666-7777-4888-9999-aaaaaaaaaaaa", "appId": "11111111-2222-3333-4444-555555555555", "updated": false }
+ }
+]
diff --git a/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/workflow-log.md b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/workflow-log.md
new file mode 100644
index 000000000..2f83607eb
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/9-project-tracker-new-entities/workflow-log.md
@@ -0,0 +1,172 @@
+# Workflow Log — Eval 9: Project tracker 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.
+
+## Phase 0 — Working directory
+- `$ARGUMENTS`: "Build a project tracker page. I need new cr_project and cr_milestone entities with sample data to test the page."
+- Working directory created: `mkdir -p 'project-tracker'` (kebab-case from "project tracker")
+- Resolved working directory: D:/work/project-tracker
+- 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/project-tracker' 'project-tracker'`
+- 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_project, cr_milestone (new)
+- AskUserQuestion: Any specific requirements for the page? → Project tracker with milestones; include sample data
+
+### 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 `pac model list-languages` → English (1033) only, no RTL language
+- Planner ran `pac model list-tables --search 'cr_project,cr_milestone'` → No tables found matching the specified criteria.
+ - Exact logical-name match: cr_project NOT FOUND, cr_milestone NOT FOUND → both confirmed as NOT existing; both need creation
+- Planner ran `pac model list-tables` for dominant prefix detection → 9 Custom tables: cr_contractor, cr_costcenter, cr_expense, cr_invoice, cr_resource, cr_timesheet, cr_vendor, new_feedback, new_survey
+ - Non-system custom prefixes: cr = 7 of 9 (78%, ≥ 3 tables) → dominant prefix detected: `cr` (detectedPrefix = cr, detectedTableCount = 7)
+- 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 → ContosoProjects (Contoso Projects, publisher prefix cr), FieldSurveys (Field Surveys, publisher prefix new)
+- Planner ran `pac model list` → 2 apps: Contoso Operations Hub (11111111-2222-3333-4444-555555555555), Field Service Desk (44444444-5555-6666-7777-888888888888)
+- 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 `pac model 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_project, cr_milestone)
+- AskUserQuestion: Your env has 7 existing custom tables using prefix `cr`. Which solution should the new tables (cr_project, cr_milestone) go in? (options, dominant-prefix match first: Continue in 'ContosoProjects' (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 'ContosoProjects' (prefix: cr)
+- Chosen prefix `cr` matches the dominant prefix and the requested table names → no prefix-mismatch warning needed
+- Recorded for the plan: `Solution: ContosoProjects`, `Publisher Prefix: cr`
+
+### Plan approval
+- Re-invoked `Task genpage-planner` with every answer gathered so far; it returned the proposed plan:
+ - 1 page: Project Tracker (project-tracker.tsx) on cr_project, cr_milestone
+ - Create `cr_project` (Project): manager (text), startdate / targetdate (date only), budget (money), status choice Planning / Active / On Hold / Completed
+ - Create `cr_milestone` (Milestone): duedate (date only), percentcomplete (whole number 0-100), status choice Not Started / In Progress / Completed / Blocked
+ - Lookup relationship: 1:N cr_project → cr_milestone, lookup column `cr_project` on cr_milestone (cr_milestone → cr_project)
+ - Sample data requested: realistic projects with milestones linked to their project
+ - App: Contoso Operations Hub; Solution: ContosoProjects (prefix cr); Languages: English (1033) only
+- EnterPlanMode called — presented the proposed plan (resolved names cr_project / cr_milestone 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/project-tracker/genpage-plan.md'`
+- Result: `"ok":true`, nothing to quarantine (first run in this folder)
+- Saved the approved plan body verbatim to D:/work/project-tracker/.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 `project`, `milestone`; column suffixes `manager`, `startdate`, `targetdate`, `budget`, `duedate`, `percentcomplete`; choice suffix `status`; lookup suffix `project` — 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/project-tracker/genpage-plan.md' --approved '@D:/work/project-tracker/.approved-genpage-plan.md'`
+- Result: `"ok":true`, kind create, targets [project-tracker.tsx], writtenHash e0a1f584bfc4462d2995c45ff9817963b1f03ce672dac1a5e8f72268538fbcaf
+
+## Phase 2a — Pre-flight: az + pac + Dataverse
+- `## Entity Creation Required` lists two tables (project, milestone) → 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/project-tracker/genpage-plan.md, working directory, plugin root and env URL https://contoso.crm.dynamics.com
+ - Read plan `## Environment`: Solution = ContosoProjects, Publisher Prefix = cr; suffix validation passed
+ - Dependency order: cr_project (independent) → cr_milestone (references cr_project) → 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/project-tracker/genpage-entity-creation-log.md
+ - Wrote D:/work/project-tracker/provision-input.json: solution ContosoProjects / prefix cr; entities cr_Project (primary cr_Name; cr_Manager Text, cr_StartDate DateTime DateOnly, cr_TargetDate DateTime DateOnly, cr_Budget Money, cr_Status Choice) and cr_Milestone (primary cr_Name; cr_DueDate DateTime DateOnly, cr_PercentComplete Integer 0-100, cr_Status Choice); relationship OneToMany cr_project_cr_milestone (referenced cr_Project, referencing cr_Milestone, lookup cr_Project)
+ - Command: `node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/project-tracker/provision-input.json' --apply`
+ - Result: `ok: true` — tables cr_project and cr_milestone, 8 columns, relationship cr_project_cr_milestone (lookup cr_project) created in ContosoProjects; 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_project: 6 columns, parent of cr_milestone; cr_milestone: 5 columns, lookup cr_project). Would you like me to add sample data for testing? → Yes, add sample data (the prompt explicitly asked for "sample data to test the page")
+- 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`: 4 cr_Project rows and 12 cr_Milestone rows; choice values written as labels; every milestone binds its project with `"$parent": { "entity": "cr_Project", "match": { "cr_name": "<project name>" } }`
+ - Command: `node 'D:/repo/plugins/model-apps/scripts/provision-entities.js' --env 'https://contoso.crm.dynamics.com' --input '@D:/work/project-tracker/provision-input.json' --apply --sample-data`
+ - Result: `ok: true` — existing tables and relationship re-reported (idempotent); parents seeded before children; records cr_Project 4, cr_Milestone 12, each milestone linked through its cr_project lookup
+ - Updated `## Commands` in genpage-entity-creation-log.md with the `--sample-data` run and recorded the created record ids
+ - Builder returned completion: cr_project (6 columns, 4 sample records), cr_milestone (5 columns incl. lookup, 12 sample records); log at D:/work/project-tracker/genpage-entity-creation-log.md
+
+## Phase 3 — App
+- SKIPPED app creation: existing app Contoso Operations Hub (11111111-2222-3333-4444-555555555555) selected; `pac model create` not called
+
+## Phase 4 — RuntimeTypes
+- `pac model genpage generate-types --data-sources 'cr_project,cr_milestone' --output-file 'D:/work/project-tracker/RuntimeTypes.ts'`
+- Read RuntimeTypes.ts: verified cr_projectid, cr_name, cr_manager, cr_startdate, cr_targetdate, cr_budget, cr_status (enum Planning/Active/On Hold/Completed = 100000000-100000003) on cr_project; cr_milestoneid, cr_name, cr_duedate, cr_percentcomplete, cr_status (enum Not Started/In Progress/Completed/Blocked = 100000000-100000003) and the `_cr_project_value` foreign key on cr_milestone (display name comes from its FormattedValue annotation; `cr_projectname` is not selectable)
+
+## 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 `### Project Tracker` subsection
+- Command: `node 'D:/repo/plugins/model-apps/scripts/check-page-files.js' --plan 'D:/work/project-tracker/genpage-plan.md'`
+- Result: `"ok":true` — project-tracker.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/project-tracker/project-tracker.tsx'`
+- Result: `"ok":true`, stamp recorded, no earlier file at the target
+- Wrote project-tracker.tsx with the file tool: one Promise.all over queryTable('cr_project') and queryTable('cr_milestone') read via `.rows`, single batched setData, window cache + in-flight de-dupe gated on `dataReady` and a refresh key, milestones grouped by `_cr_project_value` with the project label from its FormattedValue annotation, summary tiles, searchable project cards, sortable milestone DataGrid (createTableColumn + compare, resizableColumns, columnSizingOptions) with All / Open / Overdue tabs, records opened via Xrm.Navigation.navigateTo
+- Icon verification: Grep for `from "@fluentui/react-icons"` → ArrowClockwiseRegular, BriefcaseRegular, CalendarLtrRegular, FlagRegular, OpenRegular, PersonRegular, WarningRegular; 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/project-tracker/project-tracker.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 ("Project Tracker") 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 'project-tracker.tsx' --name-file 'page-name.txt' --data-sources 'cr_project,cr_milestone' --prompt-file 'prompt.txt' --model 'claude-sonnet-4-6' --agent-message-file 'agent-message.txt' --add-to-sitemap`
+- Data sources: both new tables, cr_project and cr_milestone
+- Prompt scope: full page description from the plan's `## User Requirements` (create)
+- Result: page-id = 66666666-7777-4888-9999-aaaaaaaaaaaa, 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 tables were already created in ContosoProjects)
+
+## 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 |
+|------|------|----------|--------|
+| Project Tracker | project-tracker.tsx | cr_project, cr_milestone | Deployed |
+
+- App: Contoso Operations Hub (11111111-2222-3333-4444-555555555555)
+- Page ID: 66666666-7777-4888-9999-aaaaaaaaaaaa
+- Entities created: cr_project, cr_milestone (lookup cr_milestone → cr_project) in solution ContosoProjects
+- Sample data: 4 projects, 12 milestones (each linked to its project)
+- Browser verification: skipped
diff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.md
index 0566cd9f5..2317d0592 100644
--- a/evals/model-apps/genpage/fixtures/README.md
+++ b/evals/model-apps/genpage/fixtures/README.md
@@ -90,11 +90,11 @@ Two rules for evidence files:
## Current state
-This directory has **20 fixtures, 26 top-level TSX files and 18 represented
+This directory has **27 fixtures, 34 top-level TSX files and 25 represented
prompt IDs**. All are green under both runners. Directories listed in
`contracts.json` are historical contract-1 evidence; every other directory is a
current contract-2 synthetic. Registered prompts with no fixture:
-**3, 6, 8, 9, 12, 14, 16**. `evals/model-apps/tests/eval-coverage-contract.test.js`
+**none**. `evals/model-apps/tests/eval-coverage-contract.test.js`
fails when these figures, or the reasons recorded for the missing prompts, fall out
of step with the fixtures.
@@ -120,6 +120,13 @@ of step with the fixtures.
| `23-worker-completeness/` | 23 | Current synthetic | green | Failed production gate blocks upload until fresh complete regeneration |
| `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` |
+| `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, `pac model create --solution`, new app-id used for upload |
+| `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 |
Historical captures remain compatibility/parser evidence, not proof of today's
file transport, binding preservation or full skill compliance. Their current
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index ef87cf50a..94e33e4e4 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -13,16 +13,20 @@
'use strict';
+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 } = require('./workflow-evidence.js');
-const { gradeEvidence } = require('./evidence-utils.js');
-const { navigationProblems } = require('./navigation-contract.js');
+const { currentContract, workflowCalls, isAuth, isDiscovery, authGateProblems, discoveryProblems, refusalProblems, resultObject, isGeneration, isUpload } = 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');
const { uploadProblems, uploadPreservationProblems } = require('./upload-contract.js');
const { planSection, findMarkdownTable, parseMarkdownRows } = require('./plan-evidence.js');
const { customApiProblems, customApiGateProblems } = require('./custom-api-contract.js');
const { packagingProblems, isPackaging } = require('./packaging-contract.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');
function fail(reason) { return { status: 'fail', reason }; }
function pass() { return { status: 'pass', reason: '' }; }
@@ -554,10 +558,16 @@ WORKFLOW_ASSERTIONS.set(
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
if (!solutionQuestionAsked(log)) return skip('solution question not asked');
- // Accept either canonical (dataverse-request.js /solutions or GET /solutions)
- // or the PAC CLI equivalent (`pac solution list`) — both enumerate solutions.
+ // Accept either canonical (dataverse-request.js on the solutions entity set, or GET /solutions)
+ // or the PAC CLI equivalent (`pac solution list`) — both enumerate solutions. The planner's
+ // documented command passes a RELATIVE path with no leading slash, and is written across a
+ // shell line continuation (agents/genpage-planner.md):
+ // node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \
+ // "solutions?\$select=uniquename,friendlyname&..."
+ // so the entity set may follow a quote, a space or a slash, possibly on the next line after a
+ // bash `\` or PowerShell backtick continuation — but never across an unrelated line break.
if (
- !/dataverse-request\.js[^\n]*\/solutions|GET\s+\/solutions/i.test(log) &&
+ !/dataverse-request\.js(?:[^\n]|[\\`]\r?\n)*?[\s'"/]solutions\b|GET\s+\/solutions/i.test(log) &&
!/pac\s+solution\s+list/i.test(log)
) {
return fail('solution question asked but solutions endpoint not queried (expected dataverse-request.js /solutions OR pac solution list)');
@@ -1355,6 +1365,1825 @@ PHASE_EXPECTATIONS.set(
}
);
+// ---------------------------------------------------------------------------------------------
+// Per-eval expectations graded from structured evidence
+// ---------------------------------------------------------------------------------------------
+//
+// Each check below reads the artifact a real run leaves for its requirement — a command and the
+// result recorded with it, a plan table, an entity-creation transaction or the generated
+// RuntimeTypes.ts — through lib/expectation-evidence.js. It SKIPs only where that artifact is not
+// part of the fixture's shape, and names the exact value that disagrees when it fails.
+
+const {
+ csvList, sameSet, containsAll, suffixOf, commandCalls, listTablesSearches, generateTypesCalls, uploadCalls,
+ provisionCalls, legacyProvisionCalls, planPrefix, planSolution, planEntityBlocks, existingEntities, entityLog,
+ createdTableNames, runtimeEnums, choiceEnum, NOT_FOUND, LIST_LANGUAGES, GENPAGE_LIST, GUID_RE, listingRows, conversationSteps,
+} = evidence;
+
+const resultOf = (problems) => (problems.length ? fail(problems[0]) : pass());
+const listText = (items) => (items.length ? items.join(',') : 'none');
+const normalized = (text) => String(text || '').toLowerCase().replace(/[^a-z0-9]+/g, '');
+
+// The body under a heading matched by `heading` (any level), up to the next heading of the same or
+// a higher level. Logs title their phases freely (`## Phase 8 — Summary`, `## Phase 8: Summary`),
+// so the title is a pattern rather than planSection's exact text.
+function headingSection(text, heading) {
+ const lines = String(text || '').split(/\r?\n/);
+ const start = lines.findIndex((line) => heading.test(line));
+ if (start === -1) return null;
+ const level = /^(#+)/.exec(lines[start])[1].length;
+ const out = [];
+ for (const line of lines.slice(start + 1)) {
+ const next = /^(#+)\s/.exec(line);
+ if (next && next[1].length <= level) break;
+ out.push(line);
+ }
+ return out.join('\n');
+}
+
+function pageRowsOf(plan) {
+ return parseMarkdownRows(planSection(plan, 'Pages') || '', ['Page', 'File', 'Purpose', 'Entities']);
+}
+
+// Recorded by the orchestrator (`Task genpage-entity-builder`, `Dispatched genpage-entity-builder`) or
+// implied by the provisioning scripts only the entity-builder runs.
+const BUILDER_CALL = /\b(?:Task|Dispatched)\s+genpage-entity-builder\b|\bgenpage-entity-builder\s+invoked\b|\bprovision-entities\.js\b|\b(?:create-table|add-column|create-relationship|create-record)\.js\b/i;
+
+function entityBuilderInvoked(fixture) {
+ return /genpage-entity-builder\s+invoked|entity-builder\s+invoked|Task.*entity-builder/i.test(fixture.workflowLog || '')
+ || workflowCalls(fixture).some((call) => BUILDER_CALL.test(call.command));
+}
+
+// An existing table is confirmed by BOTH halves of discovery: a `list-tables --search` that covered
+// it without reporting it absent, and the plan's verdict (listed under Existing Entities, not
+// scheduled for creation). The list-tables wording varies by capture, so the plan is the
+// structured verdict and the search result is only checked for a contradiction.
+function existingEntityProblems(fixture, names) {
+ if (!fixture.genpagePlan) return ['no genpage-plan.md'];
+ const searches = listTablesSearches(fixture);
+ if (!searches.length) return ['pac model list-tables --search was not run'];
+ const existing = existingEntities(fixture.genpagePlan);
+ const planned = planEntityBlocks(fixture.genpagePlan).map((block) => block.suffix);
+ const problems = [];
+ for (const name of names) {
+ const search = searches.find((s) => s.terms.includes(name));
+ if (!search) problems.push(`no pac model list-tables --search covered ${name} (searched: ${searches.map((s) => listText(s.terms)).join('; ')})`);
+ else if (NOT_FOUND.test(search.text)) problems.push(`list-tables recorded ${name} as not found`);
+ if (!existing.includes(name)) problems.push(`plan ## Existing Entities does not confirm ${name}`);
+ if (planned.includes(suffixOf(name))) problems.push(`plan schedules ${name} for creation although it exists`);
+ }
+ return problems;
+}
+
+// The mirror image for a table the run must create. `exact` additionally requires the verdict to
+// rest on an exact logical-name match: a search for `cr_candidate` can return `cr_candidatenote`,
+// and a fuzzy reading of that hit would skip creating a table that does not exist. A search that
+// returned no rows at all cannot have been misread, so it satisfies `exact` on its own.
+function missingEntityProblems(fixture, names, { exact = false } = {}) {
+ if (!fixture.genpagePlan) return ['no genpage-plan.md'];
+ const searches = listTablesSearches(fixture);
+ if (!searches.length) return ['pac model list-tables --search was not run'];
+ const existing = existingEntities(fixture.genpagePlan);
+ const planned = planEntityBlocks(fixture.genpagePlan).map((block) => block.suffix);
+ const problems = [];
+ for (const name of names) {
+ const search = searches.find((s) => s.terms.includes(name) || s.terms.includes(suffixOf(name)));
+ if (!search) problems.push(`no pac model list-tables --search covered ${name} (searched: ${searches.map((s) => listText(s.terms)).join('; ')})`);
+ else if (!NOT_FOUND.test(search.text)) problems.push(`list-tables result does not record ${name} as absent`);
+ else if (exact && !/\bexact\b/i.test(search.text) && !/\bNo\s+tables?\s+found\b/i.test(search.text)) {
+ problems.push(`list-tables verdict for ${name} does not rest on an exact logical-name match`);
+ }
+ if (!planned.includes(suffixOf(name))) problems.push(`plan ## Entity Creation Required has no "### ${suffixOf(name)}" block for ${name}`);
+ if (existing.includes(name)) problems.push(`plan ## Existing Entities lists ${name} although it must be created`);
+ }
+ return problems;
+}
+
+function generateTypesProblems(fixture, names, { exact = false } = {}) {
+ const calls = generateTypesCalls(fixture);
+ if (!calls.length) return ['pac model genpage generate-types was not run'];
+ if (!names.length) return ['no entity names to generate types for'];
+ const covers = (c) => (exact ? sameSet(c.sources, names) : containsAll(c.sources, names));
+ if (!calls.some(covers)) return [`no generate-types run has --data-sources ${listText(names)} (saw ${calls.map((c) => listText(c.sources)).join('; ')})`];
+ return [];
+}
+
+// Every upload of the page must bind the tables: the raw `pac` transport persists exactly the
+// `--data-sources` it is given, so an update that drops one silently unbinds the page.
+function uploadSourcesProblems(fixture, names, { exact = false } = {}) {
+ const uploads = uploadCalls(fixture);
+ if (!uploads.length) return ['no genpage upload command recorded'];
+ if (!names.length) return ['no entity names to bind'];
+ return uploads.filter((u) => (exact ? !sameSet(u.sources, names) : !containsAll(u.sources, names)))
+ .map((u) => `${u.file || 'upload'}: --data-sources is ${listText(u.sources)}, expected ${listText(names)}`);
+}
+
+// The answer to a question, recorded as `AskUserQuestion: <question> → <answer>` or as a list line
+// under a heading that names AskUserQuestion, e.g.
+// ### Discovery questions (AskUserQuestion)
+// - Question 4 (sample data): user answered "Yes, add sample data"
+// Unattended runs record `Unattended default: <decision> -> <value>` instead.
+function recordedAnswer(log, topic) {
+ let heading = '';
+ for (const line of String(log || '').split(/\r?\n/)) {
+ if (/^\s*#/.test(line)) { heading = line; continue; }
+ if (!topic.test(line)) continue;
+ const unattended = /Unattended default:/i.test(line);
+ if (!unattended && !/AskUserQuestion/.test(line) && !/AskUserQuestion/.test(heading)) continue;
+ const answer = /(?:\u2192|->|\banswered\b|\bselected\b)\s*:?\s*"?([^"\n]+)"?/i.exec(line);
+ if (answer) return { unattended, answer: answer[1].trim() };
+ }
+ return null;
+}
+
+// The sample-data QUESTION, not any line that mentions sample data. "sample data" must come before
+// the question mark or the `(topic):` label, so a requirements answer that merely asks for sample
+// data is not read as the builder's yes/no question:
+// - Question 4 (sample data): user answered "Yes, add sample data" the question
+// AskUserQuestion: … Would you like me to add sample data for testing? → Yes, add … the question
+// AskUserQuestion: Any specific requirements? → Project tracker; include sample data NOT it
+const SAMPLE_DATA_QUESTION = /\bsample\s+data\b[^\n]*?(?:\?|\):)/i;
+
+// The solution the maker picked, e.g.
+// AskUserQuestion: Which solution should cr_ticket go in? → Crdec34 (existing custom solution)
+// ### Solution selection / - User selected: "Use Default Solution"
+function solutionAnswer(log) {
+ let heading = '';
+ for (const line of String(log || '').split(/\r?\n/)) {
+ if (/^\s*#/.test(line)) { heading = line; continue; }
+ const asked = /AskUserQuestion[^\n]*solution/i.test(line) && /(?:\u2192|->)\s*(.+)$/.exec(line);
+ if (asked) return asked[1];
+ const selected = /solution/i.test(heading) && /\b(?:user\s+)?(?:selected|chose|picked|answered)\b:?\s*(.+)$/i.exec(line);
+ if (selected) return selected[1];
+ }
+ return null;
+}
+
+function solutionChoiceProblems(fixture) {
+ const { workflowLog: log, genpagePlan: plan } = fixture;
+ if (!log) return ['no workflow-log.md'];
+ if (!plan) return ['no genpage-plan.md'];
+ if (!entitiesNeedCreating(plan) && !newAppNeeded(plan)) return ['plan records no entity or app creation, so no solution question was due'];
+ const solution = planSolution(plan);
+ const prefix = planPrefix(plan);
+ const problems = [];
+ if (!solution) problems.push('## Environment has no "Solution: <uniqueName>" line');
+ if (!prefix) problems.push('## Environment has no "Publisher Prefix: <prefix>" line');
+ if (isUnattendedLog(log)) {
+ if (!/Unattended default:[^\n]*solution/i.test(log)) problems.push('unattended run recorded no solution default');
+ return problems;
+ }
+ if (!solutionQuestionAsked(log)) return [...problems, 'metadata work is planned but the solution question was not asked'];
+ const answer = solutionAnswer(log);
+ if (answer === null) problems.push('the answer to the solution question is not recorded');
+ // Compare on letters and digits only: "Use Default Solution" picked `Default`, and a "Create new
+ // genpage-recruitment solution" answer records the unique name `genpage_recruitment`.
+ else if (solution && !normalized(answer).includes(normalized(solution))) {
+ problems.push(`## Environment records Solution: ${solution}, but the maker answered "${answer.trim()}"`);
+ }
+ return problems;
+}
+
+// The lookups between tables this run creates: [{ child, parent }] by suffix. Only these impose an
+// order — a lookup to an existing table (`account`) has its target already in place.
+function newTableLookups(plan) {
+ const blocks = planEntityBlocks(plan);
+ return blocks.flatMap((block) => block.relationships
+ .filter((rel) => !/N\s*:\s*N/i.test(rel.type) && blocks.some((other) => other.suffix === rel.related))
+ .map((rel) => ({ child: block.suffix, parent: rel.related })));
+}
+
+// Every create in the plan has its transaction in genpage-entity-creation-log.md: a Created Tables
+// entry carrying the Resolved Full Name Dataverse returned, a Created Columns row per column and
+// choice column, and a Created Relationships row per lookup (From = referenced, To = referencing).
+function entityLogCoverageProblems(fixture) {
+ const log = entityLog(fixture.entityCreationLog);
+ if (!log) return { problems: ['no genpage-entity-creation-log.md (or its legacy entity-creation-log.md alias)'], log };
+ const blocks = planEntityBlocks(fixture.genpagePlan);
+ if (!blocks.length) return { problems: ['plan schedules no entity creation'], log };
+ const problems = [];
+ for (const block of blocks) {
+ const table = log.tables.find((t) => t.resolved && suffixOf(t.resolved) === block.suffix);
+ if (!table) { problems.push(`table ${block.suffix} has no Created Tables entry with its Resolved Full Name`); continue; }
+ for (const column of [...block.columns, ...block.choices]) {
+ if (!log.columns.some((row) => row.table === table.resolved && suffixOf(row.resolved) === column.suffix)) {
+ problems.push(`column ${column.suffix} of ${table.resolved} has no Created Columns row`);
+ }
+ }
+ for (const rel of block.relationships.filter((r) => !/N\s*:\s*N/i.test(r.type))) {
+ if (!log.relationships.some((row) => suffixOf(row.from) === rel.related && suffixOf(row.to) === block.suffix)) {
+ problems.push(`lookup ${table.resolved} → ${rel.related} has no Created Relationships row`);
+ }
+ }
+ }
+ return { problems, log };
+}
+
+// Tables a generated page binds: the literal first argument of each dataApi row call. Calls are
+// found in LITERAL-BLANKED source so a commented-out or quoted example never counts, and the name is
+// read back from the original at the same offset (blankLiterals keeps offsets 1:1). A table passed
+// through a variable is dynamic and not counted.
+const DATA_API_ROW_CALL = /\bdataApi\s*\??\.\s*(?:queryTable|retrieveRow|retrieveMultipleRecords|createRow|updateRow|deleteRow)\s*\(\s*/g;
+function boundTables(content) {
+ const tables = new Set();
+ for (const m of blankLiterals(content).matchAll(DATA_API_ROW_CALL)) {
+ const literal = /^(['"`])([A-Za-z_]\w*)\1/.exec(content.slice(m.index + m[0].length));
+ if (literal) tables.add(literal[2].toLowerCase());
+ }
+ return [...tables];
+}
+
+// Phase 6.5 operates on the files whose navigation still names a sibling: PAGEREF_ tokens in an
+// authored snapshot, or — in a capture taken after the fix-up — the deployed GUIDs they became.
+function navigationPhaseOf(fixture) {
+ return fixture.manifest?.navigationPhase || 'authored';
+}
+
+function pagerefFiles(fixture) {
+ const phase = navigationPhaseOf(fixture);
+ const legacy = phase === 'legacy-authored';
+ return (fixture.files || []).filter((file) => navTargets(file.content, { legacy })
+ .some((t) => (phase === 'resolved' ? t.kind === 'literal' : t.kind === 'pageref' || t.kind === 'pageref-malformed')))
+ .map((file) => file.name);
+}
+
+// The prompt an upload carried, by transport: the inline `--prompt "…"` value, the prompt file the
+// file transport passes, or the `Prompt scope:` line the skill logs next to that command.
+function uploadPrompt(fixture, upload) {
+ if (typeof upload.flags.prompt === 'string') return upload.flags.prompt;
+ if (typeof upload.flags['prompt-file'] === 'string') {
+ try { return artifactText(fixture, upload.flags['prompt-file']); } catch { /* fall through to the logged scope */ }
+ }
+ return promptEvidence(fixture.workflowLog, upload.call.command);
+}
+
+// --- Eval 2 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): Data source question is skipped or answered 'mock data' — no entity detection needed",
+ ({ fixture }) => {
+ const { workflowLog: log, genpagePlan: plan } = fixture;
+ if (!log) return fail('no workflow-log.md');
+ if (!plan) return fail('no genpage-plan.md');
+ // The data source must have resolved to mock data. A recorded answer says so directly, e.g.
+ // - Question 2 (data source): user answered "Mock data"
+ // AskUserQuestion: Dataverse entities or mock data? → mock data (pre-supplied)
+ // and an unrecorded question was skipped — then the `Data mode: mock` the orchestrator hands the
+ // page builder is the record of what it resolved to. Upload lines (`--data-sources`) are flags,
+ // not answers.
+ const answers = log.split(/\r?\n/).filter((line) => /\bdata[\s-]?source\b(?!s)|entities or mock data/i.test(line) && !/--data-sources/.test(line));
+ const other = answers.find((line) => !/mock[\s-]?data|\bskipped\b/i.test(line));
+ if (other) return fail(`the data-source question was not answered with mock data: ${other.trim()}`);
+ if (!answers.length && !/Data mode:\s*`?mock\b/i.test(log)) return fail('workflow-log records no data-source answer and no mock data mode');
+ if (entitiesNeedCreating(plan)) return fail('plan schedules entity creation for a mock-data page');
+ const existing = existingEntities(plan);
+ if (existing.length) return fail(`plan lists existing entities (${listText(existing)}) for a mock-data page`);
+ const searches = listTablesSearches(fixture);
+ if (searches.length) return fail(`entity detection ran for a mock-data page (list-tables --search ${listText(searches[0].terms)})`);
+ return pass();
+ }
+);
+
+// --- Eval 4 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): pac model list-tables --search 'incident,contact' is run; both entities confirmed as existing",
+ ({ fixture }) => resultOf(existingEntityProblems(fixture, ['incident', 'contact']))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2: Entity-builder is SKIPPED',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ if (entitiesNeedCreating(fixture.genpagePlan)) return fail('plan schedules entity creation, so skipping the builder would leave its tables missing');
+ if (entityBuilderInvoked(fixture)) return fail('entity-builder was invoked or entities were provisioned');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 4: pac model genpage generate-types --data-sources 'incident,contact' is run",
+ ({ fixture }) => resultOf(generateTypesProblems(fixture, ['incident', 'contact'], { exact: true }))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5 (Page Builder): Wizard sample (2-wizard-multi-step.tsx) is read',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ // `- Read sample: plugins/model-apps/samples/2-wizard-multi-step.tsx` — the READ, not merely
+ // the plan's ## Relevant Samples row naming it.
+ const read = fixture.workflowLog.split(/\r?\n/).some((line) => /\bread\b/i.test(line) && /samples[\\/]2-wizard-multi-step\.tsx\b/.test(line));
+ return read ? pass() : fail('workflow-log does not record reading samples/2-wizard-multi-step.tsx');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 6: Upload includes --data-sources 'incident,contact'",
+ ({ fixture }) => resultOf(uploadSourcesProblems(fixture, ['incident', 'contact'], { exact: true }))
+);
+
+// --- Eval 5 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): task entity confirmed as existing; plan describes kanban with 3 columns mapped to task statecode/statuscode values',
+ ({ fixture }) => {
+ const problems = existingEntityProblems(fixture, ['task']);
+ if (problems.length) return fail(problems[0]);
+ const spec = planSection(fixture.genpagePlan, 'Per-Page Specifications') || '';
+ const missing = ['To Do', 'In Progress', 'Done'].filter((label) => !new RegExp(`\\b${label}\\b`, 'i').test(spec));
+ if (missing.length) return fail(`## Per-Page Specifications does not describe the ${missing.join(', ')} column(s)`);
+ // e.g. `- Three columns mapped to task statuscode values: Open (1) = To Do, …`
+ if (!spec.split(/\r?\n/).some((line) => /\bcolumns?\b/i.test(line) && /\b(?:statuscode|statecode)\b/.test(line))) {
+ return fail('## Per-Page Specifications does not map the columns to task statuscode/statecode values');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 4: RuntimeTypes.ts is read — status field enum values are identified for column mapping',
+ ({ fixture }) => {
+ const calls = generateTypesCalls(fixture);
+ if (!calls.length) return fail('pac model genpage generate-types was not run');
+ // What the log records AFTER the command line, e.g.
+ // - Critical finding: planner's statuscode mapping was incorrect. RuntimeTypes shows:
+ // - `"Not Started" = 2` → To Do column
+ // The identified `"Label" = value` pairs ARE the evidence of the read: they are checked against
+ // the captured RuntimeTypes.ts below, so a guessed mapping cannot pass as a read one.
+ const after = calls.map((c) => c.text.split(/\r?\n/).slice(1).join('\n')).join('\n');
+ const pairs = [...after.matchAll(/"([^"\n]+)"\s*=\s*(-?\d+)/g)].map((m) => ({ label: m[1], value: Number(m[2]) }));
+ if (!pairs.length) return fail('workflow-log does not record the status enum values read from RuntimeTypes.ts for the column mapping');
+ if (fixture.runtimeTypes) {
+ // Cross-check against the generated schema: an identified value that is not a member of the
+ // table's statuscode/statecode enum was guessed, not read.
+ const { registrations, enums } = runtimeEnums(fixture.runtimeTypes);
+ const members = [...registrations].filter(([key]) => /-(?:statuscode|statecode)$/.test(key)).flatMap(([, name]) => enums.get(name) || []);
+ if (!members.length) return fail('RuntimeTypes.ts registers no statuscode/statecode enum');
+ const wrong = pairs.filter((p) => !members.some((m) => m.label === p.label && m.value === p.value));
+ if (wrong.length) return fail(`recorded status values are not in RuntimeTypes.ts: ${wrong.map((p) => `"${p.label}" = ${p.value}`).join(', ')}`);
+ }
+ return pass();
+ }
+);
+
+// --- Eval 7 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): pac model list-tables --search confirms cr_candidate and cr_jobrequisition do NOT exist (exact logical-name match, not fuzzy)',
+ ({ fixture }) => resultOf(missingEntityProblems(fixture, ['cr_candidate', 'cr_jobrequisition'], { exact: true }))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes entity definitions with columns, types, and a lookup relationship (cr_candidate → cr_jobrequisition)',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const blocks = planEntityBlocks(fixture.genpagePlan);
+ const problems = [];
+ for (const suffix of ['candidate', 'jobrequisition']) {
+ const block = blocks.find((b) => b.suffix === suffix);
+ if (!block) { problems.push(`## Entity Creation Required has no "### ${suffix}" definition`); continue; }
+ if (!block.columns.length) problems.push(`${suffix} defines no columns`);
+ const untyped = block.columns.filter((c) => !c.type || /^none$/i.test(c.type));
+ if (untyped.length) problems.push(`${suffix} column(s) without a type: ${untyped.map((c) => c.suffix).join(', ')}`);
+ }
+ const candidate = blocks.find((b) => b.suffix === 'candidate');
+ if (candidate && !candidate.relationships.some((r) => r.related === 'jobrequisition' && r.lookup && !/N\s*:\s*N/i.test(r.type))) {
+ problems.push('candidate has no lookup relationship to jobrequisition');
+ }
+ return resultOf(problems);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): Because entities will be created, the planner asks the solution selection question via AskUserQuestion and records the choice in ## Environment as 'Solution: <uniqueName>' and 'Publisher Prefix: <prefix>'",
+ ({ fixture }) => resultOf(solutionChoiceProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 2b (Entity Builder): Reads Solution + Publisher Prefix from the plan's ## Environment",
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ // The builder copies what it read into its transaction log's own ## Environment (entity-builder
+ // Step 3), so that block — not prose — is the record of what it read.
+ const log = entityLog(fixture.entityCreationLog);
+ if (!log) return fail('no genpage-entity-creation-log.md (or its legacy alias) recording the Environment the builder read');
+ const solution = planSolution(fixture.genpagePlan);
+ const prefix = planPrefix(fixture.genpagePlan);
+ if (!solution || !prefix) return fail('plan ## Environment lacks Solution or Publisher Prefix');
+ if (log.solution !== solution) return fail(`builder recorded Solution: ${log.solution || 'none'}, plan declares ${solution}`);
+ if (log.prefix !== prefix) return fail(`builder recorded Publisher Prefix: ${log.prefix || 'none'}, plan declares ${prefix}`);
+ // When the log restates it too (`Reads Solution=Default, Publisher Prefix=cr`), it must agree.
+ const said = /Solution\s*=\s*([^,\s]+),?\s+Publisher Prefix\s*=\s*(\S+)/i.exec(fixture.workflowLog || '');
+ if (said && (said[1] !== solution || said[2].toLowerCase() !== prefix)) {
+ return fail(`workflow-log says the builder read Solution=${said[1]}, Publisher Prefix=${said[2]}`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): cr_jobrequisition (independent) is provisioned before cr_candidate (has lookup) to satisfy dependency ordering',
+ ({ fixture }) => {
+ const lookups = newTableLookups(fixture.genpagePlan);
+ if (!lookups.some((l) => l.child === 'candidate' && l.parent === 'jobrequisition')) {
+ return fail('plan declares no candidate → jobrequisition lookup to order by');
+ }
+ const log = entityLog(fixture.entityCreationLog);
+ if (!log) return fail('no genpage-entity-creation-log.md (or its legacy alias)');
+ // Created Tables is appended as each create succeeds, so its order is the provisioning order.
+ const order = log.tables.map((t) => suffixOf(t.resolved || ''));
+ const problems = [];
+ for (const { child, parent } of lookups) {
+ const p = order.indexOf(parent);
+ const c = order.indexOf(child);
+ if (p === -1 || c === -1) problems.push(`Created Tables does not record both ${parent} and ${child}`);
+ else if (p > c) problems.push(`${child} (has the lookup) was provisioned before ${parent}`);
+ }
+ return resultOf(problems);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): provision-entities.js handles entity creation and column definitions atomically with internal propagation management',
+ ({ fixture }) => {
+ const calls = provisionCalls(fixture);
+ if (!calls.length) return fail('provision-entities.js was not run');
+ const legacy = legacyProvisionCalls(fixture);
+ if (legacy.length) return fail(`per-object scripts were run alongside provision-entities.js: ${legacy[0].call.command.split(/\s/).find((t) => /\.js$/.test(t)) || 'legacy script'}`);
+ if (!calls.some((c) => typeof c.flags.input === 'string' && c.flags.apply === true)) {
+ return fail('provision-entities.js was not run with one --input <json> --apply');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Lookup relationship (cr_candidate → cr_jobrequisition) is provisioned via input JSON; provision-entities.js handles propagation internally',
+ ({ fixture }) => {
+ if (!provisionCalls(fixture).some((c) => typeof c.flags.input === 'string')) return fail('provision-entities.js was not run with --input <json>');
+ if (legacyProvisionCalls(fixture).some((c) => /create-relationship\.js/.test(c.call.command))) {
+ return fail('create-relationship.js was run instead of declaring the lookup in the input JSON');
+ }
+ const log = entityLog(fixture.entityCreationLog);
+ if (!log) return fail('no genpage-entity-creation-log.md (or its legacy alias)');
+ if (!log.relationships.some((r) => suffixOf(r.from) === 'jobrequisition' && suffixOf(r.to) === 'candidate')) {
+ return fail('Created Relationships has no jobrequisition → candidate (1:N) row');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): User is asked about sample data via AskUserQuestion',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ const decision = recordedAnswer(fixture.workflowLog, SAMPLE_DATA_QUESTION);
+ if (!decision) return fail('workflow-log records no answered sample-data question');
+ if (decision.unattended && !isUnattendedLog(fixture.workflowLog)) return fail('sample data was defaulted in an attended run instead of asked');
+ // The answer must be the one acted on: `--sample-data` appears exactly when the maker said yes.
+ const accepted = /^\s*yes\b|\badd\b/i.test(decision.answer) && !/^\s*no\b|\bskip/i.test(decision.answer);
+ const seeded = provisionCalls(fixture).some((c) => c.flags['sample-data'] === true);
+ if (accepted !== seeded) return fail(`maker answered "${decision.answer}" but provisioning ${seeded ? 'seeded' : 'did not seed'} sample data`);
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js input JSON; parent references use $parent/match convention for dependency resolution',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ const decision = recordedAnswer(fixture.workflowLog, SAMPLE_DATA_QUESTION);
+ if (decision && /^\s*no\b|\bskip/i.test(decision.answer)) return skip('maker declined sample data');
+ 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 (legacyProvisionCalls(fixture).some((c) => /create-record\.js/.test(c.call.command))) return fail('rows were created with create-record.js instead of the input JSON');
+ // provision-input.json itself is not captured; the builder's description of it is the record.
+ // `$parent: { entity, match }` is how a child row names its parent row (entity-builder Step 7).
+ if (newTableLookups(fixture.genpagePlan).length && !/\$parent\b[^\n]*\bmatch\b/i.test(fixture.workflowLog)) {
+ return fail('child sample rows do not record the $parent/match parent reference');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/genpage-entity-creation-log.md captures each successful operation',
+ ({ fixture }) => {
+ const { problems, log } = entityLogCoverageProblems(fixture);
+ if (problems.length) return fail(problems[0]);
+ const unreported = log.tables.map((t) => t.resolved).filter((name) => !new RegExp(`\\b${name}\\b`, 'i').test(fixture.workflowLog || ''));
+ if (unreported.length) return fail(`resolved table name(s) not reported back in workflow-log: ${unreported.join(', ')}`);
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 4: pac model genpage generate-types is run with the created entity names',
+ ({ fixture }) => resultOf(generateTypesProblems(fixture, createdTableNames(fixture)))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: Upload includes --data-sources with both created entity names',
+ ({ fixture }) => {
+ const created = createdTableNames(fixture);
+ if (created.length !== 2) return fail(`expected two created tables, the run records ${listText(created)}`);
+ return resultOf(uploadSourcesProblems(fixture, created));
+ }
+);
+
+// --- Eval 10 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan records cr_widget under Entity Creation Required',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ // Matched on the suffix: the section stores suffixes only, and the prefix is the selected
+ // publisher's (`### widget` + `Publisher Prefix: cnt` is the same request as cr_widget).
+ if (!planEntityBlocks(fixture.genpagePlan).some((b) => b.suffix === 'widget')) {
+ return fail('## Entity Creation Required has no "### widget" block');
+ }
+ if (existingEntities(fixture.genpagePlan).some((name) => suffixOf(name) === 'widget')) {
+ return fail('## Existing Entities lists the widget table the plan is creating');
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2a: Orchestrator runs scripts/check-auth.js BEFORE invoking entity-builder; parses the returned JSON',
+ // authGateProblems rejects an auth call whose result is missing or not a parsed { ok } object,
+ // and any builder dispatch or provisioning call not preceded by a successful gate.
+ ({ fixture }) => checkProblems(authGateProblems(fixture, { required: true }))
+);
+
+// --- Eval 11 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes 3 pages in the Pages table with distinct file names and purposes',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length !== 3) return fail(`## Pages has ${rows.length} row(s), expected 3`);
+ const distinct = (values) => new Set(values.map((v) => v.trim().toLowerCase())).size === values.length;
+ if (!distinct(rows.map((r) => r.file))) return fail(`## Pages file names are not distinct: ${rows.map((r) => r.file).join(', ')}`);
+ if (rows.some((r) => !r.purpose.trim()) || !distinct(rows.map((r) => r.purpose))) return fail('## Pages purposes are missing or repeated');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Per-Page Specifications section has an entry for each of the 3 pages',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length !== 3) return fail(`## Pages has ${rows.length} row(s), expected 3`);
+ const blocks = parsePerPageBlocks(planSection(fixture.genpagePlan, 'Per-Page Specifications') || '');
+ const missing = rows.filter((r) => !blocks.has(r.page)).map((r) => r.page);
+ return missing.length ? fail(`## Per-Page Specifications has no "### ${missing[0]}" entry`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5a: Orchestrator validates the plan — at least one page, unique filenames, each page has a matching Per-Page Specifications subsection',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ // The gate's observable outcome is what is graded: a plan that fails any Phase 5a rule must not
+ // reach the builders. The rules are the plan-schema validator's (Pages table, page-file targets,
+ // one matching Per-Page Specifications subsection per row) plus the at-least-one-page rule.
+ const codes = new Set(['missing-pages-table', 'duplicate-page-file', 'invalid-page-file', 'missing-page-spec', 'extra-page-spec', 'page-file-mismatch']);
+ const problems = validateGenpagePlanSchema(fixture.genpagePlan).filter((e) => codes.has(e.code)).map((e) => e.message);
+ if (!pageRowsOf(fixture.genpagePlan).length) problems.unshift('plan has no pages');
+ if (!problems.length) return pass();
+ const built = (fixture.files || []).length > 0 || workflowCalls(fixture).some((c) => /genpage-page-builder/.test(c.command));
+ return built ? fail(`pages were built from a plan that fails Phase 5a: ${problems[0]}`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 4: pac model genpage generate-types is run ONCE with --data-sources 'contact,appointment'; a single RuntimeTypes.ts is generated",
+ ({ fixture }) => {
+ const calls = generateTypesCalls(fixture);
+ if (calls.length !== 1) return fail(`generate-types ran ${calls.length} time(s), expected once`);
+ const problems = generateTypesProblems(fixture, ['contact', 'appointment'], { exact: true });
+ if (problems.length) return fail(problems[0]);
+ const output = fileName(calls[0].flags['output-file']);
+ return output === 'RuntimeTypes.ts' ? pass() : fail(`generate-types wrote ${output || 'no --output-file'}, not RuntimeTypes.ts`);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5c: Each builder receives a distinct target filename — no two builders target the same file',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length < 2) return skip('single-page plan — no parallel builders');
+ const targets = rows.map((r) => r.file.trim().toLowerCase());
+ const dup = targets.find((file, i) => targets.indexOf(file) !== i);
+ if (dup) return fail(`two pages target ${dup}`);
+ // A shared target leaves one page's file missing and the other overwritten.
+ const missing = rows.filter((r) => !(fixture.files || []).some((f) => f.name === r.file)).map((r) => r.file);
+ if (missing.length) return fail(`no builder wrote ${missing.join(', ')}`);
+ // When the dispatch is logged (`- Builder A target: candidate-list.tsx`), those targets too.
+ const logged = [...String(fixture.workflowLog || '').matchAll(/\btarget:\s*`?([\w.-]+\.tsx)\b/gi)].map((m) => m[1].toLowerCase());
+ const loggedDup = logged.find((file, i) => logged.indexOf(file) !== i);
+ return loggedDup ? fail(`two builders were dispatched with target ${loggedDup}`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5c: Each builder reads the same genpage-plan.md but extracts only its own page specification',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length < 2) return skip('single-page plan — no parallel builders');
+ // The dispatch prompts are not captured, so this grades the consequence: each page binds only
+ // the tables ITS OWN specification declares, never a sibling's. `usersettings` is exempt —
+ // references/localization.md mandates it on every localized page and it is never a page entity.
+ const blocks = parsePerPageBlocks(planSection(fixture.genpagePlan, 'Per-Page Specifications') || '');
+ for (const row of rows) {
+ const block = blocks.get(row.page);
+ if (!block) return fail(`## Per-Page Specifications has no "### ${row.page}" entry`);
+ const file = (fixture.files || []).find((f) => f.name === row.file);
+ if (!file) return fail(`${row.file} was not generated`);
+ const declared = csvList((bulletFieldValues(block.lines, 'Entities')[0] || '').replace(/\([^)]*\)/g, ''));
+ const foreign = boundTables(file.content).filter((t) => t !== 'usersettings' && !declared.includes(t));
+ if (foreign.length) return fail(`${row.file} binds ${foreign.join(', ')}, which its own specification (Entities: ${listText(declared)}) does not declare`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5c: Each builder reads the same RuntimeTypes.ts for column verification',
+ ({ fixture }) => {
+ const calls = generateTypesCalls(fixture);
+ if (!calls.length) return fail('pac model genpage generate-types was not run');
+ const outputs = new Set(calls.map((c) => String(c.flags['output-file'] || '').replace(/\\/g, '/').toLowerCase()));
+ if (outputs.size !== 1) return fail(`builders could read different schemas: generate-types wrote ${[...outputs].join(', ')}`);
+ // Every Dataverse page resolves its types from the one sibling module the run generated.
+ const rows = pageRowsOf(fixture.genpagePlan);
+ const dataverse = rows.filter((r) => !/mock/i.test(r.entities));
+ const unshared = dataverse.map((r) => (fixture.files || []).find((f) => f.name === r.file))
+ .filter((f) => !f || !/from\s+['"]\.\/RuntimeTypes['"]/.test(f.content));
+ if (unshared.length) return fail(`${unshared[0]?.name || 'a Dataverse page'} does not import the shared ./RuntimeTypes`);
+ return pass();
+ }
+);
+
+// Every planned page has exactly ONE create upload (no --page-id) whose --code-file is that page's
+// file, and no create targets an unplanned file. Phase 6.5 updates are graded separately. When a
+// create's result was recorded it must have succeeded with a page id no sibling shares — two pages
+// collapsing into one id is what a shared file name would have caused.
+function createUploadProblems(fixture, rows) {
+ const creates = uploadCalls(fixture).filter((u) => !u.update);
+ for (const row of rows) {
+ const n = creates.filter((u) => u.file === row.file).length;
+ if (n !== 1) return [`${row.file} has ${n} create upload(s) with --code-file pointing at it, expected 1`];
+ }
+ const stray = creates.filter((u) => !rows.some((r) => r.file === u.file));
+ if (stray.length) return [`create upload with --code-file ${stray[0].file || 'missing'} matches no planned page`];
+ // Historical captures summarize results in prose (Phase 6 "results" sections), so only a
+ // contract-2 event's associated result is read here.
+ const results = creates.filter((u) => !u.call.historical).map((u) => resultObject(u.call)).filter(Boolean);
+ if (results.some((r) => r.ok === false)) return ['a create upload failed'];
+ const ids = results.map((r) => String(r.pageId || '').toLowerCase()).filter(Boolean);
+ if (new Set(ids).size !== ids.length) return [`two create uploads returned the same page id ${ids.find((id, i) => ids.indexOf(id) !== i)}`];
+ return [];
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: All 3 pages are deployed via separate pac model genpage upload commands, each with the correct --code-file',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length !== 3) return fail(`## Pages has ${rows.length} row(s), expected 3`);
+ return resultOf(createUploadProblems(fixture, rows));
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5c: Cross-page navigation (e.g., candidate list → candidate detail) uses quoted `"PAGEREF_<filename>"` placeholders, never invented GUIDs',
+ ({ fixture }) => {
+ const files = fixture.files || [];
+ if (files.length <= 1) return skip('single-page fixture');
+ const legacy = navigationPhaseOf(fixture) === 'legacy-authored';
+ if (!files.some((f) => navTargets(f.content, { legacy }).length)) return skip('no cross-page navigation in this build');
+ // The same oracle as the common navigation assertion: before resolution every target is a
+ // sibling PAGEREF; after it, every literal is an id from the deployed page map.
+ return gradeEvidence(navigationProblems, fixture);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6.5: If any .tsx contains PAGEREF_ tokens, orchestrator builds a filename→page-id map sorted by length desc, replaces quoted `"PAGEREF_<name>"` tokens with the matching GUID (word-boundary safe), and re-uploads only affected files with the full update flag set',
+ ({ fixture }) => {
+ if (fixture.manifest?.navigation) return gradeEvidence(navigationProblems, fixture);
+ const affected = pagerefFiles(fixture);
+ if (!affected.length) return skip('no .tsx carries a PAGEREF_ navigation target');
+ // The sort order is internal to the substitution; its observable result — every resolved target
+ // is the deployed id of the sibling it named — is what navigationProblems checks.
+ const nav = navigationProblems(fixture);
+ if (nav.length) return fail(nav[0]);
+ const uploads = uploadCalls(fixture);
+ const updates = uploads.filter((u) => u.update);
+ const reuploaded = updates.map((u) => u.file);
+ const twice = reuploaded.find((file, i) => reuploaded.indexOf(file) !== i);
+ if (twice) return fail(`${twice} was re-uploaded more than once`);
+ if (!sameSet(reuploaded, affected)) return fail(`Phase 6.5 re-uploaded ${listText(reuploaded)}, but the affected files are ${listText(affected)}`);
+ const returned = new Set([...String(fixture.workflowLog || '').matchAll(/page-id\s*[=:]\s*`?([0-9a-f-]{36})/gi)].map((m) => m[1].toLowerCase()));
+ for (const u of updates) {
+ const missing = ['app-id', 'page-id', 'code-file'].filter((flag) => !u.flags[flag]);
+ if (!u.flags.prompt && !u.flags['prompt-file']) missing.push('prompt');
+ if (!u.flags['agent-message'] && !u.flags['agent-message-file']) missing.push('agent-message');
+ if (missing.length) return fail(`${u.file}: re-upload lacks --${missing.join(', --')}`);
+ if (u.flags['add-to-sitemap']) return fail(`${u.file}: re-upload passes --add-to-sitemap`);
+ // Raw pac persists exactly the data sources it is given, so an update that drops them unbinds.
+ const create = uploads.find((c) => !c.update && c.file === u.file);
+ if (create && !sameSet(u.sources, create.sources)) return fail(`${u.file}: re-upload --data-sources ${listText(u.sources)} differs from its create (${listText(create.sources)})`);
+ if (isGuid(u.flags['page-id']) && !returned.has(u.flags['page-id'].toLowerCase())) return fail(`${u.file}: --page-id ${u.flags['page-id']} was never returned by an upload`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 6.5: Re-upload uses a DELTA --prompt (e.g. 'Resolve cross-page navigation placeholders to real page GUIDs') — NOT a copy of the original page description from Phase 6",
+ ({ fixture }) => {
+ const uploads = uploadCalls(fixture);
+ const updates = uploads.filter((u) => u.update);
+ if (!updates.length) return skip('no Phase 6.5 re-upload recorded');
+ const requirements = normalized(planSection(fixture.genpagePlan, 'User Requirements'));
+ for (const u of updates) {
+ const prompt = uploadPrompt(fixture, u);
+ if (!prompt) return fail(`${u.file}: re-upload records no prompt`);
+ if (requirements && normalized(prompt).includes(requirements)) return fail(`${u.file}: re-upload prompt restates ## User Requirements`);
+ const create = uploads.find((c) => !c.update && c.file === u.file);
+ const original = create && uploadPrompt(fixture, create);
+ if (original && normalized(original) === normalized(prompt)) return fail(`${u.file}: re-upload prompt repeats the create prompt`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6.5: Unresolved PAGEREF tokens (typos, missing siblings) cause an explicit error to the user — never silently shipped',
+ ({ fixture }) => {
+ if (fixture.manifest?.navigation) return gradeEvidence(navigationProblems, fixture);
+ const phase = navigationPhaseOf(fixture);
+ const legacy = phase === 'legacy-authored';
+ const siblings = new Set((fixture.files || []).map((f) => f.name.replace(/\.tsx$/i, '')));
+ const shipped = [];
+ const unresolved = [];
+ let seen = false;
+ for (const file of fixture.files || []) {
+ for (const t of navTargets(file.content, { legacy })) {
+ const token = t.kind === 'pageref' || (legacy && t.kind === 'pageref-malformed');
+ if (token || t.kind === 'literal') seen = true;
+ // The resolver substitutes only the canonical double-quoted token, so a malformed one would
+ // reach the deployed page verbatim.
+ if (!token && t.kind === 'pageref-malformed') shipped.push(`${file.name}: PAGEREF_${t.key} is not a resolvable double-quoted token`);
+ else if (token && phase === 'resolved') shipped.push(`${file.name}: PAGEREF_${t.key} remains after resolution`);
+ else if (token && !siblings.has(t.key)) unresolved.push({ file: file.name, key: t.key });
+ }
+ }
+ if (!seen) return skip('no cross-page navigation in this build');
+ if (shipped.length) return fail(`${shipped[0]} — an unresolved token was shipped`);
+ for (const { file, key } of unresolved) {
+ if (!new RegExp(`PAGEREF_${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^\\n]*(?:unresolved|no matching|missing)|(?:unresolved|no matching|missing)[^\\n]*PAGEREF_${key}`, 'i').test(fixture.workflowLog || '')) {
+ return fail(`${file}: PAGEREF_${key} names no sibling page and no error was reported`);
+ }
+ if (uploadCalls(fixture).some((u) => u.update && u.file === file)) return fail(`${file}: re-uploaded despite unresolved PAGEREF_${key}`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 8: Summary table lists all 3 pages with their files, entities, and deployment status',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length !== 3) return fail(`## Pages has ${rows.length} row(s), expected 3`);
+ const section = headingSection(fixture.workflowLog, /^#{2,3}\s+Phase\s*8\b/i);
+ if (section === null) return fail('workflow-log has no Phase 8 summary');
+ const summary = parseMarkdownRows(section, ['Page', 'File', 'Entities', 'Status']);
+ if (!summary.length) return fail('Phase 8 has no | Page | File | Entities | Status | table');
+ const uploads = uploadCalls(fixture);
+ for (const row of rows) {
+ const line = summary.find((s) => fileName(s.file.replace(/`/g, '')) === row.file);
+ if (!line) return fail(`Phase 8 summary does not list ${row.file}`);
+ if (!line.status.trim()) return fail(`Phase 8 summary gives ${row.file} no deployment status`);
+ // The entities the page was actually deployed with, else (no upload recorded) the plan's.
+ const create = uploads.find((u) => !u.update && u.file === row.file);
+ const expected = create ? create.sources : csvList(row.entities);
+ if (!sameSet(csvList(line.entities), expected)) return fail(`Phase 8 lists ${row.file} with entities ${line.entities}, deployed with ${listText(expected)}`);
+ }
+ return pass();
+ }
+);
+
+// --- Eval 13 -----------------------------------------------------------------------------------
+
+// LCIDs in the recorded `pac model list-languages` output. Two shapes are captured:
+// 1033 English (United States) en-US No (the PAC table)
+// English (United States) (1033, en-US), Arabic (Saudi Arabia) (1025, ar-SA) (a summary)
+// An LCID counts only next to a language tag, so a version or row count never does.
+function detectedLanguages(fixture) {
+ const calls = commandCalls(fixture, LIST_LANGUAGES);
+ if (!calls.length) return null;
+ const text = calls.map((c) => c.text).join('\n');
+ return [...new Set([...text.matchAll(/\b(\d{4,5})\b[^\n]{0,60}?\b[a-z]{2,3}-[A-Z]{2,4}\b/g)].map((m) => Number(m[1])))];
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English',
+ ({ fixture }) => {
+ const lcids = detectedLanguages(fixture);
+ if (lcids === null) return fail('pac model list-languages was not run');
+ const missing = [1033, 1025, 1036].filter((id) => !lcids.includes(id));
+ return missing.length ? fail(`recorded list-languages output lacks LCID ${missing.join(', ')} (saw ${listText(lcids)})`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes a Localization section listing detected languages',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const lcids = detectedLanguages(fixture);
+ if (lcids === null) return fail('pac model list-languages was not run, so no languages were detected');
+ const section = headingSection(fixture.genpagePlan, /^#{2,3}\s+Localization\s*$/i);
+ if (section === null) return fail('plan has no Localization section');
+ const missing = lcids.filter((id) => !new RegExp(`\\b${id}\\b`).test(section));
+ return missing.length ? fail(`Localization section does not list detected LCID ${missing.join(', ')}`) : pass();
+ }
+);
+
+// --- Eval 15 -----------------------------------------------------------------------------------
+
+// A choice column as Dataverse holds it after provisioning, read from the RuntimeTypes.ts that
+// generate-types wrote from the live schema — the plan and the input JSON only say what was asked.
+function picklistResult(fixture, tableSuffix, columnSuffix, { labels = null, count }) {
+ if (!fixture.runtimeTypes) return skip('RuntimeTypes.ts was not captured');
+ const found = choiceEnum(fixture.runtimeTypes, tableSuffix, columnSuffix);
+ if (!found) return fail(`RuntimeTypes.ts registers no ${tableSuffix}-${columnSuffix} choice`);
+ if (!found.members) return fail(`RuntimeTypes.ts has no body for enum ${found.name}`);
+ const values = found.members.map((m) => m.value);
+ if (found.members.length !== count) return fail(`${found.key} has ${found.members.length} option(s), expected ${count}`);
+ if (values.some((value, i) => value !== 100000000 + i)) return fail(`${found.key} values are ${values.join(', ')}, expected ${count} consecutive from 100000000`);
+ if (labels && found.members.some((m, i) => m.label !== labels[i])) {
+ return fail(`${found.key} options are ${found.members.map((m) => `${m.label}=${m.value}`).join(', ')}`);
+ }
+ return pass();
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): cr_ticket is identified as NOT existing',
+ ({ fixture }) => resultOf(missingEntityProblems(fixture, ['cr_ticket']))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes choice column definitions for priority and status under Choice Columns, with numeric option values starting at 100000000',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const block = planEntityBlocks(fixture.genpagePlan).find((b) => b.suffix === 'ticket');
+ if (!block) return fail('## Entity Creation Required has no "### ticket" block');
+ for (const name of ['priority', 'status']) {
+ const choice = block.choices.find((c) => c.suffix === name);
+ if (!choice) return fail(`Choice Columns has no ${name} row`);
+ if (!choice.options.length) return fail(`${name} lists no "Label (value)" options`);
+ const values = choice.options.map((o) => o.value);
+ if (values.some((value, i) => value !== 100000000 + i)) return fail(`${name} option values ${values.join(', ')} do not run from 100000000`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes a datetime column for due date',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const block = planEntityBlocks(fixture.genpagePlan).find((b) => b.suffix === 'ticket');
+ if (!block) return fail('## Entity Creation Required has no "### ticket" block');
+ const due = block.columns.find((c) => /due/.test(c.suffix));
+ if (!due) return fail('ticket defines no due-date column');
+ return /\bdate\s*(?:time|only)?\b/i.test(due.type) ? pass() : fail(`${due.suffix} has type ${due.type}, not datetime`);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Solution selection question is asked (because new entity will be created) and recorded in ## Environment',
+ ({ fixture }) => resultOf(solutionChoiceProblems(fixture))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2a: scripts/check-auth.js returns ok:true before entity-builder is invoked',
+ ({ fixture }) => {
+ const problems = authGateProblems(fixture, { required: true });
+ if (problems.length) return fail(problems[0]);
+ const calls = workflowCalls(fixture);
+ const builderAt = calls.findIndex((c) => BUILDER_CALL.test(c.command));
+ if (builderAt === -1) return fail('entity-builder was never invoked');
+ const gate = calls.slice(0, builderAt).filter((c) => isAuth(c.command)).at(-1);
+ return resultObject(gate || {})?.ok === true ? pass() : fail('the last check-auth.js result before the entity-builder is not ok:true');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)',
+ ({ fixture }) => picklistResult(fixture, 'ticket', 'priority', { count: 4, labels: ['Low', 'Medium', 'High', 'Critical'] })
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000',
+ ({ fixture }) => picklistResult(fixture, 'ticket', 'status', { count: 4 })
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration',
+ ({ fixture }) => {
+ const calls = provisionCalls(fixture);
+ if (!calls.length) return fail('provision-entities.js was not run');
+ if (!calls.some((c) => typeof c.flags.input === 'string')) return fail('provision-entities.js was not run with --input <json>');
+ if (legacyProvisionCalls(fixture).length) return fail('per-object scripts were run instead of the input JSON');
+ const solution = planSolution(fixture.genpagePlan);
+ if (!solution) return fail('plan ## Environment declares no Solution');
+ // provision-entities.js reads the solution from the JSON; an explicit flag must not contradict it.
+ const flagged = calls.find((c) => typeof c.flags.solution === 'string' && c.flags.solution !== solution);
+ if (flagged) return fail(`provision-entities.js --solution ${flagged.flags.solution} contradicts Solution: ${solution}`);
+ const log = entityLog(fixture.entityCreationLog);
+ if (log?.solution && log.solution !== solution) return fail(`transaction log records Solution: ${log.solution}, plan declares ${solution}`);
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Transaction log (genpage-entity-creation-log.md) records each create with its returned metadataId',
+ ({ fixture }) => {
+ const { problems, log } = entityLogCoverageProblems(fixture);
+ if (problems.length) return fail(problems[0]);
+ // provision-entities.js returns logical/schema names but no metadata ids, so the entity-builder
+ // (Step 5) records `Metadata ID: n/a (SDK does not surface metadata ids)`. A GUID or that
+ // documented n/a is a recorded value; an empty cell or a `...` placeholder is not.
+ const recorded = (value) => /^(?:n\/a\b.*|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(String(value || '').trim());
+ const table = log.tables.find((t) => !recorded(t.metadataId));
+ if (table) return fail(`Created Tables ${table.resolved || table.title} has Metadata ID ${table.metadataId || 'missing'}`);
+ const column = log.columns.find((c) => !recorded(c.metadataId));
+ return column ? fail(`Created Columns ${column.resolved} has Metadata ID ${column.metadataId ?? 'missing'}`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 4: pac model genpage generate-types picks up the enum registrations',
+ ({ fixture }) => {
+ const problems = generateTypesProblems(fixture, createdTableNames(fixture));
+ if (problems.length) return fail(problems[0]);
+ if (!fixture.runtimeTypes) return skip('RuntimeTypes.ts was not captured');
+ const blocks = planEntityBlocks(fixture.genpagePlan);
+ if (!blocks.some((b) => b.choices.length)) return fail('plan defines no choice columns whose enums could be registered');
+ for (const block of blocks) {
+ for (const choice of block.choices) {
+ const found = choiceEnum(fixture.runtimeTypes, block.suffix, choice.suffix);
+ if (!found?.members) return fail(`RuntimeTypes.ts EnumRegistrations has no ${block.suffix}-${choice.suffix} entry`);
+ const want = choice.options.map((o) => o.value).join(',');
+ const got = found.members.map((m) => m.value).join(',');
+ if (want !== got) return fail(`${found.key} values ${got} differ from the plan's ${want}`);
+ }
+ }
+ return pass();
+ }
+);
+
+// --- Eval 19 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names',
+ ({ fixture }) => {
+ if (!fixture.workflowLog) return fail('no workflow-log.md');
+ const calls = workflowCalls(fixture);
+ const at = (pattern) => calls.findIndex((c) => pattern.test(c.command));
+ const download = commandCalls(fixture, /\bpac(?:\.exe|\.cmd)?\s+model\s+genpage\s+download\b/)[0];
+ if (!download) return fail('pac model genpage download was not run, so no page was selected');
+ 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);
+ if (!lists.length) return fail(`pac model genpage list --app-id ${app || '<selected>'} was not run`);
+ // The edited page must come from that listing's recorded output, not from a guess. The call's
+ // text also carries the selection that followed it (`- User selected "Seattle Weather"
+ // (\`bb22…\`)`), which restates the id and so cannot count as the listing:
+ // - `pac model genpage list --app-id aa11…` → 2 pages found:
+ // - Seattle Weather — `bb223344-2233-2233-2233-bbccddee2345`
+ 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(/\bpac(?:\.exe|\.cmd)?\s+model\s+list(?![\w-])/);
+ // 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 pac model list');
+ if (listAt > positionOf(download)) return fail('the page was downloaded before pages were listed');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)',
+ ({ fixture }) => {
+ const log = fixture.workflowLog || '';
+ if (!fixture.genpageEditPlan && !/\bEdit\s+Phase\b/i.test(log)) return skip('create flow — no genpage-edit-plan.md is written');
+ // The loader reads genpage-edit-plan.md from the fixture root only, so its presence there is
+ // the root write; a copy under the downloaded `<page-id>/` folder is the regression.
+ if (!fixture.genpageEditPlan) return fail('genpage-edit-plan.md is not at the working-directory root');
+ if (/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[\\/]+genpage-edit-plan\.md/i.test(log)) {
+ return fail('workflow-log records genpage-edit-plan.md written inside the <page-id>/ folder');
+ }
+ let nested = [];
+ try {
+ nested = fs.readdirSync(fixture.dir, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(fixture.dir, entry.name, 'genpage-edit-plan.md')))
+ .map((entry) => entry.name);
+ } catch { /* a fixture object without a directory on disk has no nested copy to find */ }
+ return nested.length ? fail(`genpage-edit-plan.md also exists inside ${nested[0]}/`) : pass();
+ }
+);
+
+// ---------------------------------------------------------------------------------------------
+// Evals 3, 8, 9, 12, 14 and 16 — current contract-2 traces
+// ---------------------------------------------------------------------------------------------
+//
+// These fixtures record commands as ordered tool-result events and the conversation (questions,
+// plan presentations) in workflow-log.md, so checks read commands through workflowCalls/commandCalls
+// and the conversation through conversationSteps or the log lines.
+
+const PAC_MODEL_LIST = /\bpac(?:\.exe|\.cmd)?\s+model\s+list(?![\w-])/;
+const PAC_MODEL_CREATE = /\bpac(?:\.exe|\.cmd)?\s+model\s+create\b/;
+const GENPAGE_DOWNLOAD = /\bpac(?:\.exe|\.cmd)?\s+model\s+genpage\s+download\b/;
+const PAGE_FILES_GATE = /\bcheck-page-files\.js\b/;
+const WORKER_STAMP = /\bgenpage-worker-output\.js\b[^\n]*--stamp\b/;
+const PAGE_BUILDER = /\b(?:Task|Dispatched)\s+genpage-page-builder\b/;
+const PROVENANCE_VERIFY = /\bgenpage-plan-provenance\.js\b[^\n]*\bverify\b/;
+const PROVENANCE_PREPARE = /\bgenpage-plan-provenance\.js\b[^\n]*\bprepare\b/;
+
+function artifactOrNull(fixture, name) {
+ try { return artifactText(fixture, name); } catch { return null; }
+}
+
+// Index of a commandCalls entry inside workflowCalls (commandCalls re-reads the evidence, so match on
+// the recorded command text).
+function callIndex(fixture, entry) {
+ return entry ? workflowCalls(fixture).findIndex((c) => c.command === entry.call.command) : -1;
+}
+
+// The answer recorded with a question step: `… → <answer>` in a log line, or `"answer":"<answer>"`
+// in an AskUserQuestion tool-result event.
+function answerOf(step) {
+ const json = /"answer"\s*:\s*"([^"]*)"/.exec(step);
+ if (json) return json[1];
+ const arrow = /(?:\u2192|->)\s*(.+)$/m.exec(step);
+ return arrow ? arrow[1].trim() : null;
+}
+
+// The app and page the edit flow actually downloaded (`pac model genpage download --app-id --page-id`).
+function downloadTarget(fixture) {
+ const entry = commandCalls(fixture, GENPAGE_DOWNLOAD)[0];
+ if (!entry) return null;
+ return { entry, app: String(entry.flags['app-id'] || '').toLowerCase(), page: String(entry.flags['page-id'] || '').toLowerCase() };
+}
+
+// The question that follows a PAC listing must offer the listing's own rows — each offered GUID is
+// one the listing returned, shown with the name the listing gave it — and the item the run went on
+// with must be one of them. A log may record only the option the maker picked, so the check grades
+// what was offered and chosen, not whether every listed row appeared.
+function presentedFromListingProblems(fixture, { listing, noun, selected }) {
+ const entry = commandCalls(fixture, listing).at(-1);
+ if (!entry) return [`the ${noun} listing command was not run`];
+ const rows = listingRows(entry.call);
+ if (!rows.length) return [`the ${noun} listing recorded no ${noun}s to present`];
+ const steps = conversationSteps(fixture);
+ const listedAt = steps.findIndex((s) => listing.test(s));
+ const question = steps.slice(listedAt + 1).find((s) => /AskUserQuestion/.test(s));
+ if (!question) return [`no AskUserQuestion followed the ${noun} listing`];
+ const offered = [...new Set([...question.matchAll(new RegExp(GUID_RE.source, 'gi'))].map((m) => m[0].toLowerCase()))];
+ if (!offered.length) return [`the ${noun} question offers no ${noun} id from the listing`];
+ for (const id of offered) {
+ const row = rows.find((r) => r.id === id);
+ if (!row) return [`the ${noun} question offers ${id}, which the listing does not contain`];
+ if (row.name && !question.includes(row.name)) return [`the ${noun} question offers ${id} without its listed name "${row.name}"`];
+ }
+ if (selected && !rows.some((r) => r.id === selected)) return [`the ${noun} the run continued with (${selected}) is not in the listing`];
+ if (selected && !offered.includes(selected)) return [`the ${noun} the run continued with (${selected}) was not among the offered ${noun}s`];
+ return [];
+}
+
+// A lookup from the new table `child` to the new table `parent`, declared in the child's block.
+function planLookupProblems(plan, child, parent) {
+ if (!plan) return ['no genpage-plan.md'];
+ const blocks = planEntityBlocks(plan);
+ for (const suffix of [child, parent]) if (!blocks.some((b) => b.suffix === suffix)) return [`## Entity Creation Required has no "### ${suffix}" definition`];
+ return newTableLookups(plan).some((l) => l.child === child && l.parent === parent) && blocks.find((b) => b.suffix === child).relationships.some((r) => r.related === parent && r.lookup)
+ ? []
+ : [`${child} has no lookup relationship to ${parent}`];
+}
+
+// provision-input.json, when captured: the App Spec the entity-builder handed provision-entities.js.
+function provisionInput(fixture) {
+ const entry = provisionCalls(fixture).find((c) => typeof c.flags.input === 'string');
+ const name = entry ? fileName(String(entry.flags.input).replace(/^@/, '')) : 'provision-input.json';
+ const text = artifactOrNull(fixture, name);
+ if (text === null) return null;
+ try { return JSON.parse(text.replace(/^\uFEFF/, '')); } catch { return undefined; }
+}
+
+const schemaSuffix = (name) => suffixOf(String(name || '').toLowerCase());
+
+// Plan presentations and their outcomes, in log order. Shapes recorded by the skill:
+// - EnterPlanMode called with the initial plan:
+// - ExitPlanMode called → changes requested (revised): "add a search box in addition to …"
+// - Task genpage-planner re-invoked with the revision request …
+// - ExitPlanMode called → approved
+// - `node scripts\genpage-plan-provenance.js prepare --plan genpage-plan.md` (the plan write starts)
+function planModeEvents(log) {
+ const events = [];
+ String(log || '').split(/\r?\n/).forEach((line, at) => {
+ if (/\bEnterPlanMode\b/.test(line) && !/\bnot\b/i.test(line)) events.push({ at, kind: 'present', line });
+ else if (/\bExitPlanMode\b/.test(line)) {
+ const kind = /changes?\s+requested|\brevis|\breject/i.test(line) ? 'changes' : /\bapproved\b/i.test(line) ? 'approved' : 'unknown';
+ events.push({ at, kind, line });
+ } else if (PROVENANCE_PREPARE.test(line)) events.push({ at, kind: 'write', line });
+ else if (/\bgenpage-planner\b/.test(line) && /\b(?:re-?invoked|Task|Dispatched)\b/i.test(line)) events.push({ at, kind: 'planner', line });
+ });
+ return events;
+}
+
+function stalePlans(fixture) {
+ return Object.entries(fixture.artifacts || {})
+ .filter(([name]) => /^\.genpage-provenance\/genpage-plan\.stale-[^/]+\.md$/.test(name))
+ .map(([, text]) => text);
+}
+
+// The first plan the run approved: the quarantined copy when the plan was rewritten, else the plan.
+function initialPlan(fixture) {
+ return stalePlans(fixture)[0] ?? fixture.genpagePlan;
+}
+
+const sameTargets = (a, b) => Boolean(a && b) && a.kind === b.kind && a.targets.join('\n') === b.targets.join('\n');
+const sortedFiles = (files) => [...files].map((f) => String(f).trim()).sort();
+const pageFilesOf = (plan) => pageRowsOf(plan).map((r) => r.file);
+
+// --- Eval 3 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 1a: Apps are presented to the user via AskUserQuestion using the actual Display Name and app-id GUID from pac model list output',
+ ({ fixture }) => resultOf(presentedFromListingProblems(fixture, { listing: PAC_MODEL_LIST, noun: 'app', selected: downloadTarget(fixture)?.app }))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 1b: Pages are presented to the user via AskUserQuestion using the actual page names and page-id GUIDs from pac model genpage list output',
+ ({ fixture }) => resultOf(presentedFromListingProblems(fixture, { listing: GENPAGE_LIST, noun: 'page', selected: downloadTarget(fixture)?.page }))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 1c: Selection is restated to the user before proceeding to download',
+ ({ fixture }) => {
+ const target = downloadTarget(fixture);
+ if (!target) return fail('pac model genpage download was not run, so nothing was selected');
+ // e.g. `- "Editing **Contacts Directory** (2222…) in app **Sales Hub** (1111…). Continuing to download…"`
+ // — a statement (not a question) naming both selected ids, after the page was chosen and before
+ // the download command.
+ const lines = String(fixture.workflowLog || '').split(/\r?\n/);
+ const downloadAt = lines.findIndex((l) => GENPAGE_DOWNLOAD.test(l));
+ if (downloadAt === -1) return fail('workflow-log does not record the download');
+ let chosenAt = -1;
+ lines.slice(0, downloadAt).forEach((l, i) => { if (/AskUserQuestion/.test(l) && l.toLowerCase().includes(target.page)) chosenAt = i; });
+ const restated = lines.slice(chosenAt + 1, downloadAt).some((l) => !/AskUserQuestion/.test(l)
+ && l.toLowerCase().includes(target.page) && l.toLowerCase().includes(target.app));
+ return restated ? pass() : fail('no restatement of the selected app and page between the selection and the download');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Edit Phase 3: config.json is read; since dataSources contains 'contact', RuntimeTypes.ts is generated",
+ ({ fixture }) => {
+ const target = downloadTarget(fixture);
+ if (!target) return fail('pac model genpage download was not run');
+ const configText = artifactOrNull(fixture, 'before/config.json');
+ if (configText === null) return skip('the downloaded config.json was not captured');
+ let config;
+ try { config = JSON.parse(configText); } catch (error) { return fail(`downloaded config.json is not JSON: ${error.message}`); }
+ const sources = (config.dataSources || []).map((s) => String(s).toLowerCase());
+ if (!sources.includes('contact')) return fail(`downloaded config.json dataSources are ${listText(sources)}, not contact`);
+ if (!/\bconfig\.json\b/.test(headingSection(fixture.workflowLog, /^#{2,3}\s+Edit Phase 3\b/i) || '')) return fail('Edit Phase 3 does not record reading config.json');
+ const types = generateTypesCalls(fixture);
+ const run = types.find((c) => sameSet(c.sources, sources));
+ if (!run) return fail(`generate-types was not run with config.json's dataSources ${listText(sources)} (saw ${types.map((c) => listText(c.sources)).join('; ') || 'none'})`);
+ if (callIndex(fixture, run) < callIndex(fixture, target.entry)) return fail('generate-types ran before the page was downloaded');
+ return fileName(run.flags['output-file']) === 'RuntimeTypes.ts' ? pass() : fail('generate-types did not write RuntimeTypes.ts');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 4: edit-planner reads page.tsx, config.json, and prompt.txt from the <page-id>/ folder',
+ ({ fixture }) => {
+ const plan = fixture.genpageEditPlan;
+ if (!plan) return fail('no genpage-edit-plan.md');
+ const target = downloadTarget(fixture);
+ if (!target) return fail('pac model genpage download was not run');
+ const prompt = artifactOrNull(fixture, 'before/prompt.txt');
+ const configText = artifactOrNull(fixture, 'before/config.json');
+ if (prompt === null || configText === null) return skip('the downloaded <page-id>/ snapshot was not captured');
+ // The edit plan restates what the planner read (agents/genpage-edit-planner.md Step 4):
+ // - **Absolute path:** D:/work/x/<page-id>/page.tsx
+ // - **Original prompt (from prompt.txt):** <the downloaded prompt>
+ // - **Original data sources (from config.json):** contact
+ // so each value is compared with the downloaded file it claims to come from.
+ const field = (label) => new RegExp(`\\*\\*${label}[^*\\n]*\\*\\*\\s*(.+)`, 'i').exec(plan)?.[1].trim() ?? null;
+ const file = String(field('Absolute path') || '').replace(/\\/g, '/').toLowerCase();
+ if (!file.endsWith(`${target.page}/page.tsx`)) return fail(`edit plan's page.tsx (${file || 'none'}) is not inside the downloaded ${target.page}/ folder`);
+ if (normalized(field('Original prompt')) !== normalized(prompt)) return fail('edit plan\'s original prompt differs from the downloaded prompt.txt');
+ let config;
+ try { config = JSON.parse(configText); } catch (error) { return fail(`downloaded config.json is not JSON: ${error.message}`); }
+ const want = (config.dataSources || []).map((s) => String(s).toLowerCase());
+ const got = csvList(field('Original data sources') || '');
+ if (!sameSet(got, want)) return fail(`edit plan's original data sources ${listText(got)} differ from config.json's ${listText(want)}`);
+ const planner = commandCalls(fixture, /\bgenpage-edit-planner\b/)[0];
+ if (planner && callIndex(fixture, planner) < callIndex(fixture, target.entry)) return fail('the edit planner ran before the page was downloaded');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 5: Orchestrator reads genpage-edit-plan.md, rules.md, RuntimeTypes.ts, and page.tsx',
+ ({ fixture }) => {
+ const section = headingSection(fixture.workflowLog, /^#{2,3}\s+Edit Phase 5\b/i);
+ if (section === null) return fail('workflow-log has no Edit Phase 5 section');
+ // `- Orchestrator read genpage-edit-plan.md, references/rules.md, RuntimeTypes.ts and <id>/page.tsx`
+ const reads = section.split(/\r?\n/).filter((l) => /\bread\b/i.test(l)).join('\n');
+ const wanted = ['genpage-edit-plan.md', 'rules.md', 'page.tsx'];
+ // RuntimeTypes.ts exists only when Edit Phase 3 generated it (a mock page has none to read).
+ if (generateTypesCalls(fixture).length) wanted.push('RuntimeTypes.ts');
+ const missing = wanted.filter((name) => !reads.includes(name));
+ return missing.length ? fail(`Edit Phase 5 does not record reading ${missing.join(', ')}`) : pass();
+ }
+);
+
+// The attribute text of every `<Name …>` opening tag in literal-blanked code. Attributes can hold
+// arrow functions (`getRowId={(row) => row.id}`), so the tag ends at the first `>` outside braces,
+// not at the first `>`.
+function openingTags(code, name) {
+ const tags = [];
+ for (const m of code.matchAll(new RegExp(`<${name}\\b`, 'g'))) {
+ let depth = 0;
+ let i = m.index + m[0].length;
+ for (; i < code.length; i += 1) {
+ if (code[i] === '{') depth += 1;
+ else if (code[i] === '}') depth -= 1;
+ else if (code[i] === '>' && depth === 0) break;
+ }
+ tags.push(code.slice(m.index + m[0].length, i));
+ }
+ return tags;
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Edit Phase 5: Search implementation uses Fluent UI V9 SearchBox or Input; sort uses column header handlers',
+ ({ fixture }) => {
+ const page = (fixture.files || []).find((f) => /(?:^|\/)page\.tsx$/.test(f.name)) || (fixture.files || [])[0];
+ if (!page) return fail('no edited page.tsx');
+ // Code view: comments and strings blanked, so a comment naming SearchBox proves nothing.
+ const code = blankLiterals(page.content);
+ const fluent = /import\s*\{([^}]*)\}\s*from\s*['"]@fluentui\/react-components['"]/.exec(page.content)?.[1] || '';
+ const control = ['SearchBox', 'Input'].find((name) => new RegExp(`\\b${name}\\b`).test(fluent) && new RegExp(`<${name}\\b`).test(code));
+ if (!control) return fail(`${page.name}: no Fluent UI V9 SearchBox or Input is imported and rendered`);
+ if (/<(?:input|select|textarea)\b/.test(code)) return fail(`${page.name}: uses a raw HTML form element`);
+ // Header-driven sorting: a sortable DataGrid with a sort handler and per-column compare, or table
+ // header cells with click/sort handlers.
+ const grid = openingTags(code, 'DataGrid').some((attrs) => /\bsortable\b/.test(attrs) && /\bonSortChange\b/.test(attrs)) && /\bcompare\s*:/.test(code);
+ const headers = ['DataGridHeaderCell', 'TableHeaderCell'].some((tag) => openingTags(code, tag).some((attrs) => /\b(?:onClick|sortDirection)\b/.test(attrs)));
+ return grid || headers ? pass() : fail(`${page.name}: columns are not sorted through column header handlers`);
+ }
+);
+
+// --- Eval 8 ------------------------------------------------------------------------------------
+
+function returnedAppId(entry) {
+ const result = entry.call.historical ? null : resultObject(entry.call);
+ const id = result?.appId || GUID_RE.exec(entry.text.split(/\r?\n/).slice(1).join('\n'))?.[0];
+ return id ? String(id).toLowerCase() : null;
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): pac model list returns zero apps',
+ ({ fixture }) => {
+ const entry = commandCalls(fixture, PAC_MODEL_LIST)[0];
+ if (!entry) return fail('pac model list was not run');
+ const rows = listingRows(entry.call);
+ if (rows.length) return fail(`pac model list returned ${rows.length} app(s)`);
+ // Zero rows must be STATED, so an unparsed listing is never mistaken for an empty one:
+ // {"apps":[]} / → no model-driven apps found (0 apps returned)
+ return /"apps"\s*:\s*\[\s*\]|\bno model-driven apps\b|\b0 apps\b/i.test(entry.text) ? pass() : fail('pac model list result does not record zero apps');
+ }
+);
+
+// The create-or-cancel question asked after an empty app listing, with its recorded answer.
+function createAppDecision(fixture) {
+ const steps = conversationSteps(fixture);
+ const listedAt = steps.findIndex((s) => PAC_MODEL_LIST.test(s));
+ if (listedAt === -1) return { problem: 'pac model list was not run' };
+ const question = steps.slice(listedAt + 1).find((s) => /AskUserQuestion/.test(s) && /\bcreate\b/i.test(s) && /\bcancel\b/i.test(s));
+ if (!question) return { problem: 'no AskUserQuestion offered to create a new app or cancel after the app listing' };
+ const answer = answerOf(question);
+ return answer ? { answer, steps, listedAt } : { problem: 'the create-or-cancel answer is not recorded' };
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): User is asked via AskUserQuestion whether to create a new app or cancel',
+ ({ fixture }) => {
+ const decision = createAppDecision(fixture);
+ return decision.problem ? fail(decision.problem) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): Plan records 'create new app' decision",
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const decision = createAppDecision(fixture);
+ if (decision.problem) return fail(decision.problem);
+ if (!/\bcreate\b/i.test(decision.answer) || /\bcancel\b/i.test(decision.answer)) return fail(`maker answered "${decision.answer}", not create`);
+ if (!newAppNeeded(fixture.genpagePlan)) return fail('## Environment does not record "App: create new: <name>"');
+ // When the maker named the app, the plan creates THAT app.
+ const named = decision.steps.slice(decision.listedAt + 1).find((s) => /AskUserQuestion/.test(s) && /\bcalled\b|\bname\b/i.test(s));
+ const name = named && answerOf(named);
+ const app = /^\s*[-*]?\s*App:\s*(.+)$/im.exec(planSection(fixture.genpagePlan, 'Environment') || '')?.[1] || '';
+ return name && !app.includes(name) ? fail(`plan App "${app.trim()}" is not the app the maker named ("${name}")`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Because a new app will be created, the planner asks the solution selection question and records the choice in ## Environment',
+ ({ fixture }) => {
+ if (!newAppNeeded(fixture.genpagePlan)) return fail('plan does not record a new app');
+ return resultOf(solutionChoiceProblems(fixture));
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 3: The new app-id returned from pac model create is stored for Phase 6',
+ ({ fixture }) => {
+ const create = commandCalls(fixture, PAC_MODEL_CREATE)[0];
+ if (!create) return fail('pac model create was not run');
+ const solution = planSolution(fixture.genpagePlan);
+ if (create.flags.solution !== solution) return fail(`pac model create --solution ${create.flags.solution || 'missing'} is not the plan's Solution: ${solution}`);
+ const appId = returnedAppId(create);
+ if (!appId) return fail('pac model create recorded no returned app-id');
+ const upload = uploadCalls(fixture)[0];
+ if (!upload) return fail('no upload consumed the stored app-id');
+ if (callIndex(fixture, upload) < callIndex(fixture, create)) return fail('the first upload ran before the app was created');
+ const used = String(upload.flags['app-id'] || '').toLowerCase();
+ return used === appId ? pass() : fail(`the first upload used --app-id ${used || 'missing'}, not the created ${appId}`);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: Upload uses the newly created app-id',
+ ({ fixture }) => {
+ const create = commandCalls(fixture, PAC_MODEL_CREATE)[0];
+ if (!create) return fail('pac model create was not run');
+ const appId = returnedAppId(create);
+ if (!appId) return fail('pac model create recorded no returned app-id');
+ const uploads = uploadCalls(fixture);
+ if (!uploads.length) return fail('no genpage upload command recorded');
+ const other = uploads.find((u) => String(u.flags['app-id'] || '').toLowerCase() !== appId);
+ if (other) return fail(`${other.file || 'upload'}: --app-id ${other.flags['app-id'] || 'missing'} is not the created app ${appId}`);
+ const result = uploads.map((u) => (u.call.historical ? null : resultObject(u.call))).find((r) => r?.appId && String(r.appId).toLowerCase() !== appId);
+ return result ? fail(`upload result names app ${result.appId}, not the created ${appId}`) : pass();
+ }
+);
+
+// --- Eval 9 ------------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): cr_project and cr_milestone confirmed as NOT existing',
+ ({ fixture }) => resultOf(missingEntityProblems(fixture, ['cr_project', 'cr_milestone']))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan includes a lookup relationship (cr_milestone → cr_project)',
+ ({ fixture }) => resultOf(planLookupProblems(fixture.genpagePlan, 'milestone', 'project'))
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Solution selection question is asked because new entities will be created',
+ ({ fixture }) => {
+ if (!entitiesNeedCreating(fixture.genpagePlan)) return fail('plan schedules no entity creation');
+ return resultOf(solutionChoiceProblems(fixture));
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): cr_project and cr_milestone entities are provisioned with lookup relationship (cr_milestone → cr_project) via provision-entities.js; dependency ordering is handled automatically',
+ ({ fixture }) => {
+ const calls = provisionCalls(fixture).filter((c) => typeof c.flags.input === 'string' && c.flags.apply === true);
+ if (!calls.length) return fail('provision-entities.js was not run with --input <json> --apply');
+ if (legacyProvisionCalls(fixture).length) return fail('per-object scripts were run, so ordering was not left to provision-entities.js');
+ const failed = calls.find((c) => !c.call.historical && resultObject(c.call)?.ok !== true);
+ if (failed) return fail('a provision-entities.js run did not return ok:true');
+ const input = provisionInput(fixture);
+ if (input === undefined) return fail('provision-input.json is not JSON');
+ if (input) {
+ // The App Spec declares both tables and the lookup; the CLI, not the builder, orders them.
+ const tables = (input.entities || []).map((e) => schemaSuffix(e.schemaName));
+ for (const suffix of ['project', 'milestone']) if (!tables.includes(suffix)) return fail(`provision-input.json does not declare ${suffix}`);
+ const rel = (input.relationships || []).some((r) => /^OneToMany$/i.test(r.type)
+ && schemaSuffix(r.referenced || r.referencedEntity) === 'project' && schemaSuffix(r.referencing || r.referencingEntity) === 'milestone');
+ if (!rel) return fail('provision-input.json declares no project → milestone OneToMany relationship');
+ }
+ const log = entityLog(fixture.entityCreationLog);
+ if (!log) return fail('no genpage-entity-creation-log.md');
+ const order = log.tables.map((t) => suffixOf(t.resolved || ''));
+ if (order.indexOf('project') === -1 || order.indexOf('milestone') === -1) return fail('Created Tables does not record both tables');
+ if (order.indexOf('project') > order.indexOf('milestone')) return fail('milestone (has the lookup) was provisioned before project');
+ if (!log.relationships.some((r) => suffixOf(r.from) === 'project' && suffixOf(r.to) === 'milestone')) return fail('Created Relationships has no project → milestone (1:N) row');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Sample data is created because the user explicitly requested it in the prompt',
+ ({ fixture }) => {
+ if (!/\bsample\s+data\b/i.test(planSection(fixture.genpagePlan, 'User Requirements') || '')) return fail('## User Requirements does not ask for sample data');
+ const decision = recordedAnswer(fixture.workflowLog, SAMPLE_DATA_QUESTION);
+ if (!decision) return fail('workflow-log records no answered sample-data question');
+ if (!/^\s*yes\b|\badd\b/i.test(decision.answer) || /^\s*no\b|\bskip/i.test(decision.answer)) return fail(`sample data was requested but the answer was "${decision.answer}"`);
+ 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) => !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 && !Object.values(input.sampleData || {}).some((rows) => Array.isArray(rows) && rows.length)) return fail('provision-input.json carries no sampleData rows');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 2b (Entity Builder): Sample records respect relationships (milestones reference projects via $parent/match convention)',
+ ({ fixture }) => {
+ const input = provisionInput(fixture);
+ if (input === null) return skip('provision-input.json was not captured');
+ if (input === undefined) return fail('provision-input.json is not JSON');
+ // Each child row names its parent row the agents/genpage-entity-builder.md Step 7 way:
+ // "$parent": { "entity": "cr_Project", "match": { "cr_name": "Contoso Website Redesign" } }
+ // and the match must hit a parent row actually seeded in the same input.
+ const entries = Object.entries(input.sampleData || {});
+ const rowsOf = (suffix) => entries.filter(([name]) => schemaSuffix(name) === suffix).flatMap(([, rows]) => rows || []);
+ const parents = rowsOf('project');
+ const children = rowsOf('milestone');
+ if (!parents.length || !children.length) return fail('sampleData does not seed both projects and milestones');
+ for (const [i, row] of children.entries()) {
+ const ref = row.$parent;
+ if (!ref || schemaSuffix(ref.entity) !== 'project' || !ref.match || !Object.keys(ref.match).length) return fail(`milestone row ${i + 1} has no $parent/match reference to a project`);
+ const hit = parents.some((p) => Object.entries(ref.match).every(([k, v]) => p[k] === v));
+ if (!hit) return fail(`milestone row ${i + 1} matches no seeded project (${JSON.stringify(ref.match)})`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: Deployment includes --data-sources with both entity names',
+ ({ fixture }) => {
+ const created = createdTableNames(fixture);
+ if (created.length !== 2) return fail(`expected two created tables, the run records ${listText(created)}`);
+ return resultOf(uploadSourcesProblems(fixture, created));
+ }
+);
+
+// --- Eval 12 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Initial plan is presented via EnterPlanMode',
+ ({ fixture }) => {
+ const events = planModeEvents(fixture.workflowLog);
+ const first = events.find((e) => e.kind === 'present');
+ if (!first) return fail('workflow-log records no EnterPlanMode presentation');
+ const before = events.filter((e) => e.at < first.at).find((e) => ['approved', 'changes', 'write'].includes(e.kind));
+ return before ? fail(`"${before.line.trim()}" precedes the first plan presentation`) : pass();
+ }
+);
+
+// The first outcome after the first presentation, which must be a change request.
+function revisionRequest(log) {
+ const events = planModeEvents(log);
+ const first = events.findIndex((e) => e.kind === 'present');
+ const outcome = first === -1 ? null : events.slice(first + 1).find((e) => ['approved', 'changes', 'unknown'].includes(e.kind));
+ return { events, first, outcome };
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): User requests a revision (ExitPlanMode with changes-requested response)',
+ ({ fixture }) => {
+ const { events, outcome } = revisionRequest(fixture.workflowLog);
+ if (!outcome) return fail('no ExitPlanMode outcome follows the first presentation');
+ if (outcome.kind !== 'changes') return fail(`the first ExitPlanMode outcome is "${outcome.line.trim()}", not a change request`);
+ if (!/["\u201c][^"\u201d]+["\u201d]/.test(outcome.line)) return fail('the change request does not record what the maker asked for');
+ const write = events.find((e) => e.kind === 'write' && e.at < outcome.at);
+ return write ? fail('genpage-plan.md was written before the revision was requested') : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Planner revises the plan based on user feedback and re-enters plan mode',
+ ({ fixture }) => {
+ const { events, outcome } = revisionRequest(fixture.workflowLog);
+ if (!outcome || outcome.kind !== 'changes') return fail('no change request to revise from');
+ const after = events.filter((e) => e.at > outcome.at);
+ const planner = after.find((e) => e.kind === 'planner');
+ const again = after.find((e) => e.kind === 'present');
+ if (!planner) return fail('genpage-planner was not re-invoked after the change request');
+ if (!again) return fail('plan mode was not re-entered after the change request');
+ return planner.at < again.at ? pass() : fail('plan mode was re-entered before the planner revised the plan');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): Revised plan reflects the user's requested changes (search box added)",
+ ({ fixture }) => {
+ const approved = artifactOrNull(fixture, '.approved-genpage-plan.md');
+ if (approved === null) return fail('the approved (revised) plan body .approved-genpage-plan.md was not saved');
+ // The request was a search box IN ADDITION TO the filter toolbar, so both must be in the plan.
+ if (!/\bsearch\s*box\b/i.test(approved)) return fail('the approved revised plan has no search box');
+ if (!/\bfilter\s+toolbar\b/i.test(approved)) return fail('the approved revised plan dropped the filter toolbar');
+ const spec = planSection(fixture.genpagePlan, 'Per-Page Specifications') || '';
+ return /\bSearchBox\b|\bsearch\s*box\b/i.test(spec) ? pass() : fail('genpage-plan.md per-page specification has no search box');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): User approves the revised plan on the second presentation',
+ ({ fixture }) => {
+ const events = planModeEvents(fixture.workflowLog);
+ const presents = events.filter((e) => e.kind === 'present');
+ if (presents.length < 2) return fail(`the plan was presented ${presents.length} time(s)`);
+ const outcomeAfter = (p) => events.find((e) => e.at > p.at && ['approved', 'changes', 'unknown'].includes(e.kind));
+ if (outcomeAfter(presents[0])?.kind !== 'changes') return fail('the first presentation was not answered with a change request');
+ const second = outcomeAfter(presents[1]);
+ if (second?.kind !== 'approved') return fail('the second presentation was not approved');
+ if (presents[2] && presents[2].at < second.at) return fail('a third presentation preceded the approval');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): genpage-plan.md reflects the approved (revised) version, not the initial version',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('no genpage-plan.md');
+ const approved = artifactOrNull(fixture, '.approved-genpage-plan.md');
+ if (approved === null) return fail('the approved plan body .approved-genpage-plan.md was not saved');
+ // The approval preview and the written plan are different documents; what both state is the page
+ // files the run will write (plugins/model-apps/scripts/genpage-plan-provenance.js planTargets).
+ const want = planTargets(approved, { kind: 'create' });
+ const got = planTargets(fixture.genpagePlan, { kind: 'create' });
+ if (!sameTargets(want, got)) return fail(`genpage-plan.md targets ${JSON.stringify(got?.targets)}, the approved plan ${JSON.stringify(want?.targets)}`);
+ // The revision is what separates the approved version from the initial one.
+ if (!/\bsearch\s*box\b|\bSearchBox\b/i.test(fixture.genpagePlan)) return fail('genpage-plan.md is the initial version: it has no search box');
+ const events = planModeEvents(fixture.workflowLog);
+ const approval = events.filter((e) => e.kind === 'approved').at(-1);
+ const write = events.find((e) => e.kind === 'write');
+ if (!approval || !write || write.at < approval.at) return fail('genpage-plan.md was not written after the final approval');
+ const verify = commandCalls(fixture, PROVENANCE_VERIFY).at(-1);
+ if (!verify || !/approved-genpage-plan\.md/.test(String(verify.flags.approved || ''))) return fail('genpage-plan.md was not provenance-verified against the approved body');
+ return resultObject(verify.call)?.ok === true ? pass() : fail('provenance verification of genpage-plan.md did not pass');
+ }
+);
+
+// --- Eval 14 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): Plan initially contains a Pages table with 2 pages',
+ ({ fixture }) => {
+ const plan = initialPlan(fixture);
+ if (!plan) return fail('no genpage-plan.md');
+ const rows = pageRowsOf(plan);
+ return rows.length === 2 ? pass() : fail(`the first plan's ## Pages has ${rows.length} row(s), expected 2`);
+ }
+);
+
+// The Phase 5a page-file gate's first verdict, with the dispatch steps it must precede.
+function firstPageFilesGate(fixture) {
+ const calls = workflowCalls(fixture);
+ const at = calls.findIndex((c) => PAGE_FILES_GATE.test(c.command));
+ const dispatchAt = calls.findIndex((c) => WORKER_STAMP.test(c.command) || PAGE_BUILDER.test(c.command) || isGeneration(c.command) || isUpload(c.command));
+ return { calls, at, dispatchAt, result: at === -1 ? null : resultObject(calls[at]) };
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5a: Orchestrator reads the Pages table and detects duplicate filenames',
+ ({ fixture }) => {
+ const plan = initialPlan(fixture);
+ if (!plan) return fail('no genpage-plan.md');
+ const files = pageFilesOf(plan);
+ const { at, dispatchAt, result } = firstPageFilesGate(fixture);
+ if (at === -1) return fail('check-page-files.js was not run');
+ if (dispatchAt !== -1 && dispatchAt < at) return fail('page dispatch started before the page-file gate ran');
+ if (!result || !Array.isArray(result.files)) return fail('check-page-files.js result is missing or malformed');
+ if (sortedFiles(result.files).join('|') !== sortedFiles(files).join('|')) return fail(`the gate read ${listText(result.files)}, but the plan's Pages table lists ${listText(files)}`);
+ // Recompute with the plugin's own rule so the recorded verdict cannot be taken on trust.
+ const collisions = pageFileProblems(files, { workingDir: path.resolve(workingDirectoryOf(plan) || '.') }).filter((p) => p.code === 'collision');
+ if (!collisions.length) return fail(`the first plan's files ${listText(files)} do not collide`);
+ if (result.ok !== false || !(result.problems || []).some((p) => p.code === 'collision')) return fail('check-page-files.js did not report the collision');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 5a: check-page-files.js refuses the colliding plan and the orchestrator halts and re-plans through the planner (it never renames files itself), so genpage-plan.md carries unique, re-approved filenames (e.g., account-list.tsx, account-edit.tsx) before any builder is dispatched",
+ ({ fixture }) => {
+ const { calls, at, result } = firstPageFilesGate(fixture);
+ if (at === -1 || result?.ok !== false) return fail('check-page-files.js did not refuse the first plan');
+ const passAt = calls.findIndex((c, i) => i > at && PAGE_FILES_GATE.test(c.command) && resultObject(c)?.ok === true);
+ if (passAt === -1) return fail('no later check-page-files.js run passed a re-planned genpage-plan.md');
+ const between = calls.slice(at + 1, passAt);
+ // Never renamed in place: the orchestrator does not edit the plan, the old plan is quarantined by
+ // `prepare`, and the rewrite is provenance-verified against a re-approved body. Checked before the
+ // dispatch rule because an in-place rename edit names `.tsx` files and would read as generation.
+ if (between.some((c) => /^(?:Edit|Write)\b[^\n]*genpage-plan\.md/i.test(c.command))) return fail('the orchestrator edited genpage-plan.md itself');
+ const dispatched = between.find((c) => WORKER_STAMP.test(c.command) || PAGE_BUILDER.test(c.command) || isGeneration(c.command) || isUpload(c.command));
+ if (dispatched) return fail(`"${dispatched.command}" ran after the refusal, before a passing re-plan`);
+ const firstDispatch = calls.findIndex((c) => WORKER_STAMP.test(c.command) || PAGE_BUILDER.test(c.command));
+ if (firstDispatch !== -1 && firstDispatch < passAt) return fail('a builder target was stamped or dispatched before the re-planned files passed the gate');
+ const prepare = between.find((c) => PROVENANCE_PREPARE.test(c.command));
+ if (!prepare || !resultObject(prepare)?.quarantinedPath) return fail('the colliding plan was not quarantined before the planner rewrote it');
+ const verify = between.filter((c) => PROVENANCE_VERIFY.test(c.command)).at(-1);
+ if (resultObject(verify || {})?.ok !== true) return fail('the rewritten genpage-plan.md was not provenance-verified');
+ const lines = String(fixture.workflowLog || '').split(/\r?\n/);
+ // The refusal as logged under the gate command, e.g. `- Result: exit 3, {"ok":false,…"collision"…}`.
+ // Anchored after the first check-page-files.js line and never a heading, so a title that merely
+ // mentions the collision cannot stand in for it.
+ const gateLine = lines.findIndex((l) => PAGE_FILES_GATE.test(l));
+ const refusedAt = gateLine === -1 ? -1
+ : lines.findIndex((l, i) => i >= gateLine && !/^\s*#/.test(l) && /"ok"\s*:\s*false|\bcollision\b|\bHALTED\b|\brefus/i.test(l));
+ if (refusedAt === -1) return fail('workflow-log does not record the refusal');
+ const after = planModeEvents(fixture.workflowLog).filter((e) => e.at > refusedAt);
+ const planner = after.find((e) => e.kind === 'planner');
+ const approval = after.find((e) => e.kind === 'approved');
+ if (!planner || !approval || approval.at < planner.at) return fail('the renamed files were not re-planned by genpage-planner and re-approved');
+ const files = pageFilesOf(fixture.genpagePlan);
+ if (pageFileProblems(files, { workingDir: path.resolve(workingDirectoryOf(fixture.genpagePlan) || '.') }).length) return fail(`genpage-plan.md files ${listText(files)} are still unsafe`);
+ const approved = artifactOrNull(fixture, '.approved-genpage-plan.md');
+ if (approved === null) return fail('the re-approved plan body was not saved');
+ const want = planTargets(approved, { kind: 'create' });
+ const got = planTargets(fixture.genpagePlan, { kind: 'create' });
+ return sameTargets(want, got) ? pass() : fail(`genpage-plan.md files ${JSON.stringify(got?.targets)} are not the re-approved ${JSON.stringify(want?.targets)}`);
+ }
+);
+
+// `Task genpage-page-builder: Accounts, target file account-list.tsx` → account-list.tsx
+function builderDispatches(fixture) {
+ const calls = workflowCalls(fixture);
+ return calls.map((c, i) => ({ c, i })).filter(({ c }) => PAGE_BUILDER.test(c.command))
+ .map(({ c, i }) => ({ at: i, call: c, target: fileName((/target file\s+`?([^\s`,]+\.tsx)/i.exec(c.command) || [])[1] || '') }));
+}
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 5c: Two page-builders are invoked in parallel with distinct target filenames',
+ ({ fixture }) => {
+ const builders = builderDispatches(fixture);
+ if (builders.length !== 2) return fail(`${builders.length} page-builder dispatch(es) recorded, expected 2`);
+ const targets = builders.map((b) => b.target);
+ if (targets.some((t) => !t)) return fail('a page-builder dispatch names no target file');
+ if (targets[0].toLowerCase() === targets[1].toLowerCase()) return fail(`both page-builders target ${targets[0]}`);
+ if (!sameSet(targets, pageFilesOf(fixture.genpagePlan))) return fail(`builder targets ${listText(targets)} are not the plan's files`);
+ // Parallel = one message: the two dispatches are adjacent, with no result gate between them.
+ // That adjacency IS the observable SKILL.md 5c defines ("invoke them in a single message");
+ // the log is not required to also SAY "single message" or "in parallel".
+ if (builders[1].at !== builders[0].at + 1) return fail('the page-builders were not dispatched together');
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 5c: No builder overwrites another builder's output (both .tsx files exist after Phase 5)",
+ ({ fixture }) => {
+ const files = pageFilesOf(fixture.genpagePlan);
+ if (files.length < 2) return fail('the plan has fewer than two pages');
+ const pages = files.map((name) => (fixture.files || []).find((f) => f.name === name));
+ const missing = files.filter((_, i) => !pages[i]);
+ if (missing.length) return fail(`${missing.join(', ')} does not exist after Phase 5`);
+ if (new Set(pages.map((p) => p.content)).size !== pages.length) return fail('two page files hold identical content — one builder\'s output replaced the other');
+ // Each target was stamped empty before its builder ran and passed the completeness gate after.
+ const calls = workflowCalls(fixture);
+ for (const name of files) {
+ const stamp = calls.find((c) => WORKER_STAMP.test(c.command) && fileName(commandInfo(c).flags.file) === name);
+ if (!stamp || resultObject(stamp)?.existed !== false) return fail(`${name} was not stamped as a fresh target`);
+ const gate = calls.find((c) => /\bgenpage-worker-output\.js\b/.test(c.command) && !WORKER_STAMP.test(c.command) && fileName(commandInfo(c).flags.file) === name);
+ if (resultObject(gate || {})?.ok !== true) return fail(`${name} did not pass the worker-output gate after its builder`);
+ }
+ return pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 6: Both pages are deployed with their distinct filenames',
+ ({ fixture }) => {
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (rows.length !== 2) return fail(`## Pages has ${rows.length} row(s), expected 2`);
+ if (rows[0].file.toLowerCase() === rows[1].file.toLowerCase()) return fail(`both pages share ${rows[0].file}`);
+ return resultOf(createUploadProblems(fixture, rows));
+ }
+);
+
+// --- Eval 16 -----------------------------------------------------------------------------------
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): genpage-plan.md is written and conforms to references/plan-schema.md',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const errors = validateGenpagePlanSchema(fixture.genpagePlan);
+ if (errors.length) return fail(errors[0].message);
+ // "Written" by the planner in this run: the provenance verify of the file passed.
+ const verify = commandCalls(fixture, PROVENANCE_VERIFY).at(-1);
+ if (!verify) return fail('genpage-plan.md was not provenance-verified after it was written');
+ const result = resultObject(verify.call);
+ if (result?.ok !== true) return fail('provenance verification of genpage-plan.md did not pass');
+ const targets = planTargets(fixture.genpagePlan, { kind: 'create' });
+ return Array.isArray(result.targets) && targets && sortedFiles(result.targets).join('|') === targets.targets.join('|')
+ ? pass() : fail(`the verified targets ${listText(result.targets || [])} are not this plan's files`);
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): genpage-plan.md contains ALL required sections with exact headings: # Genpage Plan, ## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const headings = ['# Genpage Plan', '## User Requirements', '## Working Directory', '## Plugin Root', '## Environment', '## Pages',
+ '## Entity Creation Required', '## Existing Entities', '## Design Preferences', '## Relevant Samples', '## Per-Page Specifications'];
+ const lines = fixture.genpagePlan.split(/\r?\n/).map((l) => l.trimEnd());
+ const missing = headings.filter((h) => !lines.includes(h));
+ return missing.length ? fail(`missing exact heading "${missing[0]}"`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): ## Pages table has at least one row with columns Page, File, Purpose, Entities',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (!rows.length) return fail('## Pages has no table with Page, File, Purpose and Entities columns, or no rows');
+ const empty = rows.find((r) => ['page', 'file', 'purpose', 'entities'].some((c) => !String(r[c] || '').trim()));
+ return empty ? fail(`## Pages row "${empty.page || '?'}" has an empty cell`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): ## Per-Page Specifications has one ### <Page Name> subsection for each row in ## Pages',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const rows = pageRowsOf(fixture.genpagePlan);
+ if (!rows.length) return fail('## Pages has no rows');
+ const blocks = parsePerPageBlocks(planSection(fixture.genpagePlan, 'Per-Page Specifications') || '');
+ const missing = rows.find((r) => !blocks.has(r.page));
+ if (missing) return fail(`## Per-Page Specifications has no "### ${missing.page}" subsection`);
+ const extra = [...blocks.keys()].find((name) => !rows.some((r) => r.page === name));
+ return extra ? fail(`"### ${extra}" has no ## Pages row`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): File names in ## Pages are unique',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const files = pageFilesOf(fixture.genpagePlan);
+ if (!files.length) return fail('## Pages has no rows');
+ // The plugin's own rule: names that collide on a case-insensitive filesystem are duplicates too.
+ const collision = pageFileProblems(files, { workingDir: path.resolve(workingDirectoryOf(fixture.genpagePlan) || '.') }).find((p) => p.code === 'collision');
+ return collision ? fail(`## Pages file names collide: ${collision.message}`) : pass();
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): Because the account entity exists, ## Entity Creation Required contains the literal string 'No entity creation required — all entities already exist.'",
+ ({ fixture }) => {
+ const problems = existingEntityProblems(fixture, ['account']);
+ if (problems.length) return fail(problems[0]);
+ const section = planSection(fixture.genpagePlan, 'Entity Creation Required') || '';
+ return section.includes('No entity creation required — all entities already exist.') ? pass()
+ : fail('## Entity Creation Required does not contain the exact no-entity sentence');
+ }
+);
+
+PHASE_EXPECTATIONS.set(
+ 'Phase 1 (Planner): ## Existing Entities contains the entity logical name used for RuntimeTypes generation (account)',
+ ({ fixture }) => {
+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');
+ const existing = existingEntities(fixture.genpagePlan);
+ if (!existing.includes('account')) return fail(`## Existing Entities lists ${listText(existing)}, not account`);
+ const calls = generateTypesCalls(fixture);
+ if (!calls.length) return fail('pac model genpage generate-types was not run');
+ const unlisted = calls.flatMap((c) => c.sources).filter((s) => !existing.includes(s));
+ if (unlisted.length) return fail(`generate-types used ${unlisted.join(', ')}, which ## Existing Entities does not list`);
+ return calls.some((c) => c.sources.includes('account')) ? pass() : fail('generate-types was not run for account');
+ }
+);
+
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.js
index 67618b233..3177430d3 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-2.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js
@@ -20,7 +20,7 @@ const fs = require('node:fs');
// re-implemented: it is a pure lexer over TSX text, not part of the thing this harness judges, and
// two divergent copies of a tokenizer is exactly how a false-green assertion creeps back in. Evals
// never ship, so reaching into the plugin directory here is in-repo only.
-const { blankLiterals, findElisionMarker } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, findElisionMarker } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
const { pageStructureProblems } = require('../../../../plugins/model-apps/scripts/lib/page-structure.js');
const { navigationProblems } = require('./navigation-contract.js');
const { workerProblems } = require('./worker-contract.js');
@@ -608,6 +608,169 @@ PHASE5_EXPECTATIONS.set(
() => 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
+// view keeps only string, template and JSX text at its original offsets: the template-preserving
+// lexer view leaves `${…}` bodies as code, and comment ranges are dropped, so a comment explaining
+// the rule never trips it. Raw shapes this catches (references/localization.md forbids all of them):
+// <Text>${total}</Text> `$` in JSX text right before a code `{`
+// `$${amount.toFixed(2)}` `$` in template text before the `${` delimiter
+// '$' + total / 'Total: $' + total `$` ending a string that is concatenated onto an amount
+// amount + ' $' `$` opening a string concatenated after an amount
+// 'Total: €' / '$100' a symbol in a string
+// 'MM/dd/yyyy', 'yyyy-MM-dd' a date pattern instead of usersettings.dateformatstring
+// { style: 'currency', currency: 'USD' } a currency code instead of usersettings.currencysymbol
+// d.toLocaleDateString('en-US') a fixed locale's date format
+// Not currency: a bare `${x}` interpolation (its `$` is the template delimiter), an OData query
+// option such as '?$select=' + cols (`$` is followed by a name), and a `currency:` key outside a
+// `style: 'currency'` number format (e.g. a translation dictionary `{ currency: 'Devise' }`).
+const DATE_PART = '(?:d{1,2}|D{1,2}|M{1,4}|y{2,4}|Y{2,4})';
+const DATE_PATTERN = new RegExp(`\\b${DATE_PART}([/.\\-])${DATE_PART}\\1${DATE_PART}\\b`);
+
+// The object literal around `at` in the code view, by brace depth: from the nearest unmatched `{`
+// before it to its matching `}`. Strings are already blanked in `keep`, so braces inside them
+// cannot unbalance the scan. Returns [start, end) offsets, or null when `at` is not inside one.
+function enclosingObject(keep, at) {
+ let depth = 0;
+ let open = -1;
+ for (let i = at - 1; i >= 0; i -= 1) {
+ if (keep[i] === '}') depth += 1;
+ else if (keep[i] === '{') {
+ if (depth === 0) { open = i; break; }
+ depth -= 1;
+ }
+ }
+ if (open < 0) return null;
+ depth = 0;
+ for (let i = open; i < keep.length; i += 1) {
+ if (keep[i] === '{') depth += 1;
+ else if (keep[i] === '}' && --depth === 0) return [open, i + 1];
+ }
+ return [open, keep.length];
+}
+
+/**
+ * Object-literal properties named `name`, written bare (`currency:`) or quoted (`"currency":`),
+ * found in CODE only and only in key position (after `{` or `,`), so a ternary such as
+ * `x ? 'currency' : 'decimal'` is not mistaken for a key. Each value is classified:
+ * kind 'fixed' — a quoted string, or a template literal with no `${…}` (text = its content)
+ * kind 'runtime' — anything else: an identifier, a call, an interpolated template
+ * @returns {Array<{at: number, kind: 'fixed'|'runtime', text: string|null}>}
+ */
+function objectProperties(content, keep, isLiteral, name) {
+ const out = [];
+ const re = new RegExp(`(?:\\b${name}\\b|(['"])${name}\\1)\\s*:`, 'g');
+ for (const m of content.matchAll(re)) {
+ const at = m.index;
+ // Bare key: the identifier itself must be code. Quoted key: its opening quote must be a
+ // delimiter (code), not a quote character inside some other string.
+ if (m[1] ? isLiteral(at) : keep[at] !== content[at]) continue;
+ const colon = at + m[0].length - 1;
+ if (keep[colon] !== ':') continue;
+ let p = at - 1;
+ while (p >= 0 && /\s/.test(content[p])) p -= 1;
+ if (p >= 0 && content[p] !== '{' && content[p] !== ',') continue;
+ let v = colon + 1;
+ while (v < content.length && /\s/.test(content[v])) v += 1;
+ const q = content[v];
+ if (q === '\'' || q === '"' || q === '`') {
+ // The closing delimiter is the next character of the same kind that the code view kept.
+ // For a template, any kept non-blank character before it is a `${…}` body: a runtime value.
+ let k = v + 1;
+ let interpolated = false;
+ while (k < content.length && !(content[k] === q && keep[k] === q)) {
+ if (q === '`' && keep[k] === content[k] && !/\s/.test(content[k])) interpolated = true;
+ k += 1;
+ }
+ out.push(interpolated ? { at, kind: 'runtime', text: null } : { at, kind: 'fixed', text: content.slice(v + 1, k) });
+ } else {
+ out.push({ at, kind: 'runtime', text: null });
+ }
+ }
+ return out;
+}
+
+function hardcodedFormatProblem(content) {
+ const keep = blankNonCodePreservingTemplateExpressions(content);
+ const comment = new Uint8Array(content.length);
+ for (const { start, end } of commentRanges(content)) comment.fill(1, start, end);
+ // A literal character: blanked in the code view and not part of a comment. The view blanks string,
+ // template, JSX-text AND regex bodies alike but keeps their delimiters, e.g.
+ // raw.replace(/[$€]/g, '') → raw.replace(/ /g, '')
+ // so which kind of literal a character belongs to is the delimiter that OPENED its run: tracked in
+ // one forward pass as the last non-blank code character. Regex bodies are input-matching syntax,
+ // not displayed text — `raw.replace(/[$€£]/g, '')` strips symbols from input, it shows none.
+ const isLiteral = (i) => keep[i] !== content[i] && !comment[i];
+ const inRegex = new Uint8Array(content.length);
+ let opener = '';
+ for (let i = 0; i < content.length; i += 1) {
+ if (isLiteral(i)) { if (opener === '/') inRegex[i] = 1; }
+ else if (!comment[i] && !/\s/.test(content[i])) opener = content[i];
+ }
+ const isText = (i) => isLiteral(i) && !inRegex[i];
+ const text = content.split('').map((ch, i) => (isText(i) ? ch : ' ')).join('');
+ // The code character next to a string literal's delimiter, skipping whitespace, in direction dir.
+ const codeNeighbour = (from, dir) => {
+ let k = from;
+ while (k >= 0 && k < content.length && /\s/.test(content[k])) k += dir;
+ return k >= 0 && k < content.length && !isText(k) ? content[k] : '';
+ };
+ for (const m of text.matchAll(/[$\u20ac\u00a3\u00a5\u20b9]/g)) {
+ const i = m.index;
+ if (m[0] !== '$') return `hardcoded currency symbol "${m[0]}"`;
+ let j = i + 1;
+ while (j < content.length && /[ \t]/.test(content[j])) j += 1;
+ const amount = /\d/.test(content[j] || '');
+ const templateCurrency = content[i + 1] === '$' && content[i + 2] === '{';
+ const jsxCurrency = content[j] === '{' && !isText(j);
+ // String-boundary currency: the `$` is the last text character before a closing quote that is
+ // followed by `+`, or the first text character after an opening quote that is preceded by `+`.
+ // Whitespace is skipped unconditionally: the text view blanks string contents to spaces, so a
+ // space inside the string is indistinguishable from code here. Quote DELIMITERS stay visible in
+ // the code view (a quote inside text is blanked), which is what `!isText` tests below.
+ let end = i + 1;
+ while (end < content.length && /[ \t]/.test(content[end])) end += 1;
+ let start = i - 1;
+ while (start >= 0 && /[ \t]/.test(content[start])) start -= 1;
+ const prefixConcat = /['"`]/.test(content[end] || '') && !isText(end) && codeNeighbour(end + 1, 1) === '+';
+ const suffixConcat = start >= 0 && /['"`]/.test(content[start]) && !isText(start) && codeNeighbour(start - 1, -1) === '+';
+ if (amount || templateCurrency || jsxCurrency || prefixConcat || suffixConcat) return 'hardcoded "$" currency symbol';
+ }
+ const pattern = DATE_PATTERN.exec(text);
+ if (pattern && /[dD]/.test(pattern[0]) && /M/.test(pattern[0]) && /[yY]/.test(pattern[0])) return `hardcoded date format "${pattern[0]}"`;
+ // Intl formats a currency only when the SAME options object sets style: 'currency', and the code is
+ // hardcoded only when the `currency` VALUE is a fixed literal. Read real property keys — bare or
+ // quoted ({ "style": "currency", "currency": "USD" } is the same object) — and classify each value:
+ // 'USD' / "USD" / `USD` fixed (a template with no ${…} is still a constant)
+ // `${currencyCode}` / code / x runtime (comes from usersettings or other input — allowed)
+ // A `currency:` key outside such an object (a translation dictionary { currency: 'Devise' }) is
+ // an ordinary label, not a number format.
+ const currencyOptions = objectProperties(content, keep, isLiteral, 'currency');
+ if (currencyOptions.some((c) => c.kind === 'fixed')) {
+ const styles = objectProperties(content, keep, isLiteral, 'style').filter((s) => s.kind === 'fixed' && s.text === 'currency');
+ for (const c of currencyOptions.filter((p) => p.kind === 'fixed')) {
+ const span = enclosingObject(keep, c.at);
+ if (span && styles.some((s) => s.at > span[0] && s.at < span[1] && String(enclosingObject(keep, s.at)) === String(span))) {
+ return 'hardcoded currency code in a number format';
+ }
+ }
+ }
+ for (const call of keep.matchAll(/\b(?:toLocaleDateString|toLocaleString|toLocaleTimeString|DateTimeFormat)\s*\(\s*/g)) {
+ if (/^['"`][a-z]{2,3}(?:-[A-Za-z]{2,4})?['"`]/.test(content.slice(call.index + call[0].length))) return 'hardcoded locale for date formatting';
+ }
+ return null;
+}
+
+PHASE5_EXPECTATIONS.set(
+ 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats',
+ ({ files }) => {
+ for (const file of files) {
+ const problem = hardcodedFormatProblem(file.content);
+ if (problem) return fail(`${file.name}: ${problem}`);
+ }
+ return pass();
+ }
+);
+
PHASE5_EXPECTATIONS.set(
'Phase 5 (Page Builder): Generated .tsx uses dataApi.getChoices() or reads FormattedValue annotations for choice display names',
({ files }) => {
diff --git a/evals/model-apps/genpage/lib/expectation-evidence.js b/evals/model-apps/genpage/lib/expectation-evidence.js
new file mode 100644
index 000000000..52e653dae
--- /dev/null
+++ b/evals/model-apps/genpage/lib/expectation-evidence.js
@@ -0,0 +1,268 @@
+'use strict';
+
+// Structured readers for the evidence a /genpage run leaves behind, used by the per-eval Phase
+// expectations about discovery, provisioning, schema generation and deployment.
+//
+// Every reader turns ONE artifact into plain data so a check compares values instead of re-grepping
+// prose: commands come from workflowCalls (a contract-2 fixture's ordered tool-results.json, or the
+// command lines of a historical workflow-log.md), entity definitions from the plan's
+// `## Entity Creation Required`, transactions from genpage-entity-creation-log.md, and choice enums
+// from the RuntimeTypes.ts that `pac model genpage generate-types` wrote from the LIVE schema.
+//
+// Nothing here executes evidence: command text is tokenized by commandInfo, never evaluated.
+
+const { workflowCalls, isUpload } = require('./workflow-evidence.js');
+const { commandInfo, fileName } = require('./evidence-utils.js');
+const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
+
+const PAC = String.raw`\bpac(?:\.exe|\.cmd)?\s+model\s+`;
+const LIST_TABLES = new RegExp(`${PAC}list-tables\\b`);
+const LIST_LANGUAGES = new RegExp(`${PAC}list-languages\\b`);
+const GENERATE_TYPES = new RegExp(`${PAC}genpage\\s+generate-types\\b`);
+const GENPAGE_LIST = new RegExp(`${PAC}genpage\\s+list\\b`);
+const PROVISION = /\bprovision-entities\.js\b/;
+// The pre-SDK entity-builder created each table, column, relationship and row with its own script.
+const LEGACY_PROVISION = /\b(?:create-table|add-column|create-relationship|create-record)\.js\b/;
+
+// A list-tables result that says the searched table is absent. The captures phrase it as
+// `pac model list-tables --search 'cr_candidate'` — exact logical-name match: NOT FOUND
+// No tables found matching the specified criteria. / Result: cr_ticket does NOT exist
+const NOT_FOUND = /\bNOT\s+FOUND\b|\bdoes\s+not\s+exist\b|\bdo\s+not\s+exist\b|\bNo\s+tables?\s+found\b/i;
+
+// `--data-sources 'incident,contact'` → ['incident', 'contact']. commandInfo already removed the
+// one pair of quotes that wrapped the token; stray backticks from a Markdown code span go here.
+function csvList(value) {
+ if (typeof value !== 'string') return [];
+ return value.split(',').map((item) => item.trim().replace(/^[`'"]+|[`'"]+$/g, '').toLowerCase()).filter(Boolean);
+}
+
+const sameSet = (a, b) => a.length === b.length && a.every((item) => b.includes(item));
+const containsAll = (have, wanted) => wanted.every((item) => have.includes(item));
+
+// A logical name's suffix: `cr_candidate` → `candidate`. The plan stores suffixes only and the
+// prefix comes from the SELECTED solution's publisher, so a run that picked a `cnt` publisher
+// correctly creates `cnt_widget` for a prompt that said `cr_widget`.
+const suffixOf = (name) => String(name).toLowerCase().replace(/^[a-z0-9]+_/, '');
+
+// Commands matching `pattern`, each with its parsed flags and the text recorded with it (the
+// result lines that follow a historical log command, or a contract-2 event's result).
+function commandCalls(fixture, pattern) {
+ return workflowCalls(fixture).filter((call) => pattern.test(call.command)).map((call) => {
+ // A historical log wraps the command in a Markdown code span and keeps going after it:
+ // - Command: `pac model genpage generate-types --data-sources "task" --output-file "D:/x/RuntimeTypes.ts"`
+ // `node …/provision-entities.js --env https://… --input @…/provision-input.json --apply --sample-data`
+ // The closing backtick would otherwise glue onto the last token (`--sample-data\`` is then no
+ // flag at all), so drop the span delimiters before tokenizing. Recorded argv is used untouched.
+ const info = commandInfo(call.argv ? call : { ...call, command: String(call.command).replace(/`/g, ' ') });
+ const result = typeof call.result === 'string' ? call.result : call.result ? JSON.stringify(call.result) : '';
+ return { call, flags: info.flags, text: [call.text || call.command, result].join('\n') };
+ });
+}
+
+function listTablesSearches(fixture) {
+ return commandCalls(fixture, LIST_TABLES).filter((c) => typeof c.flags.search === 'string')
+ .map((c) => ({ ...c, terms: csvList(c.flags.search) }));
+}
+
+function generateTypesCalls(fixture) {
+ return commandCalls(fixture, GENERATE_TYPES).map((c) => ({ ...c, sources: csvList(c.flags['data-sources']) }));
+}
+
+// Both transports — raw `pac model genpage upload` and scripts/genpage-upload.js — take the same
+// `--code-file` / `--data-sources` / `--page-id` flags, so one reader serves both (isUpload).
+function uploadCalls(fixture) {
+ return commandCalls(fixture, /./).filter((c) => isUpload(c.call.command))
+ .map((c) => ({ ...c, file: fileName(c.flags['code-file']), sources: csvList(c.flags['data-sources']), update: Boolean(c.flags['page-id']) }));
+}
+
+function provisionCalls(fixture) {
+ return commandCalls(fixture, PROVISION);
+}
+
+function legacyProvisionCalls(fixture) {
+ return commandCalls(fixture, LEGACY_PROVISION);
+}
+
+function envField(text, label) {
+ const section = planSection(text, 'Environment') || '';
+ const match = new RegExp(`^\\s*[-*]?\\s*${label}:\\s*(\\S+)`, 'mi').exec(section);
+ return match ? match[1].trim() : null;
+}
+
+const planPrefix = (plan) => envField(plan, 'Publisher Prefix')?.toLowerCase() || null;
+const planSolution = (plan) => envField(plan, 'Solution');
+
+// Rows of a markdown table, minus the `| none | none |` placeholder rows plan-schema.md allows for
+// an empty Choice Columns or Relationships table.
+function tableRows(text, columns) {
+ return parseMarkdownRows(text, columns).filter((row) => !Object.values(row).every((cell) => /^(none|)$/i.test(cell)));
+}
+
+// `Low (100000000), Medium (100000001)` → [{ label: 'Low', value: 100000000 }, …]
+function parseOptions(cell) {
+ return [...String(cell || '').matchAll(/([^,()]+?)\s*\((\d+)\)/g)].map((m) => ({ label: m[1].trim(), value: Number(m[2]) }));
+}
+
+// The `### <suffix>` blocks of `## Entity Creation Required` (plan-schema.md), e.g.
+// ### candidate
+// - Columns:
+// | Suffix | Type | Required | Notes |
+// - Choice Columns:
+// | Column Suffix | Options |
+// - Relationships:
+// | Type | Related Table | Lookup Suffix | Cascade |
+// A Relationships row lives in the block of the REFERENCING table and names the referenced one.
+function planEntityBlocks(plan) {
+ const section = planSection(plan, 'Entity Creation Required');
+ if (!section || /No entity creation required/i.test(section)) return [];
+ const blocks = [];
+ let current = null;
+ for (const line of section.split(/\r?\n/)) {
+ const heading = /^###\s+(.+?)\s*$/.exec(line);
+ if (heading) {
+ current = { suffix: heading[1].trim().toLowerCase(), lines: [] };
+ blocks.push(current);
+ } else if (current) {
+ current.lines.push(line);
+ }
+ }
+ return blocks.map(({ suffix, lines }) => {
+ const text = lines.join('\n');
+ return {
+ suffix,
+ columns: tableRows(text, ['Suffix', 'Type']).map((row) => ({ suffix: row.suffix.toLowerCase(), type: row.type })),
+ choices: tableRows(text, ['Column Suffix', 'Options']).map((row) => ({ suffix: row['column suffix'].toLowerCase(), options: parseOptions(row.options) })),
+ relationships: tableRows(text, ['Type', 'Related Table', 'Lookup Suffix']).map((row) => ({
+ type: row.type, related: suffixOf(row['related table']), lookup: row['lookup suffix'].toLowerCase(),
+ })),
+ };
+ });
+}
+
+// `## Existing Entities` holds a comma/line separated list, `None.` or a sentence about mock data.
+function existingEntities(plan) {
+ const section = planSection(plan, 'Existing Entities') || '';
+ return (section.match(/\b[a-z][a-z0-9_]*\b/g) || []).filter((word) => !/^(none|mock|data|page)$/.test(word));
+}
+
+// genpage-entity-creation-log.md as written by agents/genpage-entity-builder.md Step 5:
+// ## Environment - Solution: Crdec34 / - Publisher Prefix: cr
+// ## Created Tables ### Ticket / - Resolved Full Name: cr_ticket / - Metadata ID: n/a
+// ## Created Columns | Table | Display Name | Schema Name | Resolved Full Name | Metadata ID |
+// ## Created Relationships | Type | From | To | Lookup Schema Name | Resolved Full Name |
+// Table order is kept: it is the order the transactions were recorded in.
+function entityLog(text) {
+ if (!text) return null;
+ const tables = [];
+ let current = null;
+ for (const line of (planSection(text, 'Created Tables') || '').split(/\r?\n/)) {
+ const heading = /^###\s+(.+?)\s*$/.exec(line);
+ if (heading) {
+ current = { title: heading[1], resolved: null, metadataId: null };
+ tables.push(current);
+ continue;
+ }
+ const field = /^\s*[-*]\s*(Resolved Full Name|Metadata ID):\s*(.*?)\s*$/i.exec(line);
+ if (current && field) current[/^Resolved/i.test(field[1]) ? 'resolved' : 'metadataId'] = field[2].toLowerCase() || null;
+ }
+ return {
+ solution: envField(text, 'Solution'),
+ prefix: envField(text, 'Publisher Prefix')?.toLowerCase() || null,
+ tables,
+ columns: parseMarkdownRows(planSection(text, 'Created Columns') || '', ['Table', 'Resolved Full Name'])
+ .map((row) => ({ table: row.table.toLowerCase(), resolved: row['resolved full name'].toLowerCase(), metadataId: row['metadata id'] ?? null })),
+ relationships: parseMarkdownRows(planSection(text, 'Created Relationships') || '', ['From', 'To'])
+ .map((row) => ({ from: row.from.toLowerCase(), to: row.to.toLowerCase(), resolved: (row['resolved full name'] || '').toLowerCase() })),
+ };
+}
+
+// The tables a run actually created: the transaction log's resolved names (Dataverse may normalize
+// them), else the plan's `<prefix>_<suffix>` when no log was captured.
+function createdTableNames(fixture) {
+ const log = entityLog(fixture.entityCreationLog);
+ const resolved = (log?.tables || []).map((t) => t.resolved).filter(Boolean);
+ if (resolved.length) return resolved;
+ const prefix = planPrefix(fixture.genpagePlan);
+ return prefix ? planEntityBlocks(fixture.genpagePlan).map((b) => `${prefix}_${b.suffix}`) : [];
+}
+
+// RuntimeTypes.ts as `pac model genpage generate-types` writes it:
+// export interface EnumRegistrations extends BaseEnumRegistrations {
+// "cr_ticket-cr_priority": cr_ticket_cr_priority,
+// }
+// const enum cr_ticket_cr_priority {
+// "Low" = 100000000,
+// }
+// Members are quoted labels (they may contain spaces); a bare identifier is accepted too.
+function runtimeEnums(source) {
+ const text = String(source || '');
+ const registrations = new Map();
+ const block = /interface\s+EnumRegistrations\b[^{]*\{([^}]*)\}/.exec(text);
+ for (const m of (block?.[1] || '').matchAll(/"([^"]+)"\s*:\s*([A-Za-z_$][\w$]*)/g)) registrations.set(m[1].toLowerCase(), m[2]);
+ const enums = new Map();
+ for (const m of text.matchAll(/\benum\s+([A-Za-z_$][\w$]*)\s*\{([^}]*)\}/g)) {
+ enums.set(m[1], [...m[2].matchAll(/(?:"([^"]+)"|([A-Za-z_$][\w$]*))\s*=\s*(-?\d+)/g)]
+ .map((x) => ({ label: x[1] ?? x[2], value: Number(x[3]) })));
+ }
+ return { registrations, enums };
+}
+
+// The enum registered for `<table>-<column>`, matched on suffixes (see suffixOf).
+function choiceEnum(source, tableSuffix, columnSuffix) {
+ const { registrations, enums } = runtimeEnums(source);
+ for (const [key, name] of registrations) {
+ const [table, column] = key.split('-');
+ if (suffixOf(table) === tableSuffix && suffixOf(column) === columnSuffix) return { key, name, members: enums.get(name) || null };
+ }
+ return null;
+}
+
+// The rows of a PAC listing — apps from `pac model list`, pages from `pac model genpage list` — as
+// { id, name }. Three recorded shapes:
+// App ID Display Name Unique Name (raw PAC table)
+// 11111111-2222-3333-4444-555555555555 Sales Hub SalesHub
+// - Sales Hub — 11111111-2222-3333-4444-555555555555 (SalesHub) (log bullet)
+// { "apps": [ { "appId": "…", "displayName": "…" } ] } (structured result)
+const GUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
+function listingRows(call) {
+ const rows = [];
+ const result = call.result;
+ if (result && typeof result === 'object' && !call.historical) {
+ for (const value of Object.values(result)) {
+ if (!Array.isArray(value)) continue;
+ for (const item of value) {
+ const id = item && Object.values(item).find((v) => typeof v === 'string' && GUID_RE.test(v));
+ if (id) rows.push({ id: GUID_RE.exec(id)[0].toLowerCase(), name: String(item.displayName || item.name || '').trim() });
+ }
+ }
+ return rows;
+ }
+ const text = typeof result === 'string' && !call.historical ? result : String(call.text || '').split(/\r?\n/).slice(1).join('\n');
+ for (const line of text.split(/\r?\n/)) {
+ const m = GUID_RE.exec(line);
+ if (!m) continue;
+ const before = line.slice(0, m.index).replace(/^[\s*-]+/, '').replace(/[\s`(—–-]+$/, '').trim();
+ const after = line.slice(m.index + m[0].length).split(/\s{2,}/).map((s) => s.trim()).filter(Boolean)[0] || '';
+ rows.push({ id: m[0].toLowerCase(), name: before || after.replace(/[`)]+$/, '') });
+ }
+ return rows;
+}
+
+// The run in order, one entry per step, for requirements that span commands AND the conversation
+// (questions, plan presentations). A contract-2 fixture that records its AskUserQuestion turns as
+// tool-result events is read from those events; otherwise the workflow-log's lines are the record,
+// since contract-2 events of the other fixtures hold commands only.
+function conversationSteps(fixture) {
+ const events = Array.isArray(fixture.events) ? fixture.events : null;
+ if (events && events.some((e) => /^AskUserQuestion\b/.test(e.command))) {
+ return events.map((e) => `${e.command}\n${typeof e.result === 'string' ? e.result : JSON.stringify(e.result ?? '')}`);
+ }
+ return String(fixture.workflowLog || '').split(/\r?\n/);
+}
+
+module.exports = {
+ LIST_LANGUAGES, GENPAGE_LIST, NOT_FOUND, GUID_RE,
+ csvList, sameSet, containsAll, suffixOf, commandCalls, listTablesSearches, generateTypesCalls, uploadCalls,
+ provisionCalls, legacyProvisionCalls, planPrefix, planSolution, planEntityBlocks, existingEntities, entityLog,
+ createdTableNames, runtimeEnums, choiceEnum, parseOptions, listingRows, conversationSteps,
+};
diff --git a/evals/model-apps/genpage/lib/fixture-loader.js b/evals/model-apps/genpage/lib/fixture-loader.js
index c32c2924c..0038dc4e9 100644
--- a/evals/model-apps/genpage/lib/fixture-loader.js
+++ b/evals/model-apps/genpage/lib/fixture-loader.js
@@ -22,6 +22,7 @@ const path = require('node:path');
// workflowLog: string | null ← workflow-log.md content (Layer 1)
// genpagePlan: string | null ← genpage-plan.md content (Layer 1)
// genpageEditPlan: string | null ← genpage-edit-plan.md content (Layer 1 edit flow)
+// runtimeTypes: string | null ← RuntimeTypes.ts content when captured (Layer 1)
// entityCreationLog: string | null ← current log or legacy alias (Layer 1)
// contractVersion, manifest, events, artifacts ← versioned synthetic evidence
@@ -108,6 +109,10 @@ function loadFixtures(fixturesDir) {
workflowLog: readOptional(dir, 'workflow-log.md'),
genpagePlan: readOptional(dir, 'genpage-plan.md'),
genpageEditPlan: readOptional(dir, 'genpage-edit-plan.md'),
+ // The schema `pac model genpage generate-types` wrote from the live environment. It is not a
+ // generated page (listTsxFiles skips it), but it is the only captured record of the choice
+ // values Dataverse actually holds after provisioning.
+ runtimeTypes: readOptional(dir, 'RuntimeTypes.ts'),
// Only absence permits the legacy alias. An empty current log must not borrow old transactions.
entityCreationLog: readOptional(dir, ENTITY_CREATION_LOG) ?? readOptional(dir, LEGACY_ENTITY_CREATION_LOG),
...fixtureEvidence(dir, entry.name, historicalContracts),
diff --git a/evals/model-apps/genpage/lib/navigation-contract.js b/evals/model-apps/genpage/lib/navigation-contract.js
index 5d7bf6e81..8e28cb5ed 100644
--- a/evals/model-apps/genpage/lib/navigation-contract.js
+++ b/evals/model-apps/genpage/lib/navigation-contract.js
@@ -15,16 +15,20 @@ function historicalPageMap(log) {
return map;
}
+// This one capture predates `pageType:"generative"` and double-quoted PAGEREFs. The compatibility
+// view admits those historical spellings ONLY; it still checks every actual target against sibling
+// files. It is never used to claim current-contract compliance.
+function navTargets(content, { legacy = false } = {}) {
+ const code = legacy ? content.replace(/\bpageType\s*:\s*(["'])custom\1/g, 'pageType: "generative"') : content;
+ return extractNavTargets(code);
+}
+
function sourceProblems(files, { phase = 'authored', pageMap = {}, legacy = false } = {}) {
const keys = new Set(files.map((file) => file.name.replace(/\.tsx$/i, '')));
const ids = new Set(Object.values(pageMap).filter(isGuid).map((id) => id.toLowerCase()));
const problems = [];
for (const file of files) {
- // This one capture predates `pageType:"generative"` and double-quoted PAGEREFs. The
- // compatibility view admits those historical spellings ONLY; it still checks every actual
- // target against sibling files. It is never used to claim current-contract compliance.
- const code = legacy ? file.content.replace(/\bpageType\s*:\s*(["'])custom\1/g, 'pageType: "generative"') : file.content;
- for (const target of extractNavTargets(code)) {
+ for (const target of navTargets(file.content, { legacy })) {
if (target.kind === 'dynamic') problems.push(`${file.name}: effective navigation target is dynamic or overridden`);
else if (target.kind === 'pageref' || (legacy && target.kind === 'pageref-malformed')) {
if (phase === 'resolved') problems.push(`${file.name}: PAGEREF_${target.key} remains after resolution`);
@@ -106,4 +110,4 @@ function navigationProblems(fixture) {
return problems;
}
-module.exports = { navigationProblems, sourceProblems };
+module.exports = { navigationProblems, sourceProblems, navTargets };
diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
index bbcf987a7..afe5c120f 100644
--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
@@ -990,3 +990,42 @@ test('validateGenpagePlanSchema: page files cannot collide by normalized case-in
`expected duplicate-page-file, got ${JSON.stringify(errors)}`
);
});
+
+// ---------- solutions query: the planner's documented RELATIVE path form ----------
+
+const SOLUTIONS_QUERY = [...WORKFLOW_ASSERTIONS.keys()].find((t) => t.startsWith('Phase 1 (Planner): When the solution question runs, the planner queries /solutions'));
+
+test('solutions query: the documented relative `solutions?$select=` command passes on its own', () => {
+ // genpage-planner.md documents `dataverse-request.js <env> GET 'solutions?$select=...'` (no
+ // leading slash). The check once required a literal `/solutions`, so a log that copied the
+ // documented command verbatim failed.
+ const log = [
+ '- Solution selection question asked',
+ "- `node 'D:/repo/plugins/model-apps/scripts/dataverse-request.js' 'https://contoso.crm.dynamics.com' GET 'solutions?$select=uniquename,friendlyname&$top=10'`",
+ ].join('\n');
+ assert.equal(WORKFLOW_ASSERTIONS.get(SOLUTIONS_QUERY)({ fixture: fix({ workflowLog: log }), eval: evalStub(8) }).status, 'pass');
+});
+
+test('solutions query: no query at all still fails, and a lookalike entity set does not satisfy it', () => {
+ const asked = '- Solution selection question asked\n';
+ const check = WORKFLOW_ASSERTIONS.get(SOLUTIONS_QUERY);
+ assert.equal(check({ fixture: fix({ workflowLog: asked }), eval: evalStub(8) }).status, 'fail');
+ const lookalike = `${asked}- node dataverse-request.js https://contoso.crm.dynamics.com GET 'solutionsfoo?$top=1'\n`;
+ assert.equal(check({ fixture: fix({ workflowLog: lookalike }), eval: evalStub(8) }).status, 'fail');
+ assert.equal(check({ fixture: fix({ workflowLog: `${asked}- pac solution list\n` }), eval: evalStub(8) }).status, 'pass');
+});
+
+test('solutions query: the documented multi-line form (bash `\\` or PowerShell backtick continuation) passes', () => {
+ const check = WORKFLOW_ASSERTIONS.get(SOLUTIONS_QUERY);
+ const asked = '- Solution selection question asked\n';
+ for (const cont of ['\\', '`']) {
+ for (const eol of ['\n', '\r\n']) {
+ const log = `${asked}node "\${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET ${cont}${eol} "solutions?\\$select=uniquename,friendlyname&\\$top=10"${eol}`;
+ assert.equal(check({ fixture: fix({ workflowLog: log }), eval: evalStub(8) }).status, 'pass', JSON.stringify({ cont, eol }));
+ }
+ }
+ // An ordinary line break is not a continuation: a later, unrelated mention of solutions must not
+ // be credited to an earlier dataverse-request.js call.
+ const unrelated = `${asked}node dataverse-request.js https://contoso.crm.dynamics.com GET 'WhoAmI'\n- solutions were discussed\n`;
+ assert.equal(check({ fixture: fix({ workflowLog: unrelated }), eval: evalStub(8) }).status, 'fail');
+});
\ No newline at end of file
diff --git a/evals/model-apps/genpage/tests/fixture-tool-results.test.js b/evals/model-apps/genpage/tests/fixture-tool-results.test.js
new file mode 100644
index 000000000..06a9b86c6
--- /dev/null
+++ b/evals/model-apps/genpage/tests/fixture-tool-results.test.js
@@ -0,0 +1,58 @@
+'use strict';
+// Corpus consistency for recorded feature-flag probes.
+//
+// Contract-2 fixtures record each command a run made in tool-results.json, including the
+// feature-gate probes `node .../scripts/lib/feature-flags.js <flag>`, which print `enabled` /
+// `disabled`. A synthetic trace once recorded `disabled` with exit code 0, contradicting the
+// script — and nothing noticed, because no check compares the two. Recorded evidence that the real
+// tool could never produce teaches the graders the wrong contract, so pin every recorded probe to
+// the exit code the actual script returns for that output, measured here by running it.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const REPO = path.join(__dirname, '..', '..', '..', '..');
+const FLAGS_SCRIPT = path.join(REPO, 'plugins', 'model-apps', 'scripts', 'lib', 'feature-flags.js');
+const FIXTURES = path.join(__dirname, '..', 'fixtures');
+
+/** Exit code the real script returns for a flag forced on/off through its env override. */
+function measuredExit(flag, on) {
+ // GENPAGE_ENABLE_<FLAG> outranks feature-flags.json (see the script's precedence), so this
+ // measures both outputs without depending on the committed flag values.
+ const envName = `GENPAGE_ENABLE_${flag.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`;
+ const r = spawnSync(process.execPath, [FLAGS_SCRIPT, flag], { encoding: 'utf8', env: { ...process.env, [envName]: on ? '1' : '0' } });
+ return { code: r.status, out: r.stdout.trim() };
+}
+
+function recordedProbes() {
+ const out = [];
+ for (const dir of fs.readdirSync(FIXTURES, { withFileTypes: true }).filter((d) => d.isDirectory())) {
+ const file = path.join(FIXTURES, dir.name, 'tool-results.json');
+ if (!fs.existsSync(file)) continue;
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
+ const events = Array.isArray(data) ? data : data.events || [];
+ for (const ev of events) {
+ // e.g. "node 'D:/repo/plugins/model-apps/scripts/lib/feature-flags.js' custom-api"
+ // "node scripts\\lib\\feature-flags.js custom-api"
+ const m = /feature-flags\.js['"]?\s+([a-z][a-z0-9-]*)\b/.exec(String(ev.command || ''));
+ if (m && typeof ev.result === 'string' && 'exitCode' in ev) out.push({ fixture: dir.name, id: ev.id, flag: m[1], result: ev.result, exitCode: ev.exitCode });
+ }
+ }
+ return out;
+}
+
+test('feature-flags.js exits 0 for enabled and 1 for disabled (the contract the fixtures record)', () => {
+ assert.deepEqual(measuredExit('custom-api', true), { code: 0, out: 'enabled' });
+ assert.deepEqual(measuredExit('custom-api', false), { code: 1, out: 'disabled' });
+});
+
+test('every recorded feature-flag probe pairs its output with the exit code the script returns', () => {
+ const probes = recordedProbes();
+ assert.ok(probes.length > 0, 'expected recorded feature-flag probes in the corpus');
+ const expected = { enabled: 0, disabled: 1 };
+ const wrong = probes.filter((p) => expected[p.result] !== p.exitCode)
+ .map((p) => `${p.fixture} ${p.id}: ${p.flag} → ${JSON.stringify(p.result)} with exitCode ${p.exitCode} (the script exits ${expected[p.result]})`);
+ assert.deepEqual(wrong, []);
+});
diff --git a/evals/model-apps/genpage/tests/phase-expectations.test.js b/evals/model-apps/genpage/tests/phase-expectations.test.js
new file mode 100644
index 000000000..14b95ff13
--- /dev/null
+++ b/evals/model-apps/genpage/tests/phase-expectations.test.js
@@ -0,0 +1,893 @@
+'use strict';
+
+// Unit tests for the per-eval Phase expectations graded from structured evidence (the checks under
+// "Per-eval expectations graded from structured evidence" and "Evals 3, 8, 9, 12, 14 and 16" in
+// lib/assertions-layer-1.js, and the hardcoded-format check in lib/assertions-layer-2.js).
+//
+// Each check is proven three ways where they apply: it PASSES on the committed fixture whose
+// evidence it reads, it FAILS on an in-memory mutation of that fixture that introduces exactly the
+// regression it exists to catch, and it SKIPs only when 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 can never 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 } = require('../lib/assertions-layer-1.js');
+const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+const { loadFixtures } = require('../lib/fixture-loader.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);
+}
+
+// A copy of a committed fixture with `field` edited (string replacement) or replaced outright.
+function mutated(dirName, field, from, to) {
+ const base = committed(dirName);
+ return { ...base, [field]: to === undefined ? from : edit(base[field], from, to) };
+}
+
+function withFile(dirName, name, from, to) {
+ const base = committed(dirName);
+ return { ...base, files: base.files.map((f) => (f.name === name ? { ...f, content: edit(f.content, from, to) } : f)) };
+}
+
+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 gradeCode(text, files) {
+ const check = PHASE5_EXPECTATIONS.get(text);
+ assert.ok(check, `a check is registered for: ${text}`);
+ return check({ files, fixture: { files }, eval: {} });
+}
+
+function assertPass(result) { assert.equal(result.status, 'pass', result.reason); }
+function assertFail(result, reason) {
+ assert.equal(result.status, 'fail', 'expected a failure');
+ 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);
+}
+
+// --- Eval 2 ------------------------------------------------------------------------------------
+
+test('eval 2: the data-source question resolves to mock data and no entity detection runs', () => {
+ const text = "Phase 1 (Planner): Data source question is skipped or answered 'mock data' — no entity detection needed";
+ assertPass(grade(text, committed('2-mock-dashboard')));
+ assertPass(grade(text, committed('2-mock-dashboard-real')));
+ assertFail(grade(text, mutated('2-mock-dashboard', 'workflowLog', 'user answered "Mock data"', 'user answered "Dataverse entities"')),
+ /not answered with mock data: - Question 2 \(data source\): user answered "Dataverse entities"/);
+ // An unrecorded question was skipped; the mock data mode handed to the builder records the result.
+ const silent = mutated('2-mock-dashboard', 'workflowLog', '- Question 2 (data source): user answered "Mock data"\n', '');
+ assertPass(grade(text, silent));
+ assertFail(grade(text, { ...silent, workflowLog: edit(silent.workflowLog, 'Data mode: mock', 'Data mode: dataverse') }), /no data-source answer and no mock data mode/);
+ const base = committed('2-mock-dashboard');
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- \`pac model list-tables --search 'account'\` — account exists\n` }),
+ /entity detection ran/);
+ assertFail(grade(text, mutated('2-mock-dashboard', 'genpagePlan', '(none — mock data page)', 'account')), /existing entities \(account\)/);
+});
+
+// --- Eval 4 ------------------------------------------------------------------------------------
+
+test('eval 4: list-tables confirms incident and contact as existing tables', () => {
+ const text = "Phase 1 (Planner): pac model list-tables --search 'incident,contact' is run; both entities confirmed as existing";
+ assertPass(grade(text, committed('4-case-wizard')));
+ assertFail(grade(text, mutated('4-case-wizard', 'workflowLog', "--search 'incident,contact'", "--search 'incident'")),
+ /no pac model list-tables --search covered contact/);
+ assertFail(grade(text, mutated('4-case-wizard', 'genpagePlan', '## Existing Entities\n\nincident, contact', '## Existing Entities\n\nincident')),
+ /does not confirm contact/);
+});
+
+test('eval 4: the entity-builder is skipped when every table exists', () => {
+ const text = 'Phase 2: Entity-builder is SKIPPED';
+ assertPass(grade(text, committed('4-case-wizard')));
+ const base = committed('4-case-wizard');
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- Dispatched genpage-entity-builder agent\n` }), /entity-builder was invoked/);
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- \`node scripts/provision-entities.js --input @x.json --apply\`\n` }), /provisioned/);
+ assertFail(grade(text, { ...base, genpagePlan: committed('7-job-candidates-new-entities').genpagePlan }), /plan schedules entity creation/);
+});
+
+test('eval 4: generate-types runs with exactly incident and contact', () => {
+ const text = "Phase 4: pac model genpage generate-types --data-sources 'incident,contact' is run";
+ assertPass(grade(text, committed('4-case-wizard')));
+ assertFail(grade(text, mutated('4-case-wizard', 'workflowLog', "generate-types --data-sources 'incident,contact'", "generate-types --data-sources 'incident'")),
+ /no generate-types run has --data-sources incident,contact \(saw incident\)/);
+ assertFail(grade(text, mutated('4-case-wizard', 'workflowLog', 'pac model genpage generate-types', 'generate types')), /was not run/);
+});
+
+test('eval 4: the wizard sample is read, not merely listed', () => {
+ const text = 'Phase 5 (Page Builder): Wizard sample (2-wizard-multi-step.tsx) is read';
+ assertPass(grade(text, committed('4-case-wizard')));
+ // The plan still names the sample in ## Relevant Samples; only the log records a read.
+ assertFail(grade(text, mutated('4-case-wizard', 'workflowLog', 'Read sample: plugins/model-apps/samples/2-wizard-multi-step.tsx', 'Read sample: plugins/model-apps/samples/9-list-with-caching.tsx')),
+ /does not record reading samples\/2-wizard-multi-step\.tsx/);
+});
+
+test('eval 4: every upload binds incident and contact, on either upload transport', () => {
+ const text = "Phase 6: Upload includes --data-sources 'incident,contact'";
+ assertPass(grade(text, committed('4-case-wizard')));
+ assertFail(grade(text, mutated('4-case-wizard', 'workflowLog', "--data-sources 'incident,contact' --prompt", '--prompt')),
+ /page\.tsx: --data-sources is none, expected incident,contact/);
+ // The file transport (scripts/genpage-upload.js) carries the same flag and is graded the same way.
+ const fileTransport = mutated('4-case-wizard', 'workflowLog', /- `pac model genpage upload[^\n]*/.exec(committed('4-case-wizard').workflowLog)[0],
+ "- Command: `node \"${PLUGIN_ROOT}/scripts/genpage-upload.js\" --env 'https://contoso.crm.dynamics.com' --app-id 'a' --code-file 'new-case-wizard/page.tsx' --data-sources 'contact,incident' --prompt-file 'new-case-wizard/prompt.txt' --agent-message-file 'new-case-wizard/agent-message.txt' --name-file 'new-case-wizard/page-name.txt' --add-to-sitemap`");
+ assertPass(grade(text, fileTransport));
+ assertFail(grade(text, { ...fileTransport, workflowLog: edit(fileTransport.workflowLog, "--data-sources 'contact,incident'", "--data-sources 'contact'") }),
+ /--data-sources is contact, expected incident,contact/);
+});
+
+// --- Eval 5 ------------------------------------------------------------------------------------
+
+test('eval 5: task exists and the plan maps the three kanban columns to status values', () => {
+ const text = 'Phase 1 (Planner): task entity confirmed as existing; plan describes kanban with 3 columns mapped to task statecode/statuscode values';
+ assertPass(grade(text, committed('5-kanban-task-board')));
+ assertFail(grade(text, mutated('5-kanban-task-board', 'workflowLog', "list-tables --search 'task'", "list-tables --search 'account'")),
+ /no pac model list-tables --search covered task/);
+ assertFail(grade(text, mutated('5-kanban-task-board', 'genpagePlan', 'Three columns mapped to task statuscode values', 'Three columns')),
+ /does not map the columns to task statuscode\/statecode/);
+});
+
+test('eval 5: status values identified after generate-types match the generated RuntimeTypes.ts', () => {
+ const text = 'Phase 4: RuntimeTypes.ts is read — status field enum values are identified for column mapping';
+ assertPass(grade(text, committed('5-kanban-task-board')));
+ assertFail(grade(text, mutated('5-kanban-task-board', 'workflowLog', '`"In Progress" = 3`', '`"In Progress" = 2`')),
+ /not in RuntimeTypes\.ts: "In Progress" = 2/);
+ const base = committed('5-kanban-task-board');
+ const noPairs = base.workflowLog.replace(/`"[^"]+" = \d+`/g, 'a status');
+ assertFail(grade(text, { ...base, workflowLog: noPairs }), /does not record the status enum values/);
+ // Without a captured RuntimeTypes.ts the recorded mapping is still required, just not cross-checked.
+ assertPass(grade(text, { ...base, runtimeTypes: null, workflowLog: edit(base.workflowLog, '`"In Progress" = 3`', '`"In Progress" = 2`') }));
+});
+
+// --- Eval 7 ------------------------------------------------------------------------------------
+
+const E7 = '7-job-candidates-new-entities';
+
+test('eval 7: list-tables records both new tables as absent on an exact match', () => {
+ const text = 'Phase 1 (Planner): pac model list-tables --search confirms cr_candidate and cr_jobrequisition do NOT exist (exact logical-name match, not fuzzy)';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'workflowLog', "--search 'cr_candidate'` — exact logical-name match: NOT FOUND", "--search 'cr_candidate'` — fuzzy match: NOT FOUND")),
+ /cr_candidate does not rest on an exact logical-name match/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', "--search 'cr_jobrequisition'` — exact logical-name match: NOT FOUND", "--search 'cr_jobrequisition'` — exact logical-name match: cr_jobrequisition")),
+ /does not record cr_jobrequisition as absent/);
+ assertFail(grade(text, mutated(E7, 'genpagePlan', '### candidate', '### applicant')), /no "### candidate" block/);
+});
+
+test('eval 7: the plan defines both tables with typed columns and the candidate → jobrequisition lookup', () => {
+ const text = 'Phase 1 (Planner): Plan includes entity definitions with columns, types, and a lookup relationship (cr_candidate → cr_jobrequisition)';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'genpagePlan', '| 1:N | jobrequisition | jobrequisition | Restrict |', '| none | none | none | none |')),
+ /candidate has no lookup relationship to jobrequisition/);
+ assertFail(grade(text, mutated(E7, 'genpagePlan', '| openings | int | yes |', '| openings | | yes |')), /without a type: openings/);
+});
+
+test('eval 7 and 15: the solution question is asked and its answer is what ## Environment records', () => {
+ const e7 = "Phase 1 (Planner): Because entities will be created, the planner asks the solution selection question via AskUserQuestion and records the choice in ## Environment as 'Solution: <uniqueName>' and 'Publisher Prefix: <prefix>'";
+ const e15 = 'Phase 1 (Planner): Solution selection question is asked (because new entity will be created) and recorded in ## Environment';
+ assertPass(grade(e7, committed(E7)));
+ assertPass(grade(e15, committed('15-support-tickets-real')));
+ assertFail(grade(e7, mutated(E7, 'genpagePlan', '- Solution: Default', '- Solution: ContosoRecruiting')), /maker answered "?"Use Default Solution"?/);
+ assertFail(grade(e15, mutated('15-support-tickets-real', 'genpagePlan', '- Solution: Crdec34', '- Solution: Default')), /maker answered "Crdec34/);
+ assertFail(grade(e7, mutated(E7, 'workflowLog', '- User selected: "Use Default Solution"', '- (answer not recorded)')), /answer to the solution question is not recorded/);
+ assertFail(grade(e7, mutated(E7, 'genpagePlan', '- Publisher Prefix: cr\n', '\n')), /no "Publisher Prefix/);
+});
+
+test('eval 7: the entity-builder records the Environment it read from the plan', () => {
+ const text = "Phase 2b (Entity Builder): Reads Solution + Publisher Prefix from the plan's ## Environment";
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'entityCreationLog', '- Publisher Prefix: cr', '- Publisher Prefix: new')), /builder recorded Publisher Prefix: new, plan declares cr/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', 'Reads Solution=Default, Publisher Prefix=cr', 'Reads Solution=Contoso, Publisher Prefix=cr')), /builder read Solution=Contoso/);
+ assertFail(grade(text, { ...committed(E7), entityCreationLog: null }), /no genpage-entity-creation-log\.md/);
+});
+
+test('eval 7: the referenced table is provisioned before the table holding the lookup', () => {
+ const text = 'Phase 2b (Entity Builder): cr_jobrequisition (independent) is provisioned before cr_candidate (has lookup) to satisfy dependency ordering';
+ assertPass(grade(text, committed(E7)));
+ const reversed = [
+ '# Entity Creation Log', '', '## Environment', '- Solution: Default', '- Publisher Prefix: cr', '',
+ '## Created Tables', '', '### Candidate', '- Resolved Full Name: cr_candidate', '',
+ '### Job Requisition', '- Resolved Full Name: cr_jobrequisition', '',
+ ].join('\n');
+ assertFail(grade(text, { ...committed(E7), entityCreationLog: reversed }), /candidate \(has the lookup\) was provisioned before jobrequisition/);
+ assertFail(grade(text, mutated(E7, 'genpagePlan', '| 1:N | jobrequisition | jobrequisition | Restrict |', '| none | none | none | none |')),
+ /no candidate → jobrequisition lookup/);
+});
+
+test('eval 7: provision-entities.js creates tables and columns from one input JSON', () => {
+ const text = 'Phase 2b (Entity Builder): provision-entities.js handles entity creation and column definitions atomically with internal propagation management';
+ assertPass(grade(text, committed(E7)));
+ const base = committed(E7);
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- \`node scripts/add-column.js --table cr_candidate --solution Default\`\n` }), /per-object scripts .*add-column\.js/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', 'provision-input.json --apply --sample-data', 'provision-input.json --sample-data')), /--input <json> --apply/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', 'scripts/provision-entities.js', 'scripts/provision.js')), /provision-entities\.js was not run/);
+});
+
+test('eval 7: the lookup is provisioned through the input JSON and recorded', () => {
+ const text = 'Phase 2b (Entity Builder): Lookup relationship (cr_candidate → cr_jobrequisition) is provisioned via input JSON; provision-entities.js handles propagation internally';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'entityCreationLog', '| 1:N | cr_jobrequisition | cr_candidate |', '| 1:N | cr_candidate | cr_jobrequisition |')),
+ /no jobrequisition → candidate \(1:N\) row/);
+ const base = committed(E7);
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- \`node scripts/create-relationship.js --from cr_jobrequisition --to cr_candidate\`\n` }),
+ /create-relationship\.js was run/);
+});
+
+test('eval 7: the sample-data question is asked and its answer is the one acted on', () => {
+ const text = 'Phase 2b (Entity Builder): User is asked about sample data via AskUserQuestion';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'workflowLog', 'user answered "Yes, add sample data"', 'user answered "No, skip"')),
+ /answered "No, skip" but provisioning seeded sample data/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', '- Question 4 (sample data): user answered "Yes, add sample data"', '- Question 4: none')),
+ /no answered sample-data question/);
+});
+
+test('eval 7: sample rows go through the input JSON with $parent/match parent references', () => {
+ const text = 'Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js input JSON; parent references use $parent/match convention for dependency resolution';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'workflowLog', ' (parent binding via $parent/match)', '')), /\$parent\/match parent reference/);
+ assertFail(grade(text, mutated(E7, 'workflowLog', '--apply --sample-data', '--apply')), /no provision-entities\.js --sample-data run/);
+ assertSkip(grade(text, mutated(E7, 'workflowLog', 'user answered "Yes, add sample data"', 'user answered "No, skip"')), /declined sample data/);
+});
+
+test('eval 7: the transaction log records every planned create and the names are reported back', () => {
+ const text = 'Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/genpage-entity-creation-log.md captures each successful operation';
+ assertPass(grade(text, committed(E7)));
+ assertFail(grade(text, mutated(E7, 'entityCreationLog', '| cr_candidate | Recruiter | cr_Recruiter | cr_recruiter | ... |', '')),
+ /column recruiter of cr_candidate has no Created Columns row/);
+ assertFail(grade(text, mutated(E7, 'entityCreationLog', '- Resolved Full Name: cr_candidate', '- Resolved Full Name: ')), /table candidate has no Created Tables entry/);
+ assertFail(grade(text, { ...committed(E7), entityCreationLog: null }), /no genpage-entity-creation-log\.md/);
+});
+
+test('eval 7: generate-types and the upload use the created table names', () => {
+ const types = 'Phase 4: pac model genpage generate-types is run with the created entity names';
+ const upload = 'Phase 6: Upload includes --data-sources with both created entity names';
+ assertPass(grade(types, committed(E7)));
+ assertPass(grade(upload, committed(E7)));
+ assertFail(grade(types, mutated(E7, 'workflowLog', "generate-types --data-sources 'cr_candidate,cr_jobrequisition'", "generate-types --data-sources 'cr_candidate'")),
+ /no generate-types run has --data-sources cr_jobrequisition,cr_candidate/);
+ assertFail(grade(upload, mutated(E7, 'workflowLog', "page.tsx --data-sources 'cr_candidate,cr_jobrequisition'", "page.tsx --data-sources 'cr_candidate'")),
+ /--data-sources is cr_candidate, expected cr_jobrequisition,cr_candidate/);
+});
+
+// --- Eval 10 -----------------------------------------------------------------------------------
+
+test('eval 10: the plan schedules the widget table for creation', () => {
+ const text = 'Phase 1 (Planner): Plan records cr_widget under Entity Creation Required';
+ assertPass(grade(text, committed('10-auth-timeout-halt')));
+ assertFail(grade(text, mutated('10-auth-timeout-halt', 'genpagePlan', '### widget', '### gadget')), /no "### widget" block/);
+});
+
+test('eval 10: check-auth.js runs and parses before any entity-builder dispatch', () => {
+ const text = 'Phase 2a: Orchestrator runs scripts/check-auth.js BEFORE invoking entity-builder; parses the returned JSON';
+ assertPass(grade(text, committed('10-auth-timeout-halt')));
+ const base = { ...committed('4-case-wizard'), genpagePlan: null };
+ assertFail(grade(text, { ...base, workflowLog: '- Dispatched genpage-entity-builder agent\n- `node scripts/check-auth.js` → returned `{ ok: true, ... }`\n' }),
+ /mutation attempted without the latest successful auth gate/);
+ assertFail(grade(text, { ...base, workflowLog: '- `node scripts/check-auth.js` → returned something unreadable\n' }), /malformed or missing auth result/);
+ assertFail(grade(text, { ...base, workflowLog: '- Dispatched genpage-entity-builder agent\n' }), /check-auth\.js not invoked/);
+});
+
+// --- Eval 11 -----------------------------------------------------------------------------------
+
+const E11 = '11-recruitment-multi-page';
+const E11_REAL = '11-recruitment-pages-real';
+
+test('eval 11: three pages with distinct files, purposes and per-page specifications', () => {
+ const pages = 'Phase 1 (Planner): Plan includes 3 pages in the Pages table with distinct file names and purposes';
+ const specs = 'Phase 1 (Planner): Per-Page Specifications section has an entry for each of the 3 pages';
+ for (const dir of [E11, E11_REAL]) {
+ assertPass(grade(pages, committed(dir)));
+ assertPass(grade(specs, committed(dir)));
+ }
+ assertFail(grade(pages, mutated(E11, 'genpagePlan', '| Metrics | hiring-metrics.tsx |', '| Metrics | interview-schedule.tsx |')), /file names are not distinct/);
+ assertFail(grade(pages, { ...committed(E11), genpagePlan: committed('4-case-wizard').genpagePlan }), /## Pages has 1 row\(s\), expected 3/);
+ assertFail(grade(specs, mutated(E11, 'genpagePlan', '### Metrics', '### Dashboard')), /no "### Metrics" entry/);
+});
+
+test('eval 11: pages are only built from a plan that passes the Phase 5a gate', () => {
+ const text = 'Phase 5a: Orchestrator validates the plan — at least one page, unique filenames, each page has a matching Per-Page Specifications subsection';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ const invalid = mutated(E11, 'genpagePlan', '| Metrics | hiring-metrics.tsx |', '| Metrics | interview-schedule.tsx |');
+ assertFail(grade(text, invalid), /pages were built from a plan that fails Phase 5a/);
+ // The same invalid plan with nothing generated is the gate holding.
+ assertPass(grade(text, { ...invalid, files: [] }));
+});
+
+test('eval 11: generate-types runs once for contact and appointment into one RuntimeTypes.ts', () => {
+ const text = "Phase 4: pac model genpage generate-types is run ONCE with --data-sources 'contact,appointment'; a single RuntimeTypes.ts is generated";
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ const base = committed(E11);
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- pac model genpage generate-types --data-sources 'contact' --output-file other/RuntimeTypes.ts\n` }),
+ /ran 2 time\(s\), expected once/);
+ assertFail(grade(text, mutated(E11, 'workflowLog', "--data-sources 'contact,appointment' --output-file recruitment-pages/RuntimeTypes.ts", "--data-sources 'contact' --output-file recruitment-pages/RuntimeTypes.ts")),
+ /no generate-types run has --data-sources contact,appointment/);
+ assertFail(grade(text, mutated(E11, 'workflowLog', '--output-file recruitment-pages/RuntimeTypes.ts', '--output-file recruitment-pages/Types.ts')), /wrote Types\.ts/);
+});
+
+test('eval 11: each builder targets its own file', () => {
+ const text = 'Phase 5c: Each builder receives a distinct target filename — no two builders target the same file';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, mutated(E11, 'workflowLog', 'Builder C target: hiring-metrics.tsx', 'Builder C target: interview-schedule.tsx')),
+ /two builders were dispatched with target interview-schedule\.tsx/);
+ const base = committed(E11);
+ assertFail(grade(text, { ...base, files: base.files.filter((f) => f.name !== 'hiring-metrics.tsx') }), /no builder wrote hiring-metrics\.tsx/);
+ assertSkip(grade(text, committed('4-case-wizard')), /single-page plan/);
+});
+
+test('eval 11: each page binds only the tables its own specification declares', () => {
+ const text = 'Phase 5c: Each builder reads the same genpage-plan.md but extracts only its own page specification';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, withFile(E11, 'candidate-list.tsx', "dataApi.queryTable('contact', {", "dataApi.queryTable('appointment', {")),
+ /candidate-list\.tsx binds appointment, which its own specification \(Entities: contact\) does not declare/);
+ // A call inside a comment or a string is not a binding.
+ assertPass(grade(text, withFile(E11, 'candidate-list.tsx', "dataApi.queryTable('contact', {", "/* dataApi.queryTable('appointment') */ dataApi.queryTable('contact', {")));
+ assertSkip(grade(text, committed('4-case-wizard')), /single-page plan/);
+});
+
+test('eval 11: every page resolves its types from the one generated RuntimeTypes.ts', () => {
+ const text = 'Phase 5c: Each builder reads the same RuntimeTypes.ts for column verification';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, withFile(E11, 'hiring-metrics.tsx', "from './RuntimeTypes'", "from './MetricsTypes'")), /hiring-metrics\.tsx does not import the shared \.\/RuntimeTypes/);
+ const base = committed(E11);
+ assertFail(grade(text, { ...base, workflowLog: `${base.workflowLog}\n- pac model genpage generate-types --data-sources 'contact' --output-file metrics/RuntimeTypes.ts\n` }),
+ /could read different schemas/);
+});
+
+test('eval 11: each page has exactly one create upload with its own --code-file', () => {
+ const text = 'Phase 6: All 3 pages are deployed via separate pac model genpage upload commands, each with the correct --code-file';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, mutated(E11, 'workflowLog', '--code-file recruitment-pages/hiring-metrics.tsx', '--code-file recruitment-pages/candidate-list.tsx')),
+ /candidate-list\.tsx has 2 create upload/);
+});
+
+test('eval 11: cross-page navigation uses sibling PAGEREF placeholders or deployed ids, never invented GUIDs', () => {
+ const text = 'Phase 5c: Cross-page navigation (e.g., candidate list → candidate detail) uses quoted `"PAGEREF_<filename>"` placeholders, never invented GUIDs';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, withFile(E11, 'candidate-list.tsx', "pageId: 'PAGEREF_interview-schedule'", "pageId: '11111111-2222-3333-4444-555555555555'")),
+ /literal page id appears before resolution/);
+ assertFail(grade(text, withFile(E11_REAL, 'hiring-metrics-dashboard.tsx', '492d8c42-b5fc-4ec5-ad44-6809c6673e9a', '99999999-b5fc-4ec5-ad44-6809c6673e9a')),
+ /not a deployed GUID from the page map/);
+ assertSkip(grade(text, committed('4-case-wizard')), /single-page fixture/);
+});
+
+test('eval 11: Phase 6.5 re-uploads exactly the affected pages with the update flag set', () => {
+ const text = 'Phase 6.5: If any .tsx contains PAGEREF_ tokens, orchestrator builds a filename→page-id map sorted by length desc, replaces quoted `"PAGEREF_<name>"` tokens with the matching GUID (word-boundary safe), and re-uploads only affected files with the full update flag set';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ const base = committed(E11);
+ const secondReupload = base.workflowLog.split(/\r?\n/).find((l) => /interview-schedule\.tsx --page-id/.test(l));
+ assertFail(grade(text, { ...base, workflowLog: edit(base.workflowLog, secondReupload, '') }),
+ /re-uploaded candidate-list\.tsx, but the affected files are candidate-list\.tsx,interview-schedule\.tsx/);
+ assertFail(grade(text, mutated(E11_REAL, 'workflowLog', '--agent-message "Replaced PAGEREF_candidate-list', '--add-to-sitemap --agent-message "Replaced PAGEREF_candidate-list')),
+ /re-upload passes --add-to-sitemap/);
+ assertFail(grade(text, mutated(E11_REAL, 'workflowLog', '--page-id e2022b27-548b-43be-95bd-4dafa02e060c', '--page-id 00000000-548b-43be-95bd-4dafa02e060c')),
+ /was never returned by an upload/);
+ assertFail(grade(text, mutated(E11_REAL, 'workflowLog', '--page-id e2022b27-548b-43be-95bd-4dafa02e060c --code-file D:/temp/recruitment-app/hiring-metrics-dashboard.tsx --data-sources "contact,appointment"', '--page-id e2022b27-548b-43be-95bd-4dafa02e060c --code-file D:/temp/recruitment-app/hiring-metrics-dashboard.tsx')),
+ /re-upload --data-sources none differs from its create/);
+ assertSkip(grade(text, committed('4-case-wizard')), /no \.tsx carries a PAGEREF_/);
+});
+
+test('eval 11: the Phase 6.5 re-upload prompt is a delta, not the original description', () => {
+ const text = "Phase 6.5: Re-upload uses a DELTA --prompt (e.g. 'Resolve cross-page navigation placeholders to real page GUIDs') — NOT a copy of the original page description from Phase 6";
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ const original = 'Build me three pages for a recruitment app: a candidate list page, an interview schedule page, and a hiring metrics dashboard. Use the contact and appointment entities.';
+ assertFail(grade(text, mutated(E11_REAL, 'workflowLog', 'Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)', original)),
+ /re-upload prompt restates ## User Requirements/);
+ assertFail(grade(text, mutated(E11, 'workflowLog', '--page-id <resolved-id> --data-sources \'contact,appointment\' --prompt "Resolve cross-page navigation placeholders to real page GUIDs" --model claude-sonnet --agent-message "PAGEREF resolution"\n- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/interview-schedule.tsx',
+ '--page-id <resolved-id> --data-sources \'contact,appointment\' --prompt "Candidate list page (eval 11)" --model claude-sonnet --agent-message "PAGEREF resolution"\n- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/interview-schedule.tsx')),
+ /candidate-list\.tsx: re-upload prompt repeats the create prompt/);
+ assertSkip(grade(text, committed('4-case-wizard')), /no Phase 6\.5 re-upload/);
+});
+
+test('eval 11: an unresolved PAGEREF is reported and never shipped', () => {
+ const text = 'Phase 6.5: Unresolved PAGEREF tokens (typos, missing siblings) cause an explicit error to the user — never silently shipped';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ const typo = withFile(E11, 'candidate-list.tsx', "'PAGEREF_interview-schedule'", "'PAGEREF_interview-scheduel'");
+ assertFail(grade(text, typo), /PAGEREF_interview-scheduel names no sibling page and no error was reported/);
+ const reported = { ...typo, workflowLog: `${typo.workflowLog}\n- ERROR: PAGEREF_interview-scheduel has no matching sibling page — stopped\n` };
+ assertFail(grade(text, reported), /re-uploaded despite unresolved PAGEREF_interview-scheduel/);
+ const candidateReupload = reported.workflowLog.split(/\r?\n/).find((l) => /candidate-list\.tsx --page-id/.test(l));
+ assertPass(grade(text, { ...reported, workflowLog: edit(reported.workflowLog, candidateReupload, '') }));
+ assertFail(grade(text, withFile(E11_REAL, 'hiring-metrics-dashboard.tsx', '"492d8c42-b5fc-4ec5-ad44-6809c6673e9a"', '"PAGEREF_candidate-list"')),
+ /PAGEREF_candidate-list remains after resolution/);
+ assertSkip(grade(text, committed('4-case-wizard')), /no cross-page navigation/);
+});
+
+test('eval 11: the Phase 8 summary lists every page with its deployed entities and status', () => {
+ const text = 'Phase 8: Summary table lists all 3 pages with their files, entities, and deployment status';
+ assertPass(grade(text, committed(E11)));
+ assertPass(grade(text, committed(E11_REAL)));
+ assertFail(grade(text, mutated(E11_REAL, 'workflowLog', '| Candidate List | candidate-list.tsx | contact | Deployed |', '| Candidate List | candidate-list.tsx | contact, appointment | Deployed |')),
+ /lists candidate-list\.tsx with entities contact, appointment, deployed with contact/);
+ assertFail(grade(text, mutated(E11, 'workflowLog', '| Metrics | hiring-metrics.tsx | contact, appointment | Deployed |', '')), /does not list hiring-metrics\.tsx/);
+ assertFail(grade(text, mutated(E11, 'workflowLog', '| Metrics | hiring-metrics.tsx | contact, appointment | Deployed |', '| Metrics | hiring-metrics.tsx | contact, appointment | |')),
+ /gives hiring-metrics\.tsx no deployment status/);
+});
+
+// --- Eval 13 -----------------------------------------------------------------------------------
+
+test('eval 13: list-languages output and the plan Localization section carry every detected LCID', () => {
+ const output = 'Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English';
+ const section = 'Phase 1 (Planner): Plan includes a Localization section listing detected languages';
+ assertPass(grade(output, committed('13-contact-localization')));
+ assertPass(grade(section, committed('13-contact-localization')));
+ assertFail(grade(output, mutated('13-contact-localization', 'workflowLog', ', French (France) (1036, fr-FR)', '')), /lacks LCID 1036/);
+ // The PAC table shape is read too.
+ const table = mutated('13-contact-localization', 'workflowLog', /- `pac model list-languages`[^\n]*/.exec(committed('13-contact-localization').workflowLog)[0],
+ '`pac model list-languages`\nLCID Language Code RTL\n1033 English (United States) en-US No\n1025 Arabic (Saudi Arabia) ar-SA Yes\n1036 French (France) fr-FR No');
+ assertPass(grade(output, table));
+ assertFail(grade(section, mutated('13-contact-localization', 'genpagePlan', '## Localization', '## Notes')), /no Localization section/);
+ assertFail(grade(section, mutated('13-contact-localization', 'genpagePlan', '(1036, fr-FR)', '(fr-FR)')), /does not list detected LCID 1036/);
+ assertFail(grade(section, mutated('13-contact-localization', 'workflowLog', 'pac model list-languages', 'language discovery')), /list-languages was not run/);
+});
+
+test('eval 13: generated text carries no hardcoded currency symbols or date formats', () => {
+ const text = 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats';
+ const page = (body) => [{ name: 'page.tsx', content: `export default function GeneratedComponent() {\n ${body}\n}\n` }];
+ assertPass(gradeCode(text, committed('13-contact-localization').files));
+ assertPass(gradeCode(text, page('return <Text>{`${count} items`}</Text>;')));
+ assertPass(gradeCode(text, page('// never write $100 or MM/dd/yyyy here\n return <Text>{formatCurrency(total)} {formatDate(due)}</Text>;')));
+ assertFail(gradeCode(text, page('return <Text>${total}</Text>;')), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page('return <Text>{`$${amount.toFixed(2)}`}</Text>;')), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page("return <Text>{'Total: \u20ac'}</Text>;")), /hardcoded currency symbol "\u20ac"/);
+ assertFail(gradeCode(text, page("const fmt = 'MM/dd/yyyy'; return null;")), /hardcoded date format "MM\/dd\/yyyy"/);
+ assertFail(gradeCode(text, page("const f = new Intl.NumberFormat(lang, { style: 'currency', currency: 'USD' }); return null;")), /hardcoded currency code/);
+ assertFail(gradeCode(text, page("return <Text>{due.toLocaleDateString('en-US')}</Text>;")), /hardcoded locale for date formatting/);
+ // `$` at a string boundary, joined onto an amount with `+`.
+ assertFail(gradeCode(text, page("return <Text>{'$' + total.toFixed(2)}</Text>;")), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page("const label = 'Total: $' + total; return null;")), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page('const label = "Total: $ " + total; return null;')), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page("const label = total + ' $'; return null;")), /hardcoded "\$" currency symbol/);
+ assertFail(gradeCode(text, page('const label = `Total: $` + total; return null;')), /hardcoded "\$" currency symbol/);
+ // ...while OData query options and template interpolation stay valid.
+ assertPass(gradeCode(text, page("const q = '?$select=name,revenue&$top=' + n; return null;")));
+ assertPass(gradeCode(text, page("const q = '$filter=statecode eq 0'; return null;")));
+ assertPass(gradeCode(text, page('return <Text>{`${count}` + suffix}</Text>;')));
+ // `currency:` is a number-format option only beside style: 'currency'.
+ assertPass(gradeCode(text, page("const labels = { currency: 'Devise', total: 'Total' }; return null;")));
+ assertPass(gradeCode(text, page("const t = { fr: { currency: 'Devise' } }; return null;")));
+ assertFail(gradeCode(text, page("return <Text>{n.toLocaleString(lang, { currency: 'EUR', style: 'currency' })}</Text>;")), /hardcoded currency code/);
+ // Regex literals match INPUT; they display nothing. Stripping symbols before formatting is fine.
+ assertPass(gradeCode(text, page("const v = Number(raw.replace(/[$\u20ac\u00a3]/g, '')); return <Text>{formatCurrency(v)}</Text>;")));
+ assertPass(gradeCode(text, page("const v = raw.replace(/^\\$\\s*/, ''); return <Text>{formatCurrency(Number(v))}</Text>;")));
+ assertFail(gradeCode(text, page("const v = raw.replace(/[$]/g, ''); return <Text>{'$' + v}</Text>;")), /hardcoded "\$" currency symbol/);
+ // Property keys are read as keys whether bare or quoted; the VALUE's literal type decides.
+ assertFail(gradeCode(text, page('const f = new Intl.NumberFormat(lang, { "style": "currency", "currency": "USD" }); return null;')), /hardcoded currency code/);
+ assertFail(gradeCode(text, page("const f = new Intl.NumberFormat(lang, { style: 'currency', currency: `USD` }); return null;")), /hardcoded currency code/);
+ assertPass(gradeCode(text, page('const f = new Intl.NumberFormat(lang, { style: "currency", currency: `${currencyCode}` }); return null;')));
+ assertPass(gradeCode(text, page("const f = new Intl.NumberFormat(lang, { style: 'currency', currency: settings.currencycode }); return null;")));
+ assertPass(gradeCode(text, page('const labels = { "currency": "Devise", "style": "Style" }; return null;')));
+ assertPass(gradeCode(text, page("const mode = isMoney ? 'currency' : 'decimal'; return null;")));
+});
+
+// --- Eval 15 -----------------------------------------------------------------------------------
+
+const E15 = '15-support-tickets-real';
+
+test('eval 15: cr_ticket is found absent and planned with priority/status choices and a due date', () => {
+ const absent = 'Phase 1 (Planner): cr_ticket is identified as NOT existing';
+ const choices = 'Phase 1 (Planner): Plan includes choice column definitions for priority and status under Choice Columns, with numeric option values starting at 100000000';
+ const due = 'Phase 1 (Planner): Plan includes a datetime column for due date';
+ assertPass(grade(absent, committed(E15)));
+ assertPass(grade(choices, committed(E15)));
+ assertPass(grade(due, committed(E15)));
+ assertFail(grade(absent, mutated(E15, 'workflowLog', 'No tables found matching the specified criteria.\nResult: cr_ticket does NOT exist → needs creation.', 'Found 1 table: cr_ticket.')),
+ /does not record cr_ticket as absent/);
+ assertFail(grade(choices, mutated(E15, 'genpagePlan', 'Low (100000000)', 'Low (1)')), /priority option values 1, 100000001/);
+ assertFail(grade(choices, mutated(E15, 'genpagePlan', '| status | Open', '| state | Open')), /Choice Columns has no status row/);
+ assertFail(grade(due, mutated(E15, 'genpagePlan', '| duedate | datetime |', '| duedate | string |')), /duedate has type string, not datetime/);
+});
+
+test('eval 15: the entity-builder runs only after an ok:true check-auth result', () => {
+ const text = 'Phase 2a: scripts/check-auth.js returns ok:true before entity-builder is invoked';
+ assertPass(grade(text, committed(E15)));
+ assertFail(grade(text, mutated(E15, 'workflowLog', 'Result: ok=true, identitiesMatch=true', 'Result: ok=false, blocker=whoami_403')),
+ /without the latest successful auth gate/);
+ assertFail(grade(text, { ...committed(E15), workflowLog: '- `node scripts/check-auth.js` → returned `{ ok: true, ... }`\n' }), /entity-builder was never invoked/);
+});
+
+test('eval 15: provisioned picklists, read from the generated RuntimeTypes.ts', () => {
+ const priority = 'Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)';
+ const status = 'Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000';
+ assertPass(grade(priority, committed(E15)));
+ assertPass(grade(status, committed(E15)));
+ assertFail(grade(priority, mutated(E15, 'runtimeTypes', '"Critical" = 100000003,', '')), /has 3 option\(s\), expected 4/);
+ assertFail(grade(priority, mutated(E15, 'runtimeTypes', '"Medium" = 100000001,', '"Normal" = 100000001,')), /options are Low=100000000, Normal=100000001/);
+ assertFail(grade(status, mutated(E15, 'runtimeTypes', '"Open" = 100000000,', '"Open" = 1,')), /values are 1, 100000001/);
+ assertFail(grade(status, mutated(E15, 'runtimeTypes', '"cr_ticket-cr_status": cr_ticket_cr_status,', '')), /registers no ticket-status choice/);
+ assertSkip(grade(status, { ...committed(E15), runtimeTypes: null }), /RuntimeTypes\.ts was not captured/);
+});
+
+test('eval 15: the solution travels in the input JSON and matches ## Environment', () => {
+ const text = 'Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration';
+ assertPass(grade(text, committed(E15)));
+ assertFail(grade(text, mutated(E15, 'entityCreationLog', '- Solution: Crdec34', '- Solution: Default')), /transaction log records Solution: Default, plan declares Crdec34/);
+ assertFail(grade(text, mutated(E15, 'workflowLog', '--input @D:/temp/support-tickets/provision-input.json --apply', '--solution Default --input @D:/temp/support-tickets/provision-input.json --apply')),
+ /--solution Default contradicts Solution: Crdec34/);
+ assertFail(grade(text, mutated(E15, 'workflowLog', '--input @D:/temp/support-tickets/provision-input.json ', '')), /not run with --input <json>/);
+});
+
+test('eval 15: every create in the transaction log carries its metadata id', () => {
+ const text = 'Phase 2b (Entity Builder): Transaction log (genpage-entity-creation-log.md) records each create with its returned metadataId';
+ assertPass(grade(text, committed(E15)));
+ assertFail(grade(text, mutated(E15, 'entityCreationLog', '| cr_ticket | Due Date | cr_DueDate | cr_duedate | n/a |', '| cr_ticket | Due Date | cr_DueDate | cr_duedate | ... |')),
+ /Created Columns cr_duedate has Metadata ID \.\.\./);
+ assertFail(grade(text, mutated(E15, 'entityCreationLog', '| cr_ticket | Due Date | cr_DueDate | cr_duedate | n/a |', '')), /column duedate of cr_ticket has no Created Columns row/);
+ // A GUID is a recorded id too.
+ assertPass(grade(text, mutated(E15, 'entityCreationLog', '| cr_ticket | Due Date | cr_DueDate | cr_duedate | n/a |', '| cr_ticket | Due Date | cr_DueDate | cr_duedate | 0f8fad5b-d9cb-469f-a165-70867728950e |')));
+});
+
+test('eval 15: generate-types picks up an enum registration for every planned choice column', () => {
+ const text = 'Phase 4: pac model genpage generate-types picks up the enum registrations';
+ assertPass(grade(text, committed(E15)));
+ assertFail(grade(text, mutated(E15, 'runtimeTypes', '"cr_ticket-cr_status": cr_ticket_cr_status,', '')), /EnumRegistrations has no ticket-status entry/);
+ assertFail(grade(text, mutated(E15, 'runtimeTypes', '"Closed" = 100000003,', '"Closed" = 100000004,')), /values 100000000,100000001,100000002,100000004 differ/);
+ assertFail(grade(text, mutated(E15, 'workflowLog', 'generate-types --data-sources "cr_ticket"', 'generate-types --data-sources "contact"')), /no generate-types run has --data-sources cr_ticket/);
+ assertSkip(grade(text, { ...committed(E15), runtimeTypes: null }), /RuntimeTypes\.ts was not captured/);
+});
+
+// --- Eval 19 -----------------------------------------------------------------------------------
+
+const E19 = '19-add-weather-connector';
+
+test('eval 19: the edited page comes from a genpage list of the selected app', () => {
+ const text = 'Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names';
+ assertPass(grade(text, committed(E19)));
+ assertFail(grade(text, mutated(E19, 'workflowLog', 'pac model genpage list --app-id aa112233-1122-1122-1122-aabbccdd1234', 'pac model genpage list --app-id cc334455-3344-3344-3344-ccddeeff3456')),
+ /pac model genpage list --app-id aa112233-1122-1122-1122-aabbccdd1234 was not run/);
+ assertFail(grade(text, mutated(E19, 'workflowLog', ' - Seattle Weather — `bb223344-2233-2233-2233-bbccddee2345`', ' - Seattle Weather')),
+ /page bb223344-2233-2233-2233-bbccddee2345 does not appear in the recorded genpage list output/);
+ assertFail(grade(text, mutated(E19, 'workflowLog', '- `pac model list` → 2 apps found:', '- apps recalled from memory:')), /before the app was discovered/);
+});
+
+test('eval 19: genpage-edit-plan.md is written at the working-directory root', () => {
+ const text = 'Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)';
+ assertPass(grade(text, committed(E19)));
+ assertFail(grade(text, { ...committed(E19), genpageEditPlan: null }), /not at the working-directory root/);
+ assertFail(grade(text, mutated(E19, 'workflowLog', '`genpage-edit-plan.md` written to the working directory root (not inside `bb223344-…/`)',
+ 'genpage-edit-plan.md written to seattle-weather-edit/bb223344-2233-2233-2233-bbccddee2345/genpage-edit-plan.md')),
+ /written inside the <page-id>\/ folder/);
+ assertSkip(grade(text, committed('4-case-wizard')), /create flow/);
+});
+
+// --- Contract-2 fixtures: helpers for event and artifact mutations ------------------------------
+
+// A copy of a committed fixture whose ordered tool-result events are rewritten by `change`.
+function withEvents(dirName, change) {
+ const base = committed(dirName);
+ return { ...base, events: change(structuredClone(base.events)) };
+}
+
+function event(events, id) {
+ const found = events.find((e) => e.id === id);
+ assert.ok(found, `fixture event ${id} exists`);
+ return found;
+}
+
+function withArtifact(dirName, name, from, to) {
+ const base = committed(dirName);
+ return { ...base, artifacts: { ...base.artifacts, [name]: to === undefined ? from : edit(base.artifacts[name], from, to) } };
+}
+
+function withoutArtifact(dirName, name) {
+ const base = committed(dirName);
+ const artifacts = { ...base.artifacts };
+ assert.ok(name in artifacts, `fixture artifact ${name} exists`);
+ delete artifacts[name];
+ return { ...base, artifacts };
+}
+
+// --- Eval 3 ------------------------------------------------------------------------------------
+
+const E3 = '3-contacts-edit-search-sort';
+
+test('eval 3: apps and pages are offered from the PAC listings, and the restated choice precedes download', () => {
+ const apps = 'Edit Phase 1a: Apps are presented to the user via AskUserQuestion using the actual Display Name and app-id GUID from pac model list output';
+ const pages = 'Edit Phase 1b: Pages are presented to the user via AskUserQuestion using the actual page names and page-id GUIDs from pac model genpage list output';
+ const restated = 'Edit Phase 1c: Selection is restated to the user before proceeding to download';
+ assertPass(grade(apps, committed(E3)));
+ assertPass(grade(pages, committed(E3)));
+ assertPass(grade(restated, committed(E3)));
+ // The listing names the app differently from the question: the offered name is not the listed one.
+ assertFail(grade(apps, withEvents(E3, (ev) => { event(ev, 'list-apps').result = event(ev, 'list-apps').result.replace('Sales Hub ', 'Sales Desk '); return ev; })),
+ /offers 11111111-2222-3333-4444-555555555555 without its listed name "Sales Desk"/);
+ assertFail(grade(apps, withEvents(E3, (ev) => { event(ev, 'list-apps').result = event(ev, 'list-apps').result.split('\n').filter((l) => !/Sales Hub/.test(l)).join('\n'); return ev; })),
+ /offers 11111111-2222-3333-4444-555555555555, which the listing does not contain/);
+ // The run downloaded a page that was listed but never offered.
+ assertFail(grade(pages, withEvents(E3, (ev) => { event(ev, 'download').command = event(ev, 'download').command.replace('22222222-3333-4444-5555-666666666666', '33333333-4444-5555-6666-777777777777'); return ev; })),
+ /continued with \(33333333-4444-5555-6666-777777777777\) was not among the offered pages/);
+ assertFail(grade(restated, mutated(E3, 'workflowLog', '- "Editing **Contacts Directory** (22222222-3333-4444-5555-666666666666) in app **Sales Hub** (11111111-2222-3333-4444-555555555555). Continuing to download the existing page code…"', '- Continuing.')),
+ /no restatement of the selected app and page/);
+});
+
+test('eval 3: config.json dataSources drive RuntimeTypes generation', () => {
+ const text = "Edit Phase 3: config.json is read; since dataSources contains 'contact', RuntimeTypes.ts is generated";
+ assertPass(grade(text, committed(E3)));
+ assertFail(grade(text, withArtifact(E3, 'before/config.json', '"dataSources": ["contact"]', '"dataSources": []')), /dataSources are none, not contact/);
+ assertFail(grade(text, withEvents(E3, (ev) => { event(ev, 'generate-types').command = event(ev, 'generate-types').command.replace("--data-sources 'contact'", "--data-sources 'account'"); return ev; })),
+ /not run with config\.json's dataSources contact \(saw account\)/);
+ assertSkip(grade(text, withoutArtifact(E3, 'before/config.json')), /config\.json was not captured/);
+});
+
+test('eval 3: the edit plan restates what the planner read from the downloaded <page-id>/ folder', () => {
+ const text = 'Edit Phase 4: edit-planner reads page.tsx, config.json, and prompt.txt from the <page-id>/ folder';
+ assertPass(grade(text, committed(E3)));
+ assertFail(grade(text, mutated(E3, 'genpageEditPlan', '- **Original prompt (from prompt.txt):** Build a contacts directory page', '- **Original prompt (from prompt.txt):** Build a contacts gallery page')),
+ /original prompt differs from the downloaded prompt\.txt/);
+ assertFail(grade(text, mutated(E3, 'genpageEditPlan', '- **Absolute path:** D:/work/contacts-search-sort/22222222-3333-4444-5555-666666666666/page.tsx', '- **Absolute path:** D:/work/contacts-search-sort/page.tsx')),
+ /is not inside the downloaded 22222222-3333-4444-5555-666666666666\/ folder/);
+ assertFail(grade(text, mutated(E3, 'genpageEditPlan', '- **Original data sources (from config.json):** contact', '- **Original data sources (from config.json):** account')),
+ /original data sources account differ from config\.json's contact/);
+ assertSkip(grade(text, withoutArtifact(E3, 'before/prompt.txt')), /snapshot was not captured/);
+});
+
+test('eval 3: Edit Phase 5 reads the edit plan, rules, RuntimeTypes and the page; search and sort use Fluent UI V9', () => {
+ const reads = 'Edit Phase 5: Orchestrator reads genpage-edit-plan.md, rules.md, RuntimeTypes.ts, and page.tsx';
+ const ui = 'Edit Phase 5: Search implementation uses Fluent UI V9 SearchBox or Input; sort uses column header handlers';
+ assertPass(grade(reads, committed(E3)));
+ assertPass(grade(ui, committed(E3)));
+ assertFail(grade(reads, mutated(E3, 'workflowLog', 'Orchestrator read genpage-edit-plan.md, references/rules.md, RuntimeTypes.ts', 'Orchestrator read genpage-edit-plan.md, RuntimeTypes.ts')),
+ /does not record reading rules\.md/);
+ assertFail(grade(ui, withFile(E3, 'page.tsx', '<SearchBox', '<Text')), /no Fluent UI V9 SearchBox or Input is imported and rendered/);
+ assertFail(grade(ui, withFile(E3, 'page.tsx', 'onSortChange={(_, next) => setSortState(next)}', '')), /not sorted through column header handlers/);
+ // A comment naming SearchBox is not a search control.
+ assertFail(grade(ui, withFile(E3, 'page.tsx', '<SearchBox', '{/* <SearchBox /> */}<Text')), /no Fluent UI V9 SearchBox/);
+});
+
+// --- Eval 8 ------------------------------------------------------------------------------------
+
+const E8 = '8-account-metrics-new-app';
+
+test('eval 8: zero apps, the create-or-cancel question, and the plan recording the new app', () => {
+ const zero = 'Phase 1 (Planner): pac model list returns zero apps';
+ const asked = 'Phase 1 (Planner): User is asked via AskUserQuestion whether to create a new app or cancel';
+ const recorded = "Phase 1 (Planner): Plan records 'create new app' decision";
+ for (const text of [zero, asked, recorded]) assertPass(grade(text, committed(E8)));
+ assertFail(grade(zero, withEvents(E8, (ev) => { event(ev, 'app-list').result = { apps: [{ appId: '99999999-0000-4000-8000-000000000000', displayName: 'Old App' }] }; return ev; })),
+ /returned 1 app/);
+ assertFail(grade(zero, withEvents(E8, (ev) => { event(ev, 'app-list').result = {}; return ev; })), /does not record zero apps/);
+ assertFail(grade(asked, withEvents(E8, (ev) => ev.filter((e) => e.id !== 'ask-create-app'))), /no AskUserQuestion offered to create a new app or cancel/);
+ assertFail(grade(recorded, withEvents(E8, (ev) => { event(ev, 'ask-create-app').result.answer = 'Cancel'; return ev; })), /answered "Cancel", not create/);
+ assertFail(grade(recorded, mutated(E8, 'genpagePlan', '- App: create new: Account Metrics', '- App: create new: Metrics Hub')), /not the app the maker named \("Account Metrics"\)/);
+ assertFail(grade(recorded, mutated(E8, 'genpagePlan', '- App: create new: Account Metrics', '- App: Sales Hub (11111111-2222-3333-4444-555555555555)')), /does not record "App: create new/);
+});
+
+test('eval 8: the solution question runs for the new app and its choice is recorded', () => {
+ const text = 'Phase 1 (Planner): Because a new app will be created, the planner asks the solution selection question and records the choice in ## Environment';
+ assertPass(grade(text, committed(E8)));
+ assertFail(grade(text, mutated(E8, 'genpagePlan', '- Solution: ContosoCore', '- Solution: Default')), /maker answered "Continue in 'Contoso Core'/);
+ assertFail(grade(text, mutated(E8, 'genpagePlan', '- App: create new: Account Metrics', '- App: Sales Hub (1)')), /does not record a new app/);
+});
+
+test('eval 8: the app-id pac model create returned is the one every upload uses', () => {
+ const stored = 'Phase 3: The new app-id returned from pac model create is stored for Phase 6';
+ const used = 'Phase 6: Upload uses the newly created app-id';
+ assertPass(grade(stored, committed(E8)));
+ assertPass(grade(used, committed(E8)));
+ const otherApp = (ev) => { event(ev, 'upload').command = event(ev, 'upload').command.replace("--app-id '44444444-5555-4666-8777-888888888888'", "--app-id '11111111-2222-3333-4444-555555555555'"); return ev; };
+ assertFail(grade(stored, withEvents(E8, otherApp)), /used --app-id 11111111-2222-3333-4444-555555555555, not the created 44444444/);
+ assertFail(grade(used, withEvents(E8, otherApp)), /--app-id 11111111-2222-3333-4444-555555555555 is not the created app/);
+ assertFail(grade(stored, withEvents(E8, (ev) => { delete event(ev, 'app-create').result.appId; return ev; })), /recorded no returned app-id/);
+ assertFail(grade(stored, withEvents(E8, (ev) => { event(ev, 'app-create').command = "pac model create --name 'Account Metrics' --solution 'Default' --publish"; return ev; })),
+ /--solution Default is not the plan's Solution: ContosoCore/);
+ assertFail(grade(used, withEvents(E8, (ev) => { event(ev, 'upload').result.appId = '11111111-2222-3333-4444-555555555555'; return ev; })), /upload result names app 11111111/);
+});
+
+// --- Eval 9 ------------------------------------------------------------------------------------
+
+const E9 = '9-project-tracker-new-entities';
+
+test('eval 9: both tables are absent, planned with the milestone → project lookup, behind the solution question', () => {
+ const absent = 'Phase 1 (Planner): cr_project and cr_milestone confirmed as NOT existing';
+ const lookup = 'Phase 1 (Planner): Plan includes a lookup relationship (cr_milestone → cr_project)';
+ const solution = 'Phase 1 (Planner): Solution selection question is asked because new entities will be created';
+ for (const text of [absent, lookup, solution]) assertPass(grade(text, committed(E9)));
+ assertFail(grade(absent, withEvents(E9, (ev) => { event(ev, 'list-tables-search').result = 'Logical Name Display Name\ncr_project Project'; return ev; })),
+ /does not record cr_project as absent/);
+ assertFail(grade(lookup, mutated(E9, 'genpagePlan', '| 1:N lookup | project | project | RemoveLink |', '| none | none | none | none |')), /milestone has no lookup relationship to project/);
+ assertFail(grade(solution, mutated(E9, 'genpagePlan', '- Solution: ContosoProjects', '- Solution: FieldSurveys')), /maker answered "Continue in 'ContosoProjects'/);
+});
+
+test('eval 9: provision-entities.js creates both tables and the lookup from one input', () => {
+ const text = 'Phase 2b (Entity Builder): cr_project and cr_milestone entities are provisioned with lookup relationship (cr_milestone → cr_project) via provision-entities.js; dependency ordering is handled automatically';
+ assertPass(grade(text, committed(E9)));
+ const input = JSON.parse(committed(E9).artifacts['provision-input.json']);
+ assertFail(grade(text, withArtifact(E9, 'provision-input.json', JSON.stringify({ ...input, relationships: [] }))), /declares no project → milestone OneToMany relationship/);
+ assertFail(grade(text, mutated(E9, 'entityCreationLog', '| 1:N | cr_project | cr_milestone |', '| 1:N | cr_milestone | cr_project |')), /no project → milestone \(1:N\) row/);
+ assertFail(grade(text, withEvents(E9, (ev) => { event(ev, 'provision-data-model').result = { ok: false, error: 'throttled' }; return ev; })), /did not return ok:true/);
+ assertFail(grade(text, withArtifact(E9, 'provision-input.json', '{ not json')), /provision-input\.json is not JSON/);
+});
+
+test('eval 9: sample data is seeded because the prompt asked, with milestones bound to seeded projects', () => {
+ const requested = 'Phase 2b (Entity Builder): Sample data is created because the user explicitly requested it in the prompt';
+ const parents = 'Phase 2b (Entity Builder): Sample records respect relationships (milestones reference projects via $parent/match convention)';
+ assertPass(grade(requested, committed(E9)));
+ assertPass(grade(parents, committed(E9)));
+ assertFail(grade(requested, mutated(E9, 'genpagePlan', 'entities with sample data to test the page.', 'entities.')), /does not ask for sample data/);
+ assertFail(grade(requested, mutated(E9, 'workflowLog', 'for testing? → Yes, add sample data', 'for testing? → No, skip')), /answer was "No, skip/);
+ const input = JSON.parse(committed(E9).artifacts['provision-input.json']);
+ const typo = structuredClone(input);
+ typo.sampleData.cr_Milestone[0].$parent.match.cr_name = 'Contoso Website Redesing';
+ assertFail(grade(parents, withArtifact(E9, 'provision-input.json', JSON.stringify(typo))), /milestone row 1 matches no seeded project/);
+ const orphan = structuredClone(input);
+ delete orphan.sampleData.cr_Milestone[2].$parent;
+ assertFail(grade(parents, withArtifact(E9, 'provision-input.json', JSON.stringify(orphan))), /milestone row 3 has no \$parent\/match reference/);
+ assertSkip(grade(parents, withoutArtifact(E9, 'provision-input.json')), /provision-input\.json was not captured/);
+});
+
+test('eval 9: the upload binds both created tables', () => {
+ const text = 'Phase 6: Deployment includes --data-sources with both entity names';
+ assertPass(grade(text, committed(E9)));
+ assertFail(grade(text, withEvents(E9, (ev) => { event(ev, 'create').command = event(ev, 'create').command.replace("--data-sources 'cr_project,cr_milestone'", "--data-sources 'cr_project'"); return ev; })),
+ /--data-sources is cr_project, expected cr_project,cr_milestone/);
+});
+
+// --- Eval 12 -----------------------------------------------------------------------------------
+
+const E12 = '12-account-plan-revision';
+
+test('eval 12: present, request a revision, revise, re-present and approve — in that order', () => {
+ const initial = 'Phase 1 (Planner): Initial plan is presented via EnterPlanMode';
+ const request = 'Phase 1 (Planner): User requests a revision (ExitPlanMode with changes-requested response)';
+ const revise = 'Phase 1 (Planner): Planner revises the plan based on user feedback and re-enters plan mode';
+ const second = 'Phase 1 (Planner): User approves the revised plan on the second presentation';
+ for (const text of [initial, request, revise, second]) assertPass(grade(text, committed(E12)));
+ assertFail(grade(initial, mutated(E12, 'workflowLog', '- EnterPlanMode called with the initial plan:', '- Plan shown in chat:')), /precedes the first plan presentation/);
+ const approvedFirst = mutated(E12, 'workflowLog', '- ExitPlanMode called → changes requested (revised): "add a search box in addition to the filter toolbar"', '- ExitPlanMode called → approved');
+ assertFail(grade(request, approvedFirst), /not a change request/);
+ assertFail(grade(second, approvedFirst), /first presentation was not answered with a change request/);
+ assertFail(grade(request, mutated(E12, 'workflowLog', '→ changes requested (revised): "add a search box in addition to the filter toolbar"', '→ changes requested')),
+ /does not record what the maker asked for/);
+ // With the revision re-invocation gone, the only planner call left is the approval writeback, which
+ // comes after the re-presentation.
+ assertFail(grade(revise, mutated(E12, 'workflowLog', '- Task genpage-planner re-invoked with the revision request', '- Revised the plan inline with the revision request')),
+ /plan mode was re-entered before the planner revised the plan/);
+ assertFail(grade(second, mutated(E12, 'workflowLog', '- EnterPlanMode called with the revised plan (search box + filter toolbar + sortable columns)\n- ExitPlanMode called → approved',
+ '- EnterPlanMode called with the revised plan (search box + filter toolbar + sortable columns)\n- ExitPlanMode called → changes requested ("smaller header")')), /second presentation was not approved/);
+});
+
+test('eval 12: the approved and written plan carry the requested search box', () => {
+ const reflects = "Phase 1 (Planner): Revised plan reflects the user's requested changes (search box added)";
+ const written = 'Phase 1 (Planner): genpage-plan.md reflects the approved (revised) version, not the initial version';
+ assertPass(grade(reflects, committed(E12)));
+ assertPass(grade(written, committed(E12)));
+ const base = committed(E12);
+ const noSearch = base.artifacts['.approved-genpage-plan.md'].replace(/search box/gi, 'header');
+ assertFail(grade(reflects, withArtifact(E12, '.approved-genpage-plan.md', noSearch)), /approved revised plan has no search box/);
+ assertFail(grade(reflects, withArtifact(E12, '.approved-genpage-plan.md', base.artifacts['.approved-genpage-plan.md'].replace(/filter toolbar/gi, 'filters'))), /dropped the filter toolbar/);
+ // An initial-version plan: no search box anywhere.
+ assertFail(grade(written, { ...base, genpagePlan: base.genpagePlan.replace(/search box|SearchBox/gi, 'header') }), /is the initial version: it has no search box/);
+ assertFail(grade(written, mutated(E12, 'genpagePlan', '| Accounts | account-list.tsx |', '| Accounts | accounts.tsx |')), /genpage-plan\.md targets \["accounts\.tsx"\], the approved plan \["account-list\.tsx"\]/);
+ assertFail(grade(written, withEvents(E12, (ev) => { event(ev, 'plan-verify').result.ok = false; return ev; })), /verification of genpage-plan\.md did not pass/);
+});
+
+// --- Eval 14 -----------------------------------------------------------------------------------
+
+const E14 = '14-account-list-edit-collision';
+const STALE = '.genpage-provenance/genpage-plan.stale-e0fbb49f3c98.md';
+
+test('eval 14: the first plan has two pages whose shared file name the Phase 5a gate detects', () => {
+ const initial = 'Phase 1 (Planner): Plan initially contains a Pages table with 2 pages';
+ const detects = 'Phase 5a: Orchestrator reads the Pages table and detects duplicate filenames';
+ assertPass(grade(initial, committed(E14)));
+ assertPass(grade(detects, committed(E14)));
+ assertFail(grade(initial, withArtifact(E14, STALE, committed(E12).genpagePlan)), /first plan's ## Pages has 1 row\(s\), expected 2/);
+ assertFail(grade(detects, withEvents(E14, (ev) => { Object.assign(event(ev, 'page-files-1').result, { ok: true, problems: [] }); return ev; })),
+ /did not report the collision/);
+ assertFail(grade(detects, withEvents(E14, (ev) => { event(ev, 'page-files-1').result.files = ['account-list.tsx', 'account-edit.tsx']; return ev; })),
+ /the gate read account-list\.tsx,account-edit\.tsx, but the plan's Pages table lists account\.tsx,account\.tsx/);
+ assertFail(grade(detects, withEvents(E14, (ev) => {
+ const i = ev.findIndex((e) => e.id === 'page-files-1');
+ return [...ev.slice(0, i), { id: 'early-stamp', command: 'node scripts\\genpage-worker-output.js --stamp --file account.tsx', result: { ok: true, existed: false } }, ...ev.slice(i)];
+ })), /page dispatch started before the page-file gate ran/);
+});
+
+test('eval 14: the refused plan is re-planned and re-approved, never renamed in place, before dispatch', () => {
+ const text = "Phase 5a: check-page-files.js refuses the colliding plan and the orchestrator halts and re-plans through the planner (it never renames files itself), so genpage-plan.md carries unique, re-approved filenames (e.g., account-list.tsx, account-edit.tsx) before any builder is dispatched";
+ assertPass(grade(text, committed(E14)));
+ const insertAfterRefusal = (entry) => withEvents(E14, (ev) => {
+ const i = ev.findIndex((e) => e.id === 'page-files-1') + 1;
+ return [...ev.slice(0, i), entry, ...ev.slice(i)];
+ });
+ assertFail(grade(text, insertAfterRefusal({ id: 'stamp', command: 'node scripts\\genpage-worker-output.js --stamp --file account.tsx', result: { ok: true, existed: false } })),
+ /ran after the refusal, before a passing re-plan/);
+ assertFail(grade(text, insertAfterRefusal({ id: 'rename', command: 'Edit genpage-plan.md (rename the second account.tsx to account-edit.tsx)' })),
+ /orchestrator edited genpage-plan\.md itself/);
+ assertFail(grade(text, withEvents(E14, (ev) => { event(ev, 'plan-prepare-2').result.quarantinedPath = null; return ev; })), /was not quarantined/);
+ assertFail(grade(text, withEvents(E14, (ev) => { event(ev, 'page-files-2').result.ok = false; return ev; })), /no later check-page-files\.js run passed/);
+ assertFail(grade(text, mutated(E14, 'workflowLog', '- Task genpage-planner re-invoked with the check-page-files problem', '- Renamed the files in the plan')),
+ /were not re-planned by genpage-planner and re-approved/);
+ assertFail(grade(text, withArtifact(E14, '.approved-genpage-plan.md', committed(E14).artifacts['.approved-genpage-plan.md'].replace('account-edit.tsx', 'account-detail.tsx'))),
+ /are not the re-approved/);
+});
+
+test('eval 14: two parallel builders write two distinct, intact pages that deploy separately', () => {
+ const parallel = 'Phase 5c: Two page-builders are invoked in parallel with distinct target filenames';
+ const intact = "Phase 5c: No builder overwrites another builder's output (both .tsx files exist after Phase 5)";
+ const deployed = 'Phase 6: Both pages are deployed with their distinct filenames';
+ for (const text of [parallel, intact, deployed]) assertPass(grade(text, committed(E14)));
+ // Adjacent dispatches ARE the parallel evidence; a log that never says "single message" or
+ // "in parallel" (a correct run need not) must still pass.
+ const plainLog = committed(E14).workflowLog.replace(/single message|in parallel|\(parallel\)/gi, 'together');
+ assert.doesNotMatch(plainLog, /single message|in parallel/i);
+ assertPass(grade(parallel, { ...committed(E14), workflowLog: plainLog }));
+ assertFail(grade(parallel, withEvents(E14, (ev) => { event(ev, 'builder-edit').command = 'Task genpage-page-builder: Edit Account, target file account-list.tsx'; return ev; })),
+ /both page-builders target account-list\.tsx/);
+ assertFail(grade(parallel, withEvents(E14, (ev) => {
+ const i = ev.findIndex((e) => e.id === 'builder-edit');
+ return [...ev.slice(0, i), { id: 'gate-list-early', command: 'node scripts\\genpage-worker-output.js --file account-list.tsx', result: { ok: true, problems: [] } }, ...ev.slice(i)];
+ })), /were not dispatched together/);
+ const base = committed(E14);
+ const list = base.files.find((f) => f.name === 'account-list.tsx');
+ assertFail(grade(intact, { ...base, files: base.files.map((f) => (f.name === 'account-edit.tsx' ? { ...f, content: list.content } : f)) }), /identical content/);
+ assertFail(grade(intact, { ...base, files: base.files.filter((f) => f.name !== 'account-edit.tsx') }), /account-edit\.tsx does not exist after Phase 5/);
+ assertFail(grade(intact, withEvents(E14, (ev) => { event(ev, 'stamp-edit').result.existed = true; return ev; })), /account-edit\.tsx was not stamped as a fresh target/);
+ assertFail(grade(deployed, withEvents(E14, (ev) => { event(ev, 'edit-create').command = event(ev, 'edit-create').command.replace('--code-file before\\account-edit.tsx', '--code-file before\\account-list.tsx'); return ev; })),
+ /account-list\.tsx has 2 create upload/);
+ assertFail(grade(deployed, withEvents(E14, (ev) => { event(ev, 'edit-create').result.pageId = event(ev, 'list-create').result.pageId; return ev; })),
+ /two create uploads returned the same page id/);
+});
+
+// --- Eval 16 -----------------------------------------------------------------------------------
+
+const E16 = '16-account-list';
+
+test('eval 16: the written plan conforms to plan-schema.md section by section', () => {
+ const conforms = 'Phase 1 (Planner): genpage-plan.md is written and conforms to references/plan-schema.md';
+ const headings = 'Phase 1 (Planner): genpage-plan.md contains ALL required sections with exact headings: # Genpage Plan, ## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications';
+ const table = 'Phase 1 (Planner): ## Pages table has at least one row with columns Page, File, Purpose, Entities';
+ const specs = 'Phase 1 (Planner): ## Per-Page Specifications has one ### <Page Name> subsection for each row in ## Pages';
+ const unique = 'Phase 1 (Planner): File names in ## Pages are unique';
+ for (const text of [conforms, headings, table, specs, unique]) assertPass(grade(text, committed(E16)));
+ assertFail(grade(conforms, mutated(E16, 'genpagePlan', '## Relevant Samples', '## Samples')), /missing required section "## Relevant Samples"/);
+ assertFail(grade(conforms, withEvents(E16, (ev) => { event(ev, 'plan-verify').result.targets = ['other.tsx']; return ev; })), /verified targets other\.tsx are not this plan's files/);
+ assertFail(grade(conforms, withEvents(E16, (ev) => ev.filter((e) => e.id !== 'plan-verify'))), /was not provenance-verified/);
+ assertFail(grade(headings, mutated(E16, 'genpagePlan', '## Pages\n', '## Page List\n')), /missing exact heading "## Pages"/);
+ assertFail(grade(headings, mutated(E16, 'genpagePlan', '# Genpage Plan\n', '# Plan\n')), /missing exact heading "# Genpage Plan"/);
+ assertFail(grade(table, mutated(E16, 'genpagePlan', '| Account List | account-list.tsx | Simple sortable list of Account records with click-to-open | account |', '| Account List | account-list.tsx | | account |')),
+ /row "Account List" has an empty cell/);
+ assertFail(grade(specs, mutated(E16, 'genpagePlan', '### Account List', '### Accounts')), /no "### Account List" subsection/);
+ const twoRows = mutated(E16, 'genpagePlan', '| Account List | account-list.tsx | Simple sortable list of Account records with click-to-open | account |',
+ '| Account List | account-list.tsx | Simple sortable list of Account records with click-to-open | account |\n| Account Grid | Account-List.tsx | Grid | account |');
+ assertFail(grade(unique, twoRows), /file names collide/);
+});
+
+test('eval 16: account exists, so the plan uses the no-creation sentence and lists account for RuntimeTypes', () => {
+ const sentinel = "Phase 1 (Planner): Because the account entity exists, ## Entity Creation Required contains the literal string 'No entity creation required — all entities already exist.'";
+ const existing = 'Phase 1 (Planner): ## Existing Entities contains the entity logical name used for RuntimeTypes generation (account)';
+ assertPass(grade(sentinel, committed(E16)));
+ assertPass(grade(existing, committed(E16)));
+ assertFail(grade(sentinel, mutated(E16, 'genpagePlan', 'No entity creation required — all entities already exist.', 'No entity creation needed.')), /exact no-entity sentence/);
+ assertFail(grade(sentinel, withEvents(E16, (ev) => { event(ev, 'list-tables').command = "pac model list-tables --search 'contact'"; return ev; })), /no pac model list-tables --search covered account/);
+ assertFail(grade(existing, mutated(E16, 'genpagePlan', '## Existing Entities\naccount', '## Existing Entities\ncontact')), /lists contact, not account/);
+ assertFail(grade(existing, withEvents(E16, (ev) => { event(ev, 'generate-types').command = "pac model genpage generate-types --data-sources 'account,contact' --output-file 'RuntimeTypes.ts'"; return ev; })),
+ /generate-types used contact, which ## Existing Entities does not list/);
+});
diff --git a/evals/model-apps/routing/EVAL_GUIDE.md b/evals/model-apps/routing/EVAL_GUIDE.md
new file mode 100644
index 000000000..98fcb2cd7
--- /dev/null
+++ b/evals/model-apps/routing/EVAL_GUIDE.md
@@ -0,0 +1,140 @@
+# Routing Eval — model-apps skill selection
+
+Grades the decision an agent makes **before** any skill runs: given a user prompt and the plugin's
+skill descriptions, does it pick the right model-apps skill — or correctly pick none?
+
+The offline harnesses next door grade the *artifacts* a run produced (`../genpage/` grades
+workflow logs, plans and `.tsx`; `../app-builder/` grades App Spec stage facts). Neither can see a
+mis-route, and the two skill descriptions point at each other (`/genpage` → "use /app-builder
+instead" and back), so a wording change to one can silently start stealing the other's prompts.
+
+## What a case looks like
+
+`evals.json`:
+
+```json
+{
+ "id": 4,
+ "tier": "smoke",
+ "prompt": "I need a Dataverse app for inventory with products, warehouses and stock levels, plus a dashboard overview page.",
+ "expect": "app-builder",
+ "trap": "the word \"page\" pulling a whole-app request into /genpage"
+}
+```
+
+| Field | Meaning |
+|-------|---------|
+| `expect` | The model-apps skill the agent must invoke **first** — `genpage`, `app-builder`, `report-issue`, `telemetry` — or `null` for "none of them" (a negative / bleed case) |
+| `accept` | Optional other outcomes that are also correct, for a genuinely ambiguous prompt. `null` is never implied: "ambiguous" does not mean "anything goes" |
+| `trap` | Optional. The mis-route the case exists to catch; printed when the case fails |
+| `tier` | `smoke` / `full` / `stress`, as in the other suites |
+
+The 20 committed cases cover: positives for every skill; the `/genpage` ↔ `/app-builder` boundary
+from both sides ("add a page to my existing app" vs "an app … plus a dashboard page", "add a
+**table** to my existing app"); and negatives that share vocabulary with the plugin — Power Pages,
+canvas/Power Fx, Power Automate, a generic React dashboard, and a pure knowledge question.
+
+## How a trial runs
+
+`run-routing.js` launches a real agent CLI headlessly, once per trial:
+
+- **Isolated.** cwd is a fresh empty temp dir (no repo `AGENTS.md` can steer the model); only this
+ plugin is loaded via `--plugin-dir`; the user's own plugins/skills are excluded (Claude:
+ `--restricted`, which also confines the file tools to that empty cwd; Copilot: a throwaway
+ `COPILOT_HOME`); MCP servers are off. One residual gap: a user-level `~/.claude/CLAUDE.md` still
+ loads for Claude — `--safe-mode` would skip it but also drops the plugin's own skills — and CI
+ runners have none.
+- **Read-only.** The tool set is cut to "invoke a skill + read files". The trade-off is that a real
+ session offers more tools, so the model sees a slightly smaller menu.
+- **Stopped at the decision.** The JSONL transcript is parsed as it streams, and the agent is killed
+ the moment it invokes a model-apps skill, so a positive trial costs about one model turn.
+- **Guarded.** Every trial proves the plugin's skills were loaded before its outcome counts; if they
+ were not, the trial is a harness **error**, not a passing "none". Claude reports its loaded
+ skills in the transcript's init event. Copilot's transcript does not, so each Copilot trial first
+ runs `copilot --plugin-dir <dir> skill list --json` with the trial's own isolated `COPILOT_HOME`.
+ That fails the trial, before any model call, if a plugin skill is missing or any non-builtin skill
+ from outside the plugin is present (an isolation leak). A CLI that exits non-zero or reports a
+ failed result before deciding (not signed in, not installed, crashed), or a run cut off by
+ `--timeout` before choosing a skill, is also an error. Only a run that **finishes successfully**
+ without invoking a model-apps skill counts as "none".
+
+Every flag is in `lib/agents.js`; every transcript shape the parser understands is documented in
+`lib/transcript.js`.
+
+## Grading
+
+Routing is not deterministic, so each case runs `--runs` trials (default 3) and passes when its
+successes over the **non-error** trials reach `--threshold`, compared strictly (default `2/3`, i.e.
+2 of 3; pass a decimal such as `0.8` or a fraction such as `3/4`). Prefer a fraction to a rounded
+decimal: `0.67` is stricter than `2/3`, so 2 of 3 fails it. A case whose every trial errored is a
+harness error.
+
+Exit codes: `0` every case met the threshold · `1` a case failed · `2` harness error.
+
+```
+TAP version 13
+# agent claude · model sonnet · runs 2 · threshold 2/3
+1..20
+ok 1 - #1 [smoke] expect genpage — 2/2 (genpage×2)
+not ok 4 - #4 [smoke] expect app-builder — 1/2 (app-builder×1, genpage×1)
+ ---
+ prompt: "I need a Dataverse app for inventory ..."
+ trap: "the word \"page\" pulling a whole-app request into /genpage"
+ ...
+# cases 20 (pass 19, fail 1, error 0)
+# trials 40 (errors 0)
+# cost >= $0.48 (killed trials do not report cost)
+```
+
+## Running it
+
+From the repo root. You must be signed in to the agent CLI you choose.
+
+```bash
+# See exactly what would be launched; launches nothing
+node evals/model-apps/routing/run-routing.js --dry-run
+
+# Smoke tier, one trial each (quick local check after editing a SKILL.md description)
+node evals/model-apps/routing/run-routing.js --tier smoke --runs 1
+
+# Full suite on Copilot CLI with a specific model, saving results for later comparison
+node evals/model-apps/routing/run-routing.js --agent copilot --model claude-sonnet-5.5 --out before.json
+
+# ...edit a description, then compare: prints `# delta #<id>: <old> → <new>` for every case that moved
+node evals/model-apps/routing/run-routing.js --agent copilot --model claude-sonnet-5.5 --out after.json --compare before.json
+```
+
+`--out` records each skill's description fingerprint, so two result files show whether the
+descriptions changed between them. `--transcripts <dir>` saves raw JSONL per trial for debugging —
+keep those local; they can contain local paths and model output.
+
+Measured when the suite was added: all 20 cases passed 2/2 on both Claude Code (`--model sonnet`)
+and Copilot CLI (`--model claude-sonnet-5.5`), ~5–15 s per trial. The suite is therefore a
+**regression guard** for the descriptions, not a known-failing backlog — and since every case is
+currently easy for these models, harder boundary prompts are the most useful additions.
+
+## Cadence
+
+Not part of the per-PR gate: it costs model usage and is non-deterministic.
+`.github/workflows/model-apps-agent-evals.yml` runs it on a same-repo PR labelled
+**`run-agent-evals`** (use the label on any PR that edits a skill `description:`; re-apply it to
+re-run after new commits), **weekly**, and **on demand**. It is report-only, not a required check.
+
+**No secret to provision.** The default agent is Copilot CLI, which authenticates with the
+workflow's built-in `GITHUB_TOKEN` because the job holds `copilot-requests: write`; usage is billed
+to the organization (the *Allow use of Copilot CLI billed to the organization* Copilot policy must
+be on — it is by default when Copilot CLI is enabled). See [Using Copilot CLI in GitHub Actions with
+GITHUB_TOKEN](https://docs.github.com/copilot/how-tos/copilot-cli/use-copilot-cli-in-actions).
+`agent=claude` (dispatch only) needs an `ANTHROPIC_API_KEY` secret and clean-skips without it. The
+job uploads only the results JSON, never transcripts.
+
+The runner's own logic (parsing, grading, process handling against a fake agent) **is** unit-tested
+on every PR: `node --test evals/model-apps/routing/tests/*.test.js`.
+
+## Adding a case
+
+1. Append to `evals.json` with the next id. Prefer prompts a real user would type, and give every
+ negative or boundary case a `trap`.
+2. `node evals/model-apps/routing/run-routing.js --eval <id> --runs 3` — a new case should pass at
+ least 2/3 on the current descriptions, or it documents a routing bug worth fixing first.
+3. `node --test evals/model-apps/routing/tests/*.test.js` validates the file's shape.
diff --git a/evals/model-apps/routing/evals.json b/evals/model-apps/routing/evals.json
new file mode 100644
index 000000000..67cedaf9f
--- /dev/null
+++ b/evals/model-apps/routing/evals.json
@@ -0,0 +1,139 @@
+{
+ "skill_name": "model-apps-routing",
+ "eval_instructions": "Each case is one user prompt sent to a headless agent with only the model-apps plugin loaded. `expect` is the model-apps skill the agent must invoke FIRST (genpage | app-builder | report-issue | telemetry), or null when it must invoke none of them. `accept` lists other outcomes that are also correct for a genuinely ambiguous prompt. `trap` names the mis-route the case exists to catch. Graded by run-routing.js over N trials against a pass-rate threshold.",
+ "evals": [
+ {
+ "id": 1,
+ "tier": "smoke",
+ "prompt": "Add a generative page to my existing Sales Hub model-driven app that shows accounts as a gallery of cards.",
+ "expect": "genpage"
+ },
+ {
+ "id": 2,
+ "tier": "smoke",
+ "prompt": "Build me a model-driven app to manage equipment rentals: customers, rentals, and returns.",
+ "expect": "app-builder"
+ },
+ {
+ "id": 3,
+ "tier": "smoke",
+ "prompt": "Build a Power Pages site where customers can submit warranty claims.",
+ "expect": null,
+ "trap": "\"build a site/page\" wording bleeding into /genpage; Power Pages is a different product"
+ },
+ {
+ "id": 4,
+ "tier": "smoke",
+ "prompt": "I need a Dataverse app for inventory with products, warehouses and stock levels, plus a dashboard overview page.",
+ "expect": "app-builder",
+ "trap": "the word \"page\" pulling a whole-app request into /genpage"
+ },
+ {
+ "id": 5,
+ "tier": "full",
+ "prompt": "Edit the dashboard genpage in my Field Service app so the revenue chart is a donut instead of bars.",
+ "expect": "genpage"
+ },
+ {
+ "id": 6,
+ "tier": "full",
+ "prompt": "Create a genux page in my Operations Hub app that lists open cases with a filter toolbar and sortable columns.",
+ "expect": "genpage"
+ },
+ {
+ "id": 7,
+ "tier": "full",
+ "prompt": "My Contoso Recruiting model-driven app already exists. Add a page to it that shows candidates as a kanban board grouped by stage.",
+ "expect": "genpage",
+ "trap": "\"recruiting app\" read as a request to build an app"
+ },
+ {
+ "id": 8,
+ "tier": "full",
+ "prompt": "Create a model-driven app for tracking IT support tickets, with separate access for support agents and support leads.",
+ "expect": "app-builder"
+ },
+ {
+ "id": 9,
+ "tier": "full",
+ "prompt": "Make me an app to manage volunteer shifts for our nonprofit, with tables, forms and views.",
+ "expect": "app-builder"
+ },
+ {
+ "id": 10,
+ "tier": "full",
+ "prompt": "Add a business process flow to my Case Management model-driven app that walks a case through Triage, Investigate and Resolve.",
+ "expect": "app-builder",
+ "trap": "\"add ... to my existing app\" read as a /genpage edit"
+ },
+ {
+ "id": 11,
+ "tier": "full",
+ "prompt": "Download my deployed Asset Tracker model-driven app and add a Warranty table related to Asset.",
+ "expect": "app-builder",
+ "trap": "\"download my app\" read as the /genpage edit flow, which downloads pages"
+ },
+ {
+ "id": 12,
+ "tier": "full",
+ "prompt": "Write a Power Fx formula for a canvas app button that filters a gallery by the selected dropdown value.",
+ "expect": null,
+ "trap": "Power Apps wording bleeding into model-apps; canvas apps are a different plugin"
+ },
+ {
+ "id": 13,
+ "tier": "full",
+ "prompt": "Explain the difference between a canvas app and a model-driven app.",
+ "expect": null,
+ "trap": "a knowledge question triggering a build skill"
+ },
+ {
+ "id": 14,
+ "tier": "full",
+ "prompt": "Create a Power Automate cloud flow that emails me whenever a new account is created in Dataverse.",
+ "expect": null
+ },
+ {
+ "id": 15,
+ "tier": "full",
+ "prompt": "Build a React + Vite web app with a dashboard of sales charts that I can host on Azure Static Web Apps.",
+ "expect": null,
+ "trap": "\"React dashboard page\" bleeding into /genpage, which generates React pages for model-driven apps only"
+ },
+ {
+ "id": 16,
+ "tier": "stress",
+ "prompt": "Report a bug: the genpage skill crashed while uploading my page with pac.",
+ "expect": "report-issue",
+ "trap": "the skill name in a bug report invoking /genpage itself"
+ },
+ {
+ "id": 17,
+ "tier": "stress",
+ "prompt": "Turn off usage telemetry for the model apps plugin.",
+ "expect": "telemetry"
+ },
+ {
+ "id": 18,
+ "tier": "stress",
+ "prompt": "Add an overview page to the model-driven app I want to build for fleet maintenance: vehicles, service records and mechanics.",
+ "expect": "app-builder",
+ "trap": "\"add an overview page\" sent to /genpage although the app does not exist yet"
+ },
+ {
+ "id": 19,
+ "tier": "stress",
+ "prompt": "In my existing Asset Tracker model-driven app, add a Warranty table with a lookup to Asset and show it on the Asset form.",
+ "expect": "app-builder",
+ "trap": "an edit to an existing app's DATA MODEL routed to /genpage, which only builds pages"
+ },
+ {
+ "id": 20,
+ "tier": "stress",
+ "prompt": "Create a page for my existing model-driven app that tracks project milestones. I'll also need a new Milestone table for it.",
+ "expect": "genpage",
+ "accept": ["app-builder"],
+ "trap": "genuinely ambiguous: /genpage can create the table it needs, and /app-builder can edit the app; either is acceptable, NEITHER is not"
+ }
+ ]
+}
diff --git a/evals/model-apps/routing/lib/agents.js b/evals/model-apps/routing/lib/agents.js
new file mode 100644
index 000000000..93dbf7bbd
--- /dev/null
+++ b/evals/model-apps/routing/lib/agents.js
@@ -0,0 +1,81 @@
+'use strict';
+
+// How each supported agent CLI is launched for ONE routing trial. Kept apart from the runner so
+// the exact flags are unit-tested and reviewed in one place: they decide what the eval measures.
+//
+// The trial must observe ROUTING, not the user's machine, so every invocation is isolated:
+// * cwd is a fresh empty temp dir — no repo AGENTS.md/CLAUDE.md can steer the model;
+// * only the plugin under test is loaded (`--plugin-dir`); the user's installed plugins and
+// skills are excluded (Claude: `--restricted`, which ignores user/project/local settings —
+// where installed plugins are enabled — and confines Read/Glob/Grep to the empty cwd so the
+// model cannot read the user's files; Copilot: a throwaway COPILOT_HOME, which is where
+// installed plugins and user skills live). NOT `--safe-mode`: it was measured to drop the
+// --plugin-dir plugin's skills too, which would make every trial a harness error. Residual
+// gap: a user-level ~/.claude/CLAUDE.md still loads for Claude — no flag skips it without
+// also dropping plugin skills; CI runners have none;
+// * MCP servers are off — the plugin's own Playwright server would otherwise launch a browser
+// per trial for nothing;
+// * the tool set is cut to "invoke a skill + read-only file tools". Routing happens before any
+// tool that could change anything, and the runner kills the agent as soon as a plugin skill
+// is chosen; the allowlist is what keeps a run that never routes from doing anything either.
+// The trade-off: a real session has more tools, so the model sees a slightly different menu.
+//
+// The prompt is sent on STDIN, never argv: on Windows the CLIs are `.cmd` shims that must be
+// spawned through cmd.exe, where quoting an arbitrary natural-language prompt is unsafe.
+
+const TELEMETRY_OPTOUT = 'POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT';
+
+/**
+ * @param {'claude'|'copilot'} agent
+ * @param {{pluginDir: string, model?: string|null, maxTurns?: number, copilotHome?: string}} o
+ * @returns {{bin: string, args: string[], env: Record<string,string>}}
+ */
+function buildInvocation(agent, { pluginDir, model = null, maxTurns = 4, copilotHome } = {}) {
+ // CI and evals are not real usage: never let a hook a trial triggers transmit telemetry.
+ const env = { [TELEMETRY_OPTOUT]: '1' };
+ if (agent === 'claude') {
+ const args = [
+ '-p',
+ '--plugin-dir', pluginDir,
+ '--restricted',
+ '--strict-mcp-config',
+ '--tools', 'Skill,Read,Glob,Grep',
+ '--output-format', 'stream-json',
+ '--verbose', // required by Claude Code for stream-json in print mode
+ '--no-session-persistence',
+ '--max-turns', String(maxTurns),
+ ];
+ if (model) args.push('--model', model);
+ return { bin: 'claude', args, env };
+ }
+ if (agent === 'copilot') {
+ if (!copilotHome) throw new Error('copilot trials need an isolated copilotHome');
+ env.COPILOT_HOME = copilotHome;
+ const args = [
+ '--plugin-dir', pluginDir,
+ '--output-format', 'json',
+ '--no-custom-instructions',
+ '--no-ask-user',
+ '--no-auto-update',
+ '--disable-builtin-mcps',
+ '--disable-mcp-server', 'playwright',
+ ];
+ if (model) args.push('--model', model);
+ // Variadic flag LAST, so it cannot swallow a following option.
+ args.push('--available-tools', 'skill', 'view', 'glob', 'grep');
+ return { bin: 'copilot', args, env };
+ }
+ throw new Error(`unknown agent ${JSON.stringify(agent)}`);
+}
+
+/**
+ * Quote one argument for cmd.exe (used only on Windows, where `.cmd` shims require a shell).
+ * Our arguments are flags, tool names and file-system paths — never the prompt (stdin) — so
+ * wrapping anything with spaces or cmd metacharacters in double quotes is sufficient.
+ */
+function quoteForCmd(arg) {
+ const s = String(arg);
+ return /[\s"&|<>^()%!,;]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+}
+
+module.exports = { buildInvocation, quoteForCmd, TELEMETRY_OPTOUT };
diff --git a/evals/model-apps/routing/lib/grade.js b/evals/model-apps/routing/lib/grade.js
new file mode 100644
index 000000000..000b02757
--- /dev/null
+++ b/evals/model-apps/routing/lib/grade.js
@@ -0,0 +1,103 @@
+'use strict';
+
+// Pure grading for routing evals. No I/O, so every rule here is unit-tested directly.
+//
+// An eval case:
+// { "id": 1, "tier": "smoke", "prompt": "…", "expect": "genpage" | "app-builder" | null,
+// "accept": ["app-builder"], ← optional: other outcomes that are also correct
+// "trap": "…" } ← optional: the mis-route this case guards against
+// `expect: null` means "no skill of the plugin under test" (a negative / bleed-detection case).
+//
+// A trial (one headless agent run) reports `routedTo` — the first plugin skill invoked, or null.
+//
+// Model routing is not deterministic, so a case runs N trials and passes when its pass RATE
+// reaches the threshold. A trial that errored (spawn failure, plugin not loaded, crash before any
+// decision) is EXCLUDED from the rate rather than counted as a fail — a broken harness must read
+// as a harness error, never as "the description is bad".
+
+const NONE = 'none';
+// Only absorbs binary floating-point error in `threshold * trials` (0.7 * 10 = 7.000000000000001);
+// it never lowers a requirement by a whole trial. The default "2 of 3" is the exact fraction 2/3
+// rather than a rounded 0.67, so no tolerance is needed to make it mean what it says.
+const FLOAT_EPSILON = 1e-9;
+
+function outcomeLabel(routedTo) {
+ return routedTo == null ? NONE : routedTo;
+}
+
+/** Acceptable outcome labels for a case (`none` stands for "no plugin skill"). */
+function acceptable(evalCase) {
+ const list = [evalCase.expect, ...(evalCase.accept || [])];
+ return [...new Set(list.map(outcomeLabel))];
+}
+
+/**
+ * @param {object} evalCase
+ * @param {{routedTo: string|null, error?: string, timedOut?: boolean}} trial
+ * @returns {{status: 'pass'|'fail'|'error', outcome?: string, reason: string}}
+ */
+function gradeTrial(evalCase, trial) {
+ // A trial that timed out before routing arrives here with `error` set (run-routing.js): an
+ // unfinished run has not decided "none", so it is excluded rather than graded.
+ if (trial.error) return { status: 'error', reason: trial.error };
+ const outcome = outcomeLabel(trial.routedTo);
+ const ok = acceptable(evalCase).includes(outcome);
+ return {
+ status: ok ? 'pass' : 'fail',
+ outcome,
+ reason: ok ? `routed to ${outcome}` : `routed to ${outcome}, expected ${acceptable(evalCase).join(' | ')}`,
+ };
+}
+
+/**
+ * @param {object} evalCase
+ * @param {Array} trials
+ * @param {number} threshold - 0..1, minimum pass rate over the non-error trials.
+ */
+function summarizeCase(evalCase, trials, threshold) {
+ const graded = trials.map((t) => gradeTrial(evalCase, t));
+ const valid = graded.filter((g) => g.status !== 'error');
+ const passes = valid.filter((g) => g.status === 'pass').length;
+ const outcomes = {};
+ for (const g of valid) outcomes[g.outcome] = (outcomes[g.outcome] || 0) + 1;
+ const errors = graded.filter((g) => g.status === 'error').map((g) => g.reason);
+ if (!valid.length) {
+ return { status: 'error', passes: 0, valid: 0, runs: trials.length, rate: null, outcomes, errors, graded };
+ }
+ const rate = passes / valid.length;
+ return {
+ // Compare successes against the required COUNT, strictly: a threshold of 0.01 still needs one
+ // success, and a threshold of 1 needs every valid trial.
+ status: passes + FLOAT_EPSILON >= threshold * valid.length ? 'pass' : 'fail',
+ passes,
+ valid: valid.length,
+ runs: trials.length,
+ rate,
+ outcomes,
+ errors,
+ graded,
+ };
+}
+
+/** Validate evals.json up front so a typo is a harness error, not a mystery failure. */
+function validateEvals(data, pluginSkills) {
+ const errs = [];
+ if (!data || !Array.isArray(data.evals)) return ['evals.json must have an "evals" array'];
+ const ids = new Set();
+ const allowed = new Set([...pluginSkills, null]);
+ for (const e of data.evals) {
+ const where = `eval ${JSON.stringify(e && e.id)}`;
+ if (!Number.isInteger(e.id) || e.id < 0) errs.push(`${where}: id must be a non-negative integer`);
+ else if (ids.has(e.id)) errs.push(`${where}: duplicate id`);
+ ids.add(e.id);
+ if (typeof e.prompt !== 'string' || !e.prompt.trim()) errs.push(`${where}: prompt must be a non-empty string`);
+ if (!('expect' in e)) errs.push(`${where}: "expect" is required (a skill name, or null for "no plugin skill")`);
+ else if (!allowed.has(e.expect)) errs.push(`${where}: expect ${JSON.stringify(e.expect)} is not a plugin skill (${pluginSkills.join(', ')}) or null`);
+ for (const a of e.accept || []) {
+ if (!allowed.has(a)) errs.push(`${where}: accept ${JSON.stringify(a)} is not a plugin skill or null`);
+ }
+ }
+ return errs;
+}
+
+module.exports = { gradeTrial, summarizeCase, validateEvals, acceptable, outcomeLabel, NONE };
diff --git a/evals/model-apps/routing/lib/transcript.js b/evals/model-apps/routing/lib/transcript.js
new file mode 100644
index 000000000..55ef75184
--- /dev/null
+++ b/evals/model-apps/routing/lib/transcript.js
@@ -0,0 +1,139 @@
+'use strict';
+
+// Incremental parser for a headless agent transcript — the ONE place that knows each CLI's
+// JSONL event shapes. The routing runner feeds it stdout line by line and stops the agent as
+// soon as `decided` is true, so a trial costs one model turn rather than a whole skill run.
+//
+// Claude Code (`claude -p --output-format stream-json --verbose`), one JSON object per line:
+// {"type":"system","subtype":"init","skills":["model-apps:genpage","design",...],"plugins":[...]}
+// {"type":"assistant","message":{"content":[
+// {"type":"text","text":"..."},
+// {"type":"tool_use","id":"toolu_…","name":"Skill","input":{"skill":"model-apps:genpage","args":"…"}}]}}
+// {"type":"result","subtype":"success","num_turns":3,"total_cost_usd":0.064}
+// Plugin skills are namespaced `<plugin>:<skill>`; built-in skills are bare (`design`).
+//
+// GitHub Copilot CLI (`copilot -p … --output-format json`), one JSON object per line:
+// {"type":"assistant.message","data":{"toolRequests":[
+// {"toolCallId":"toolu_…","name":"skill","arguments":{"skill":"genpage"}}],"content":""}}
+// {"type":"tool.execution_start","data":{"toolCallId":"toolu_…","toolName":"skill","arguments":{"skill":"genpage"}}}
+// {"type":"assistant.message_delta","data":{"deltaContent":"…"}} ← streamed text, ignored
+// {"type":"result","exitCode":0,"usage":{"premiumRequests":1,…}}
+// Skill names are NOT namespaced. `assistant.message` is the earliest COMPLETE tool request;
+// `tool.execution_start` repeats it, so calls are de-duplicated by toolCallId.
+//
+// Non-JSON lines (CLI banners, warnings on stderr merged into stdout) are ignored rather than
+// treated as errors: a transcript is evidence, and one noisy line must not void a trial.
+
+const AGENTS = ['claude', 'copilot'];
+
+class TranscriptParser {
+ /**
+ * @param {'claude'|'copilot'} agent
+ * @param {{pluginName: string, pluginSkills: string[]}} plugin - the plugin under test. A skill
+ * counts as a ROUTING DECISION only when it belongs to this plugin; a built-in skill (Claude's
+ * `design`, say) is recorded but does not end the trial, because the model may still route.
+ */
+ constructor(agent, { pluginName, pluginSkills }) {
+ if (!AGENTS.includes(agent)) throw new Error(`unknown agent ${JSON.stringify(agent)} (expected ${AGENTS.join('|')})`);
+ this.agent = agent;
+ this.pluginName = pluginName;
+ this.pluginSkills = new Set(pluginSkills);
+ this.skillCalls = []; // every skill invocation, in order: { raw, name, ofPlugin }
+ this.loadedSkills = null; // Claude only: the init event's skill list (isolation evidence)
+ this.text = ''; // final assistant text (best-effort; for diagnostics only)
+ this.result = null; // the terminal `result` event, when the run got that far
+ this.eventCount = 0; // JSON events accepted — 0 means the agent never really ran
+ this._seen = new Set();
+ }
+
+ /** First skill of the plugin under test, normalized (`genpage`), or null. */
+ get routedTo() {
+ const hit = this.skillCalls.find((c) => c.ofPlugin);
+ return hit ? hit.name : null;
+ }
+
+ /** True once the trial's outcome cannot change: a plugin skill was chosen, or the run ended. */
+ get decided() {
+ return this.routedTo !== null || this.result !== null;
+ }
+
+ /**
+ * Why the terminal `result` says the run FAILED, or null. A failed run that chose no plugin
+ * skill has not decided "none" — it never got to decide — so the runner turns this into a trial
+ * error instead of grading it (graded, it would pass every negative case).
+ * Claude: {"type":"result","subtype":"error_during_execution","is_error":true,...}
+ * (success is subtype "success" with is_error false; other subtypes include
+ * "error_max_turns")
+ * Copilot: {"type":"result","exitCode":1,...}
+ */
+ get resultError() {
+ const r = this.result;
+ if (!r) return null;
+ if (this.agent === 'claude') {
+ if (r.subtype !== 'success' || r.isError) return `claude result ${r.subtype || 'error'}${r.isError ? ' (is_error)' : ''}`;
+ return null;
+ }
+ return typeof r.exitCode === 'number' && r.exitCode !== 0 ? `copilot result exitCode ${r.exitCode}` : null;
+ }
+
+ push(line) {
+ const s = String(line).trim();
+ if (!s.startsWith('{')) return;
+ let ev;
+ try { ev = JSON.parse(s); } catch { return; }
+ if (!ev || typeof ev !== 'object') return;
+ this.eventCount += 1;
+ if (this.agent === 'claude') this._claude(ev);
+ else this._copilot(ev);
+ }
+
+ _skill(id, rawName) {
+ if (typeof rawName !== 'string' || !rawName) return;
+ if (id) {
+ if (this._seen.has(id)) return;
+ this._seen.add(id);
+ }
+ // `model-apps:genpage` → plugin skill `genpage`; a bare name is the plugin's only when the
+ // plugin actually ships a skill by that name (Copilot does not namespace).
+ const m = rawName.match(/^([^:]+):(.+)$/);
+ const name = m ? m[2] : rawName;
+ const ofPlugin = m ? m[1] === this.pluginName && this.pluginSkills.has(name) : this.pluginSkills.has(name);
+ this.skillCalls.push({ raw: rawName, name, ofPlugin });
+ }
+
+ _claude(ev) {
+ if (ev.type === 'system' && ev.subtype === 'init' && Array.isArray(ev.skills)) {
+ this.loadedSkills = ev.skills.slice();
+ } else if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {
+ for (const c of ev.message.content) {
+ if (c.type === 'tool_use' && c.name === 'Skill' && c.input) this._skill(c.id, c.input.skill);
+ else if (c.type === 'text' && typeof c.text === 'string') this.text = c.text;
+ }
+ } else if (ev.type === 'result') {
+ this.result = { subtype: ev.subtype, isError: ev.is_error === true, turns: ev.num_turns, costUsd: ev.total_cost_usd };
+ }
+ }
+
+ _copilot(ev) {
+ const d = ev.data || {};
+ if (ev.type === 'assistant.message') {
+ for (const r of d.toolRequests || []) {
+ if (r.name === 'skill' && r.arguments) this._skill(r.toolCallId, r.arguments.skill);
+ }
+ if (typeof d.content === 'string' && d.content) this.text = d.content;
+ } else if (ev.type === 'tool.execution_start' && d.toolName === 'skill' && d.arguments) {
+ this._skill(d.toolCallId, d.arguments.skill);
+ } else if (ev.type === 'result') {
+ this.result = { exitCode: ev.exitCode, premiumRequests: ev.usage && ev.usage.premiumRequests };
+ }
+ }
+}
+
+/** Parse a whole transcript at once (tests, and re-grading saved transcripts). */
+function parseTranscript(agent, text, plugin) {
+ const p = new TranscriptParser(agent, plugin);
+ for (const line of String(text).split(/\r?\n/)) p.push(line);
+ return p;
+}
+
+module.exports = { TranscriptParser, parseTranscript, AGENTS };
diff --git a/evals/model-apps/routing/run-routing.js b/evals/model-apps/routing/run-routing.js
new file mode 100644
index 000000000..994b59932
--- /dev/null
+++ b/evals/model-apps/routing/run-routing.js
@@ -0,0 +1,486 @@
+#!/usr/bin/env node
+'use strict';
+
+// Routing (skill-trigger) eval runner for the model-apps plugin.
+//
+// The offline harnesses next door (genpage/, app-builder/) grade ARTIFACTS a run produced. This
+// one grades the decision that happens before any of that: given a user prompt and the plugin's
+// skill descriptions, does the agent pick the right skill — `/genpage` for a page in an app that
+// already exists, `/app-builder` for a whole app, and NEITHER for Power Pages, canvas, Power
+// Automate or a generic web app? The two descriptions explicitly point at each other, so a
+// wording change to one can silently start stealing the other's prompts; nothing else catches it.
+//
+// Each trial launches a real agent CLI headlessly (Claude Code or GitHub Copilot CLI) in an
+// isolated empty workspace with ONLY this plugin loaded, streams its JSONL transcript, and kills
+// it the moment a plugin skill is invoked (see lib/agents.js for the isolation flags and
+// lib/transcript.js for the event shapes). Cost is therefore ~one model turn per trial.
+//
+// NOT part of the per-PR gate: it needs model credentials, is non-deterministic, and costs money.
+// See EVAL_GUIDE.md → "Cadence" and .github/workflows/model-apps-agent-evals.yml.
+//
+// Usage: node run-routing.js [--agent claude|copilot] [--model <m>] [--runs <n>]
+// [--threshold <0..1|a/b>] [--tier smoke|full|stress] [--eval <id>] [--concurrency <n>]
+// [--timeout <sec>] [--out <results.json>] [--transcripts <dir>] [--compare <prev.json>]
+// [--agent-bin <path>] [--dry-run]
+// Exit: 0 every case met the threshold · 1 a case failed · 2 harness error (bad args, agent
+// missing / not signed in, plugin not loaded, or every trial of a case errored)
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { spawn, spawnSync } = require('node:child_process');
+
+const { TIERS } = require('../lib/eval-args.js');
+const { TranscriptParser, AGENTS } = require('./lib/transcript.js');
+const { buildInvocation, quoteForCmd } = require('./lib/agents.js');
+const { summarizeCase, validateEvals } = require('./lib/grade.js');
+
+const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');
+const PLUGIN_DIR = path.join(REPO_ROOT, 'plugins', 'model-apps');
+const PLUGIN_NAME = 'model-apps';
+
+const DEFAULTS = { agent: 'claude', model: null, runs: 3, threshold: 2 / 3, thresholdLabel: '2/3', tier: null, eval: null, concurrency: 4, timeout: 180, out: null, transcripts: null, compare: null, agentBin: null, dryRun: false };
+
+const USAGE = `Usage: run-routing.js [options]
+
+ --agent <claude|copilot> Agent CLI to drive (default: claude)
+ --model <name> Model passed to the agent CLI (default: the CLI's own default)
+ --runs <n> Trials per case (default: 3)
+ --threshold <0..1|a/b> Minimum pass rate per case, compared strictly (default: 2/3)
+ --tier <tier> Only cases of this tier (${TIERS.join(' | ')})
+ --eval <id> Only this case id
+ --concurrency <n> Parallel trials (default: 4)
+ --timeout <sec> Per-trial timeout (default: 180)
+ --out <file> Write machine-readable results JSON
+ --transcripts <dir> Save each trial's raw JSONL transcript (local debugging; may contain local paths)
+ --compare <file> Print per-case pass-rate deltas against an earlier --out file
+ --agent-bin <path> Override the agent executable
+ --dry-run Print the invocation and selected cases; launch nothing
+`;
+
+function parseArgs(argv, { fail = (m) => { console.error(`error: ${m}`); process.exit(2); } } = {}) {
+ const a = { ...DEFAULTS };
+ const value = (flag, i) => {
+ const v = argv[i];
+ if (v === undefined || /^--/.test(v)) fail(`${flag} requires a value`);
+ return v;
+ };
+ const int = (flag, raw, min) => {
+ if (!/^\d+$/.test(raw) || Number(raw) < min) fail(`${flag} requires an integer >= ${min} (got ${JSON.stringify(raw)})`);
+ return Number(raw);
+ };
+ for (let i = 0; i < argv.length; i++) {
+ const f = argv[i];
+ switch (f) {
+ case '--agent': a.agent = value(f, ++i); if (!AGENTS.includes(a.agent)) fail(`--agent must be one of ${AGENTS.join('|')}`); break;
+ case '--model':
+ a.model = value(f, ++i);
+ // On Windows the agent CLI is a .cmd shim launched through cmd.exe, where `%VAR%` and
+ // `!` expand even inside double quotes. Model ids never need those characters, so
+ // reject anything outside a plain id charset instead of trusting quoting.
+ if (!/^[A-Za-z0-9._:/-]+$/.test(a.model)) fail(`--model must be a plain model id (letters, digits, . _ : / -), got ${JSON.stringify(a.model)}`);
+ break;
+ case '--runs': a.runs = int(f, value(f, ++i), 1); break;
+ case '--threshold': {
+ // A decimal in (0, 1] or an exact fraction such as 2/3 — the default — so "2 of 3" never
+ // has to be rounded to 0.67 (which 2/3 = 0.666… would then fail under strict comparison).
+ const raw = value(f, ++i);
+ const frac = /^(\d+)\/(\d+)$/.exec(raw);
+ const n = frac ? Number(frac[1]) / Number(frac[2]) : Number(raw);
+ const shapeOk = frac ? Number(frac[2]) > 0 : /^(0(\.\d+)?|1(\.0+)?)$/.test(raw);
+ if (!shapeOk || !(n > 0 && n <= 1)) fail(`--threshold must be a number in (0, 1] or a fraction such as 2/3 (got ${JSON.stringify(raw)})`);
+ a.threshold = n;
+ a.thresholdLabel = raw;
+ break;
+ }
+ case '--tier': a.tier = value(f, ++i); if (!TIERS.includes(a.tier)) fail(`--tier must be one of ${TIERS.join('|')}`); break;
+ case '--eval': a.eval = int(f, value(f, ++i), 0); break;
+ case '--concurrency': a.concurrency = int(f, value(f, ++i), 1); break;
+ case '--timeout': a.timeout = int(f, value(f, ++i), 1); break;
+ case '--out': a.out = value(f, ++i); break;
+ case '--transcripts': a.transcripts = value(f, ++i); break;
+ case '--compare': a.compare = value(f, ++i); break;
+ case '--agent-bin': a.agentBin = value(f, ++i); break;
+ case '--dry-run': a.dryRun = true; break;
+ case '--help': case '-h': process.stdout.write(USAGE); process.exit(0); break;
+ default: fail(`unknown argument ${JSON.stringify(f)}\n${USAGE}`);
+ }
+ }
+ return a;
+}
+
+function pluginSkills(pluginDir = PLUGIN_DIR) {
+ return fs.readdirSync(path.join(pluginDir, 'skills'), { withFileTypes: true })
+ .filter((e) => e.isDirectory() && fs.existsSync(path.join(pluginDir, 'skills', e.name, 'SKILL.md')))
+ .map((e) => e.name)
+ .sort();
+}
+
+/**
+ * A SKILL.md frontmatter `description`, inline or as a YAML block scalar:
+ * description: Creates, updates … pages. ← inline (genpage, app-builder)
+ * description: > ← folded (report-issue, telemetry)
+ * Use this skill when the user wants to …
+ * For a block scalar, the value is every following line indented deeper than the key, joined.
+ * Reading only the key's own line hashed the literal ">" for folded descriptions, so edits to
+ * them never moved the fingerprint.
+ */
+function frontmatterDescription(md) {
+ const fm = md.match(/^---\r?\n([\s\S]*?)\r?\n---/);
+ const lines = (fm ? fm[1] : '').split(/\r?\n/);
+ const i = lines.findIndex((l) => /^description:/.test(l));
+ if (i < 0) return '';
+ const inline = lines[i].replace(/^description:\s*/, '').trim();
+ if (!/^[>|][+-]?$/.test(inline)) return inline;
+ const body = [];
+ for (const l of lines.slice(i + 1)) {
+ if (l.trim() && !/^\s/.test(l)) break;
+ body.push(l.trim());
+ }
+ return body.join(' ').trim();
+}
+
+/**
+ * Fingerprint of what the model routes on — each skill's frontmatter `description:`. Recorded in
+ * the results so a --compare between two runs can tell "the descriptions changed" from noise.
+ */
+function descriptionFingerprint(pluginDir = PLUGIN_DIR) {
+ const out = {};
+ for (const s of pluginSkills(pluginDir)) {
+ const md = fs.readFileSync(path.join(pluginDir, 'skills', s, 'SKILL.md'), 'utf8');
+ out[s] = crypto.createHash('sha256').update(frontmatterDescription(md)).digest('hex').slice(0, 12);
+ }
+ return out;
+}
+
+function killTree(child) {
+ if (!child || child.exitCode !== null || child.killed) return;
+ try {
+ if (process.platform === 'win32') {
+ // child.kill() would end only cmd.exe and orphan the agent beneath it.
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
+ } else {
+ process.kill(-child.pid, 'SIGKILL'); // detached → its own process group
+ }
+ } catch { /* already gone */ }
+}
+
+/**
+ * How to launch `bin` with `argv`. Windows: a bare name (PATH lookup) or a .cmd/.bat shim must go
+ * through cmd.exe — Node refuses to spawn a batch file without a shell (EINVAL) — so the command
+ * itself is quoted too. Shared by the trial and the Copilot skill preflight so both resolve the
+ * same executable the same way.
+ */
+function commandFor(bin, argv) {
+ const useShell = process.platform === 'win32' && (!path.isAbsolute(bin) || /\.(cmd|bat)$/i.test(bin));
+ return { cmd: useShell ? quoteForCmd(bin) : bin, args: useShell ? argv.map(quoteForCmd) : argv, shell: useShell };
+}
+
+/**
+ * Copilot CLI does not report its loaded skills in the JSONL stream (Claude's init event does), so
+ * ask the CLI itself, with the trial's plugin dir and isolated COPILOT_HOME — the same inputs the
+ * session resolves skills from:
+ * copilot --plugin-dir <dir> --no-auto-update skill list --json
+ * → [{ "name": "genpage", "source": "plugin", "path": "<dir>\\skills\\genpage", "enabled": true },
+ * { "name": "customize-cloud-agent", "source": "builtin", "path": "...", "enabled": true }, …]
+ * `names` are the enabled skills that come from the plugin under test; `leaks` are enabled skills
+ * from anywhere else except the CLI's own builtins (a personal, project or other plugin's skill
+ * reaching the trial means the isolation failed and routing could be steered by it).
+ * @returns {{names?: string[], leaks?: string[], error?: string}}
+ */
+function copilotSkillInventory({ bin, binArgs = [], pluginDir, env, cwd }) {
+ const { cmd, args, shell } = commandFor(bin, [...binArgs, '--plugin-dir', pluginDir, '--no-auto-update', 'skill', 'list', '--json']);
+ const r = spawnSync(cmd, args, { cwd, env: { ...process.env, ...env }, shell, encoding: 'utf8', timeout: 60000, windowsHide: true });
+ if (r.error || r.status !== 0) {
+ const tail = String(r.stderr || (r.error && r.error.message) || '').trim().split(/\r?\n/).slice(-2).join(' | ');
+ return { error: `could not verify Copilot skill loading (\`skill list\` exit ${r.status})${tail ? `: ${tail}` : ''}` };
+ }
+ let list;
+ try { list = JSON.parse(r.stdout); } catch { return { error: 'could not verify Copilot skill loading: `skill list --json` returned unparseable output' }; }
+ if (!Array.isArray(list)) return { error: 'could not verify Copilot skill loading: `skill list --json` did not return an array' };
+ const norm = (p) => { const s = path.resolve(String(p || '')); return process.platform === 'win32' ? s.toLowerCase() : s; };
+ const root = norm(pluginDir) + path.sep;
+ const fromPlugin = (s) => s.source === 'plugin' && norm(s.path).startsWith(root);
+ const enabled = list.filter((s) => s && s.enabled !== false);
+ return {
+ names: enabled.filter(fromPlugin).map((s) => s.name),
+ leaks: enabled.filter((s) => s.source !== 'builtin' && !fromPlugin(s)).map((s) => `${s.name} (${s.source})`),
+ };
+}
+
+/**
+ * Launch one agent run and resolve when it ROUTED, finished, timed out, or failed to start.
+ * Never rejects: every failure becomes `trial.error`, which grading excludes from the pass rate.
+ * `loadedSkills` / `loadError` carry a preflight's skill inventory for agents whose transcript does
+ * not report it (Copilot); a `loadError` fails the trial before any model call is made.
+ */
+function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugin, agent, loadedSkills = null, loadError = null }) {
+ return new Promise((resolve) => {
+ const started = Date.now();
+ const parser = new TranscriptParser(agent, plugin);
+ if (loadError) {
+ resolve({ error: loadError, routedTo: null, skillCalls: [], loadedSkills, durationMs: 0, stdout: '' });
+ return;
+ }
+ const { cmd, args: argv, shell: useShell } = commandFor(bin, [...binArgs, ...args]);
+ let child;
+ try {
+ child = spawn(cmd, argv, {
+ cwd,
+ env: { ...process.env, ...env },
+ shell: useShell,
+ detached: process.platform !== 'win32',
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ } catch (err) {
+ resolve({ error: `could not start ${bin}: ${err.message}`, routedTo: null, skillCalls: [], durationMs: 0, stdout: '' });
+ return;
+ }
+ let stdout = '';
+ let stderr = '';
+ let buf = '';
+ let timedOut = false;
+ let settled = false;
+ const finish = (extra = {}) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ killTree(child);
+ let error = extra.error || null;
+ // "none" is a DECISION only when the run ended on its own without choosing a plugin skill.
+ // A run cut off by the timeout has not decided anything — even if it streamed events (an
+ // init line, message deltas) first — and graded as `none` it would pass every negative
+ // case. So a timeout without a route is always an error, excluded from the pass rate; so is
+ // a run that produced no transcript at all (network/auth stall, a CLI that ignored stdin).
+ if (!error && parser.routedTo === null) {
+ if (timedOut) {
+ error = parser.eventCount === 0
+ ? 'timed out with no transcript output'
+ : `timed out before routing (${parser.eventCount} transcript events, no decision)`;
+ } else if (parser.eventCount === 0) {
+ error = `${bin} produced no transcript output`;
+ } else if (parser.resultError) {
+ error = `${parser.resultError} before any routing decision`;
+ }
+ }
+ // Isolation guard: if the plugin's skills are not all loaded, every negative case would
+ // "pass" for the wrong reason and positives would look like routing failures — so fail
+ // loudly instead. Claude reports its skills in the init event (namespaced
+ // `model-apps:genpage`); Copilot's come from the skill-list preflight (bare `genpage`).
+ const loaded = parser.loadedSkills || loadedSkills;
+ if (!error && loaded) {
+ const missing = plugin.pluginSkills.filter((s) => !loaded.includes(`${plugin.pluginName}:${s}`) && !loaded.includes(s));
+ if (missing.length) error = `plugin skills not loaded: ${missing.join(', ')} (check --plugin-dir)`;
+ }
+ resolve({
+ routedTo: parser.routedTo,
+ skillCalls: parser.skillCalls,
+ loadedSkills: loaded,
+ result: parser.result,
+ timedOut,
+ error,
+ durationMs: Date.now() - started,
+ stdout,
+ });
+ };
+ const timer = setTimeout(() => { timedOut = true; finish(); }, timeoutMs);
+ child.stdout.on('data', (chunk) => {
+ const s = chunk.toString('utf8');
+ stdout += s;
+ buf += s;
+ let nl;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ parser.push(buf.slice(0, nl));
+ buf = buf.slice(nl + 1);
+ if (parser.routedTo !== null) { finish(); return; }
+ }
+ });
+ child.stderr.on('data', (c) => { stderr += c.toString('utf8'); });
+ child.on('error', (err) => finish({ error: `could not start ${bin}: ${err.message}` }));
+ child.on('close', (code) => {
+ if (buf) parser.push(buf);
+ const tail = stderr.trim().split(/\r?\n/).slice(-3).join(' | ');
+ // A run that ends without routing is a valid "none" outcome only if it ended SUCCESSFULLY.
+ // Exiting non-zero is an auth/install/runtime failure, not a decision — even when a terminal
+ // `result` event was printed first (a failed result is also caught via parser.resultError).
+ if (parser.routedTo === null && code !== 0 && !timedOut) {
+ finish({ error: `${bin} exited ${code} before any routing decision${tail ? `: ${tail}` : ''}` });
+ } else {
+ finish();
+ }
+ });
+ child.stdin.on('error', () => { /* agent exited before reading the prompt; 'close' reports it */ });
+ child.stdin.end(prompt);
+ });
+}
+
+function mkTemp(prefix) {
+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+}
+
+function rmQuiet(dir) {
+ // Windows can hold a handle briefly after taskkill; retry rather than fail the run over cleanup.
+ try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* best effort */ }
+}
+
+/** Default trial runner: real agent CLI, isolated temp workspace (+ COPILOT_HOME). */
+async function runTrialWithAgent(opts, evalCase, plugin) {
+ const cwd = mkTemp('mapps-routing-ws-');
+ const copilotHome = opts.agent === 'copilot' ? mkTemp('mapps-routing-home-') : undefined;
+ try {
+ const inv = buildInvocation(opts.agent, { pluginDir: PLUGIN_DIR, model: opts.model, copilotHome });
+ const bin = opts.agentBin || inv.bin;
+ // Copilot's transcript never lists loaded skills, so verify them up front with the same
+ // isolated home and plugin dir; a missing skill or a leaked one is a trial error, not a grade.
+ let preflight = {};
+ if (opts.agent === 'copilot') {
+ const inventory = copilotSkillInventory({ bin, pluginDir: PLUGIN_DIR, env: inv.env, cwd });
+ preflight = inventory.error
+ ? { loadError: inventory.error }
+ : inventory.leaks.length
+ ? { loadError: `isolation leak: skills from outside the plugin are loaded: ${inventory.leaks.join(', ')}` }
+ : { loadedSkills: inventory.names };
+ }
+ return await spawnTrial({
+ agent: opts.agent,
+ bin,
+ args: inv.args,
+ env: inv.env,
+ prompt: evalCase.prompt,
+ cwd,
+ timeoutMs: opts.timeout * 1000,
+ plugin,
+ ...preflight,
+ });
+ } finally {
+ rmQuiet(cwd);
+ if (copilotHome) rmQuiet(copilotHome);
+ }
+}
+
+async function pool(items, limit, fn) {
+ const results = new Array(items.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < items.length) {
+ const i = next++;
+ results[i] = await fn(items[i], i);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
+ return results;
+}
+
+function yamlStr(s) { return JSON.stringify(String(s)); }
+
+/**
+ * Run the selected cases and print TAP. `deps.runTrial` is the seam tests use to grade canned
+ * trials without launching an agent.
+ * @returns {Promise<{exitCode: number, results: object}>}
+ */
+async function runRouting(opts, { runTrial = runTrialWithAgent, evalsData, write = (l) => process.stdout.write(`${l}\n`), plugin } = {}) {
+ plugin = plugin || { pluginName: PLUGIN_NAME, pluginSkills: pluginSkills() };
+ const data = evalsData || JSON.parse(fs.readFileSync(path.join(__dirname, 'evals.json'), 'utf8'));
+ const errs = validateEvals(data, plugin.pluginSkills);
+ if (errs.length) {
+ for (const e of errs) console.error(`error: evals.json: ${e}`);
+ return { exitCode: 2, results: null };
+ }
+ let cases = data.evals;
+ if (opts.tier) cases = cases.filter((c) => c.tier === opts.tier);
+ if (opts.eval !== null) cases = cases.filter((c) => c.id === opts.eval);
+ if (!cases.length) {
+ console.error('error: no cases matched the filter');
+ return { exitCode: 2, results: null };
+ }
+
+ if (opts.dryRun) {
+ const inv = buildInvocation(opts.agent, { pluginDir: PLUGIN_DIR, model: opts.model, copilotHome: '<temp COPILOT_HOME>' });
+ write(`# dry run — would launch ${cases.length} case(s) × ${opts.runs} trial(s):`);
+ write(`# ${opts.agentBin || inv.bin} ${inv.args.join(' ')} (prompt on stdin, cwd = empty temp dir)`);
+ for (const c of cases) write(`# #${c.id} [${c.tier}] expect ${c.expect === null ? 'none' : c.expect}: ${c.prompt}`);
+ return { exitCode: 0, results: null };
+ }
+
+ const jobs = cases.flatMap((c) => Array.from({ length: opts.runs }, (_, t) => ({ c, t })));
+ const trials = await pool(jobs, opts.concurrency, async ({ c, t }) => {
+ const trial = await runTrial(opts, c, plugin);
+ if (opts.transcripts && trial.stdout) {
+ fs.mkdirSync(opts.transcripts, { recursive: true });
+ fs.writeFileSync(path.join(opts.transcripts, `${c.id}-${t + 1}.${opts.agent}.jsonl`), trial.stdout);
+ }
+ return { id: c.id, trial };
+ });
+
+ const byCase = new Map(cases.map((c) => [c.id, []]));
+ for (const { id, trial } of trials) byCase.get(id).push(trial);
+
+ const prev = opts.compare ? JSON.parse(fs.readFileSync(opts.compare, 'utf8')) : null;
+ const prevRate = new Map(prev ? prev.cases.map((c) => [c.id, c.rate]) : []);
+
+ write('TAP version 13');
+ write(`# agent ${opts.agent} · model ${opts.model || '(cli default)'} · runs ${opts.runs} · threshold ${opts.thresholdLabel || opts.threshold}`);
+ write(`1..${cases.length}`);
+ const summary = { pass: 0, fail: 0, error: 0, trials: 0, trialErrors: 0, costUsd: 0 };
+ const caseResults = [];
+ cases.forEach((c, i) => {
+ const ts = byCase.get(c.id);
+ const s = summarizeCase(c, ts, opts.threshold);
+ summary[s.status] += 1;
+ summary.trials += ts.length;
+ summary.trialErrors += s.errors.length;
+ for (const t of ts) if (t.result && typeof t.result.costUsd === 'number') summary.costUsd += t.result.costUsd;
+ const dist = Object.entries(s.outcomes).map(([k, v]) => `${k}×${v}`).join(', ') || 'no valid trials';
+ const head = `#${c.id} [${c.tier}] expect ${c.expect === null ? 'none' : c.expect} — ${s.passes}/${s.valid} (${dist})`;
+ write(`${s.status === 'pass' ? 'ok' : 'not ok'} ${i + 1} - ${head}`);
+ if (s.status !== 'pass' || s.errors.length) {
+ write(' ---');
+ write(` prompt: ${yamlStr(c.prompt)}`);
+ if (c.trap) write(` trap: ${yamlStr(c.trap)}`);
+ for (const e of [...new Set(s.errors)]) write(` error: ${yamlStr(e)}`);
+ write(' ...');
+ }
+ if (prevRate.has(c.id) && s.rate !== null && prevRate.get(c.id) !== s.rate) {
+ write(`# delta #${c.id}: ${prevRate.get(c.id) === null ? 'n/a' : prevRate.get(c.id).toFixed(2)} → ${s.rate.toFixed(2)}`);
+ }
+ caseResults.push({
+ id: c.id, tier: c.tier, prompt: c.prompt, expect: c.expect, accept: c.accept || [],
+ status: s.status, rate: s.rate, passes: s.passes, valid: s.valid, outcomes: s.outcomes, errors: s.errors,
+ trials: ts.map((t) => ({ routedTo: t.routedTo, skills: (t.skillCalls || []).map((k) => k.raw), timedOut: !!t.timedOut, error: t.error || null, durationMs: t.durationMs })),
+ });
+ });
+ write(`# cases ${cases.length} (pass ${summary.pass}, fail ${summary.fail}, error ${summary.error})`);
+ write(`# trials ${summary.trials} (errors ${summary.trialErrors})`);
+ // Only runs that reach their `result` event report cost; trials killed at the routing decision
+ // never do, so this is a lower bound and is labelled as one.
+ if (summary.costUsd) write(`# cost >= $${summary.costUsd.toFixed(2)} (killed trials do not report cost)`);
+
+ const results = {
+ schema: 1,
+ agent: opts.agent,
+ model: opts.model,
+ runs: opts.runs,
+ threshold: opts.threshold,
+ finishedAt: new Date().toISOString(),
+ descriptions: descriptionFingerprint(),
+ summary,
+ cases: caseResults,
+ };
+ if (opts.out) fs.writeFileSync(opts.out, `${JSON.stringify(results, null, 2)}\n`);
+ const exitCode = summary.error ? 2 : summary.fail ? 1 : 0;
+ return { exitCode, results };
+}
+
+async function main() {
+ const opts = parseArgs(process.argv.slice(2));
+ const { exitCode } = await runRouting(opts);
+ process.exitCode = exitCode;
+}
+
+if (require.main === module) {
+ main().catch((err) => { console.error(`error: ${err.stack || err.message}`); process.exit(2); });
+}
+
+module.exports = { parseArgs, runRouting, spawnTrial, copilotSkillInventory, pluginSkills, descriptionFingerprint, frontmatterDescription, DEFAULTS };
diff --git a/evals/model-apps/routing/tests/fake-agent.js b/evals/model-apps/routing/tests/fake-agent.js
new file mode 100644
index 000000000..054056b77
--- /dev/null
+++ b/evals/model-apps/routing/tests/fake-agent.js
@@ -0,0 +1,73 @@
+'use strict';
+// Stand-in for an agent CLI in run-routing tests. Reads the prompt from stdin (as the real CLIs
+// do), then behaves according to FAKE_AGENT_MODE:
+// route-then-hang print a Claude init + Skill tool_use, then stay alive (the runner must kill it)
+// answer print a text answer + result event and exit 0 (a "none" outcome)
+// crash print to stderr and exit 3 before any decision (auth/install failure shape)
+// hang print nothing and never exit (timeout path)
+// init-then-hang print the init event, then never exit (timeout AFTER transcript output)
+// no-plugin init event WITHOUT the plugin's skills, then a text answer (isolation guard)
+// claude-failed Claude init + a FAILED result (error_during_execution), no skill call
+// copilot-failed Copilot-format FAILED result (exitCode 1), no skill call
+// copilot-answer Copilot-format successful text answer (exitCode 0), no skill call
+// FAKE_AGENT_EXIT sets the process exit code for the *-failed modes (default 1), so a test can
+// prove the failed RESULT alone is caught even when the process exits 0.
+const mode = process.env.FAKE_AGENT_MODE;
+const out = (o) => process.stdout.write(`${JSON.stringify(o)}\n`);
+const skills = ['model-apps:app-builder', 'model-apps:genpage', 'model-apps:report-issue', 'model-apps:telemetry'];
+
+// `<agent> --plugin-dir <dir> ... skill list --json` — the Copilot skill-load preflight. Shape per
+// FAKE_SKILL_LIST: ok (all four plugin skills + a builtin), missing (builtin only), leak (adds a
+// personal skill), broken (exit 2), garbage (non-JSON).
+const argv = process.argv.slice(2);
+if (argv.includes('skill') && argv.includes('list')) {
+ const path = require('node:path');
+ const dir = argv[argv.indexOf('--plugin-dir') + 1];
+ const plugin = ['app-builder', 'genpage', 'report-issue', 'telemetry'].map((name) => ({ name, source: 'plugin', path: path.join(dir, 'skills', name), enabled: true }));
+ const builtin = { name: 'customize-cloud-agent', source: 'builtin', path: '/opt/copilot/builtin/customize-cloud-agent', enabled: true };
+ const shape = process.env.FAKE_SKILL_LIST || 'ok';
+ if (shape === 'broken') { process.stderr.write('Error: not signed in\n'); process.exit(2); }
+ if (shape === 'garbage') { process.stdout.write('not json\n'); process.exit(0); }
+ const list = shape === 'missing' ? [builtin]
+ : shape === 'leak' ? [...plugin, builtin, { name: 'brainstorming', source: 'personal', path: '/home/u/.copilot/skills/brainstorming', enabled: true }]
+ : [...plugin, builtin];
+ process.stdout.write(JSON.stringify(list));
+ process.exit(0);
+}
+
+let prompt = '';
+process.stdin.on('data', (c) => { prompt += c; });
+process.stdin.on('end', () => {
+ if (mode === 'crash') {
+ process.stderr.write('Error: not signed in\n');
+ process.exit(3);
+ }
+ if (mode === 'hang') { setInterval(() => {}, 1000); return; }
+ const failExit = Number(process.env.FAKE_AGENT_EXIT || 1);
+ if (mode === 'copilot-failed') {
+ out({ type: 'user.message', data: { content: prompt.trim() } });
+ out({ type: 'result', exitCode: 1, usage: { premiumRequests: 1 } });
+ process.exit(failExit);
+ }
+ if (mode === 'copilot-answer') {
+ out({ type: 'user.message', data: { content: prompt.trim() } });
+ out({ type: 'assistant.message', data: { content: 'That is outside these skills.', toolRequests: [] } });
+ out({ type: 'result', exitCode: 0, usage: { premiumRequests: 1 } });
+ process.exit(0);
+ }
+ out({ type: 'system', subtype: 'init', skills: mode === 'no-plugin' ? ['design'] : skills });
+ if (mode === 'init-then-hang') { setInterval(() => {}, 1000); return; }
+ if (mode === 'claude-failed') {
+ out({ type: 'result', subtype: 'error_during_execution', is_error: true, num_turns: 1, total_cost_usd: 0.001 });
+ process.exit(failExit);
+ }
+ if (mode === 'route-then-hang') {
+ const skill = /app/i.test(prompt) ? 'model-apps:app-builder' : 'model-apps:genpage';
+ out({ type: 'assistant', message: { content: [{ type: 'tool_use', id: 't1', name: 'Skill', input: { skill } }] } });
+ setInterval(() => {}, 1000);
+ return;
+ }
+ out({ type: 'assistant', message: { content: [{ type: 'text', text: `no skill for: ${prompt.trim()}` }] } });
+ out({ type: 'result', subtype: 'success', num_turns: 1, total_cost_usd: 0.001 });
+ process.exit(0);
+});
diff --git a/evals/model-apps/routing/tests/routing-lib.test.js b/evals/model-apps/routing/tests/routing-lib.test.js
new file mode 100644
index 000000000..ef6112d9e
--- /dev/null
+++ b/evals/model-apps/routing/tests/routing-lib.test.js
@@ -0,0 +1,199 @@
+'use strict';
+// Pure-unit tests for the routing eval library: transcript parsing (both CLIs), grading, the
+// evals.json validator, and the agent invocation flags. No agent is launched here.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const { TranscriptParser, parseTranscript } = require('../lib/transcript.js');
+const { gradeTrial, summarizeCase, validateEvals, acceptable } = require('../lib/grade.js');
+const { buildInvocation, quoteForCmd, TELEMETRY_OPTOUT } = require('../lib/agents.js');
+
+const PLUGIN = { pluginName: 'model-apps', pluginSkills: ['app-builder', 'genpage', 'report-issue', 'telemetry'] };
+const sample = (name) => fs.readFileSync(path.join(__dirname, 'transcripts', name), 'utf8');
+
+// ---------- transcript ----------
+
+test('transcript(claude): namespaced Skill tool_use is the routing decision; init skills recorded', () => {
+ const p = parseTranscript('claude', sample('claude-genpage.jsonl'), PLUGIN);
+ assert.equal(p.routedTo, 'genpage');
+ assert.deepEqual(p.skillCalls.map((c) => c.raw), ['model-apps:genpage']);
+ assert.ok(p.loadedSkills.includes('model-apps:app-builder'));
+ assert.equal(p.result.costUsd, 0.0123);
+ assert.equal(p.decided, true);
+});
+
+test('transcript(copilot): unprefixed skill, de-duplicated across assistant.message and tool.execution_start', () => {
+ const p = parseTranscript('copilot', sample('copilot-app-builder.jsonl'), PLUGIN);
+ assert.equal(p.routedTo, 'app-builder');
+ assert.equal(p.skillCalls.length, 1, 'the execution_start echo of the same toolCallId must not double-count');
+ assert.equal(p.result.premiumRequests, 1);
+ assert.equal(p.loadedSkills, null, 'Copilot does not report loaded skills');
+});
+
+test('transcript(copilot): a run that answers in text routes to none, and is decided by its result event', () => {
+ const p = parseTranscript('copilot', sample('copilot-none.jsonl'), PLUGIN);
+ assert.equal(p.routedTo, null);
+ assert.equal(p.decided, true);
+ assert.match(p.text, /Power Pages/);
+});
+
+test('transcript: a built-in or foreign-plugin skill is recorded but is not a routing decision', () => {
+ const p = new TranscriptParser('claude', PLUGIN);
+ const use = (id, skill) => JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id, name: 'Skill', input: { skill } }] } });
+ p.push(use('a', 'design'));
+ p.push(use('b', 'other-plugin:genpage')); // same skill name, different plugin
+ assert.equal(p.routedTo, null);
+ assert.equal(p.decided, false, 'the model may still route after a built-in skill');
+ p.push(use('c', 'model-apps:app-builder'));
+ assert.equal(p.routedTo, 'app-builder');
+ assert.deepEqual(p.skillCalls.map((c) => c.ofPlugin), [false, false, true]);
+});
+
+test('transcript: an unprefixed name only counts when the plugin ships that skill', () => {
+ const p = new TranscriptParser('copilot', PLUGIN);
+ p.push(JSON.stringify({ type: 'assistant.message', data: { toolRequests: [{ toolCallId: 'x', name: 'skill', arguments: { skill: 'brainstorming' } }] } }));
+ assert.equal(p.routedTo, null);
+});
+
+test('transcript: banners, blank lines, partial JSON and stderr noise are ignored, not fatal', () => {
+ const p = new TranscriptParser('claude', PLUGIN);
+ for (const l of ['', 'Warning: something', '{"type":"assistant","message":', ' ', '[]', 'null']) p.push(l);
+ assert.deepEqual(p.skillCalls, []);
+ assert.equal(p.decided, false);
+});
+
+test('transcript: resultError reports a failed terminal result for both CLIs and nothing for success', () => {
+ const claude = (r) => { const p = new TranscriptParser('claude', PLUGIN); p.push(JSON.stringify({ type: 'result', ...r })); return p.resultError; };
+ assert.equal(claude({ subtype: 'success', is_error: false }), null);
+ assert.equal(claude({ subtype: 'error_max_turns', is_error: false }), 'claude result error_max_turns');
+ assert.equal(claude({ subtype: 'success', is_error: true }), 'claude result success (is_error)');
+ const copilot = (r) => { const p = new TranscriptParser('copilot', PLUGIN); p.push(JSON.stringify({ type: 'result', ...r })); return p.resultError; };
+ assert.equal(copilot({ exitCode: 0 }), null);
+ assert.equal(copilot({ exitCode: 1 }), 'copilot result exitCode 1');
+ assert.equal(new TranscriptParser('claude', PLUGIN).resultError, null, 'no result yet is not a failure');
+});
+
+test('transcript: an unknown agent is rejected', () => {
+ assert.throws(() => new TranscriptParser('gemini', PLUGIN), /unknown agent/);
+});
+
+// ---------- grading ----------
+
+const CASE_GENPAGE = { id: 1, prompt: 'p', expect: 'genpage' };
+const CASE_NONE = { id: 2, prompt: 'p', expect: null };
+const CASE_AMBIG = { id: 3, prompt: 'p', expect: 'genpage', accept: ['app-builder'] };
+
+test('grade: acceptable outcomes include accept[] and map null to "none"', () => {
+ assert.deepEqual(acceptable(CASE_AMBIG), ['genpage', 'app-builder']);
+ assert.deepEqual(acceptable(CASE_NONE), ['none']);
+});
+
+test('grade: trial pass/fail/error', () => {
+ assert.equal(gradeTrial(CASE_GENPAGE, { routedTo: 'genpage' }).status, 'pass');
+ const wrong = gradeTrial(CASE_GENPAGE, { routedTo: 'app-builder' });
+ assert.equal(wrong.status, 'fail');
+ assert.match(wrong.reason, /routed to app-builder, expected genpage/);
+ assert.equal(gradeTrial(CASE_NONE, { routedTo: null }).status, 'pass');
+ assert.equal(gradeTrial(CASE_NONE, { routedTo: 'genpage' }).status, 'fail');
+ assert.equal(gradeTrial(CASE_AMBIG, { routedTo: 'app-builder' }).status, 'pass');
+ assert.equal(gradeTrial(CASE_AMBIG, { routedTo: null }).status, 'fail', 'ambiguous ≠ anything goes');
+ assert.equal(gradeTrial(CASE_GENPAGE, { routedTo: null, error: 'boom' }).status, 'error');
+});
+
+test('grade: a timed-out trial arrives as an error and is never graded as "none"', () => {
+ const g = gradeTrial(CASE_NONE, { routedTo: null, timedOut: true, error: 'timed out before routing (3 transcript events, no decision)' });
+ assert.equal(g.status, 'error', 'a negative case must not pass on a run that never finished');
+});
+
+test('summarize: strict threshold over non-error trials; the default 2/3 is exactly 2 of 3', () => {
+ const t = (routedTo) => ({ routedTo });
+ assert.equal(summarizeCase(CASE_GENPAGE, [t('genpage'), t('genpage'), t(null)], 2 / 3).status, 'pass');
+ assert.equal(summarizeCase(CASE_GENPAGE, [t('genpage'), t(null), t(null)], 2 / 3).status, 'fail');
+ // No tolerance: a threshold is never lowered by a trial.
+ assert.equal(summarizeCase(CASE_GENPAGE, [t(null), t(null), t(null)], 0.01).status, 'fail', 'zero successes never pass');
+ const hundred = [...Array(99).fill(t('genpage')), t(null)];
+ assert.equal(summarizeCase(CASE_GENPAGE, hundred, 1).status, 'fail', 'threshold 1 needs every trial');
+ assert.equal(summarizeCase(CASE_GENPAGE, [...hundred.slice(0, 99), t('genpage')], 1).status, 'pass');
+ assert.equal(summarizeCase(CASE_GENPAGE, [t('genpage'), t('genpage'), t(null)], 0.67).status, 'fail', 'a rounded 0.67 is stricter than 2/3 — use 2/3');
+ // Float representation must not cost a trial: 0.7 * 10 = 7.000000000000001.
+ assert.equal(summarizeCase(CASE_GENPAGE, [...Array(7).fill(t('genpage')), t(null), t(null), t(null)], 0.7).status, 'pass');
+ const s = summarizeCase(CASE_GENPAGE, [t('genpage'), t('genpage'), { routedTo: null, error: 'spawn' }], 1);
+ assert.equal(s.status, 'pass', 'an errored trial is excluded, not counted as a fail');
+ assert.equal(s.valid, 2);
+ assert.deepEqual(s.errors, ['spawn']);
+ assert.deepEqual(s.outcomes, { genpage: 2 });
+});
+
+test('summarize: every trial errored → error, never pass or fail', () => {
+ const s = summarizeCase(CASE_NONE, [{ routedTo: null, error: 'not signed in' }], 2 / 3);
+ assert.equal(s.status, 'error');
+ assert.equal(s.rate, null);
+});
+
+test('validateEvals: the committed evals.json is valid', () => {
+ const data = require('../evals.json');
+ assert.deepEqual(validateEvals(data, PLUGIN.pluginSkills), []);
+ // Coverage the suite exists for: every authoring skill is a positive target AND there are
+ // negatives. If someone trims the file down to one shape, the eval stops measuring routing.
+ const expects = new Set(data.evals.map((e) => e.expect));
+ for (const want of ['genpage', 'app-builder', null]) assert.ok(expects.has(want), `no case expects ${want}`);
+ assert.ok(data.evals.filter((e) => e.expect === null).length >= 3, 'keep at least 3 negative (bleed) cases');
+});
+
+test('validateEvals: rejects bad ids, prompts, unknown skills and a missing expect', () => {
+ const errs = validateEvals({ evals: [
+ { id: 1, tier: 'smoke', prompt: 'x', expect: 'genpage' },
+ { id: 1, tier: 'smoke', prompt: 'x', expect: 'genpage' },
+ { id: -2, tier: 'smoke', prompt: '', expect: 'genpages' },
+ { id: 3, tier: 'smoke', prompt: 'x' },
+ { id: 4, tier: 'smoke', prompt: 'x', expect: null, accept: ['canvas'] },
+ ] }, PLUGIN.pluginSkills);
+ const all = errs.join('\n');
+ assert.match(all, /eval 1: duplicate id/);
+ assert.match(all, /eval -2: id must be/);
+ assert.match(all, /eval -2: prompt/);
+ assert.match(all, /"genpages" is not a plugin skill/);
+ assert.match(all, /eval 3: "expect" is required/);
+ assert.match(all, /accept "canvas"/);
+ assert.deepEqual(validateEvals({}, []), ['evals.json must have an "evals" array']);
+});
+
+// ---------- agent invocation ----------
+
+test('agents(claude): isolation + read-only tool allowlist + stream-json + telemetry opt-out', () => {
+ const inv = buildInvocation('claude', { pluginDir: '/p', model: 'sonnet' });
+ assert.equal(inv.bin, 'claude');
+ const a = inv.args.join(' ');
+ for (const flag of ['-p', '--plugin-dir /p', '--restricted', '--strict-mcp-config',
+ '--tools Skill,Read,Glob,Grep', '--output-format stream-json', '--verbose', '--no-session-persistence', '--model sonnet']) {
+ assert.ok(a.includes(flag), `missing ${flag}`);
+ }
+ assert.equal(inv.env[TELEMETRY_OPTOUT], '1');
+ assert.ok(!buildInvocation('claude', { pluginDir: '/p' }).args.includes('--model'), 'no --model unless asked: the CLI default applies');
+ // --safe-mode was measured to drop the --plugin-dir plugin's skills, so every trial would be a
+ // harness error; it must not creep back in as an "isolation" improvement.
+ assert.ok(!inv.args.includes('--safe-mode'));
+});
+
+test('agents(copilot): isolated COPILOT_HOME required; variadic --available-tools is last', () => {
+ assert.throws(() => buildInvocation('copilot', { pluginDir: '/p' }), /copilotHome/);
+ const inv = buildInvocation('copilot', { pluginDir: '/p', copilotHome: '/h', model: 'm' });
+ assert.equal(inv.env.COPILOT_HOME, '/h');
+ assert.equal(inv.env[TELEMETRY_OPTOUT], '1');
+ const i = inv.args.indexOf('--available-tools');
+ assert.deepEqual(inv.args.slice(i), ['--available-tools', 'skill', 'view', 'glob', 'grep']);
+ for (const flag of ['--no-custom-instructions', '--no-ask-user', '--disable-builtin-mcps', '--output-format']) {
+ assert.ok(inv.args.includes(flag), `missing ${flag}`);
+ }
+ assert.deepEqual(inv.args.slice(inv.args.indexOf('--disable-mcp-server'), inv.args.indexOf('--disable-mcp-server') + 2), ['--disable-mcp-server', 'playwright']);
+});
+
+test('agents: quoteForCmd quotes paths with spaces and cmd metacharacters only', () => {
+ assert.equal(quoteForCmd('--verbose'), '--verbose');
+ assert.equal(quoteForCmd('C:\\Program Files\\x'), '"C:\\Program Files\\x"');
+ assert.equal(quoteForCmd('a&b'), '"a&b"');
+ assert.equal(quoteForCmd('Skill,Read'), '"Skill,Read"');
+ assert.equal(quoteForCmd('say "hi"'), '"say ""hi"""');
+});
diff --git a/evals/model-apps/routing/tests/run-routing.test.js b/evals/model-apps/routing/tests/run-routing.test.js
new file mode 100644
index 000000000..f12f7815d
--- /dev/null
+++ b/evals/model-apps/routing/tests/run-routing.test.js
@@ -0,0 +1,305 @@
+'use strict';
+// Runner tests for run-routing.js. Two seams:
+// * runRouting(opts, { runTrial }) with canned trials — TAP shape, thresholds, exit codes,
+// --compare deltas, --out JSON — without launching anything;
+// * spawnTrial() against tests/fake-agent.js — the real process plumbing: prompt on stdin,
+// streaming parse, kill-on-decision, crash/timeout/isolation errors.
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const { parseArgs, runRouting, spawnTrial, DEFAULTS } = require('../run-routing.js');
+
+const RUNNER = path.join(__dirname, '..', 'run-routing.js');
+const FAKE = path.join(__dirname, 'fake-agent.js');
+const PLUGIN = { pluginName: 'model-apps', pluginSkills: ['app-builder', 'genpage', 'report-issue', 'telemetry'] };
+const EVALS = { evals: [
+ { id: 1, tier: 'smoke', prompt: 'page please', expect: 'genpage' },
+ { id: 2, tier: 'smoke', prompt: 'power pages site', expect: null, trap: 'bleed' },
+ { id: 3, tier: 'full', prompt: 'whole app', expect: 'app-builder' },
+] };
+
+function parse(argv) {
+ const errors = [];
+ try {
+ return { args: parseArgs(argv, { fail: (m) => { errors.push(m); throw new Error('__fail__'); } }), errors };
+ } catch (e) {
+ if (e.message !== '__fail__') throw e;
+ return { args: null, errors };
+ }
+}
+
+// ---------- argument parsing ----------
+
+test('parseArgs: defaults and valid flags', () => {
+ assert.deepEqual(parse([]).args, DEFAULTS);
+ const { args } = parse(['--agent', 'copilot', '--runs', '5', '--threshold', '0.8', '--tier', 'stress', '--eval', '0', '--dry-run']);
+ assert.equal(args.agent, 'copilot');
+ assert.equal(args.runs, 5);
+ assert.equal(args.threshold, 0.8);
+ assert.equal(args.tier, 'stress');
+ assert.equal(args.eval, 0);
+ assert.equal(args.dryRun, true);
+ assert.equal(DEFAULTS.threshold, 2 / 3, 'the default is the exact fraction, not a rounded 0.67');
+ const frac = parse(['--threshold', '3/4']).args;
+ assert.equal(frac.threshold, 0.75);
+ assert.equal(frac.thresholdLabel, '3/4');
+ assert.equal(parse(['--threshold', '1']).args.threshold, 1);
+});
+
+test('parseArgs: rejects typos and value-less or out-of-range values instead of defaulting', () => {
+ for (const argv of [['--agent', 'gemini'], ['--runs', '0'], ['--runs'], ['--threshold', '1.5'], ['--threshold', '0'],
+ ['--threshold', 'abc'], ['--threshold', '4/3'], ['--threshold', '0/3'], ['--threshold', '2/0'],
+ ['--tier', 'smoek'], ['--eval', '1.5'], ['--timeout', '--runs'], ['--runz', '3'],
+ ['--model', 'gpt%PATH%'], ['--model', 'a b'], ['--model', 'x&calc']]) {
+ const { args, errors } = parse(argv);
+ assert.equal(args, null, `${argv.join(' ')} must be rejected`);
+ assert.ok(errors.length, argv.join(' '));
+ }
+});
+
+// ---------- runRouting with canned trials ----------
+
+function collect() {
+ const lines = [];
+ return { write: (l) => lines.push(l), text: () => lines.join('\n') };
+}
+
+const canned = (byId) => async (_opts, c) => byId[c.id].shift();
+
+test('runRouting: all cases at threshold → exit 0, TAP per case, results JSON written', async () => {
+ const out = collect();
+ const file = path.join(os.tmpdir(), `routing-results-${process.pid}.json`);
+ try {
+ const { exitCode, results } = await runRouting({ ...DEFAULTS, runs: 3, out: file }, {
+ evalsData: EVALS, plugin: PLUGIN, write: out.write,
+ runTrial: canned({
+ 1: [{ routedTo: 'genpage' }, { routedTo: 'genpage' }, { routedTo: null }],
+ 2: [{ routedTo: null, result: { costUsd: 0.01 } }, { routedTo: null }, { routedTo: null }],
+ 3: [{ routedTo: 'app-builder' }, { routedTo: 'app-builder' }, { routedTo: 'app-builder' }],
+ }),
+ });
+ assert.equal(exitCode, 0, out.text());
+ assert.match(out.text(), /^ok 1 - #1 \[smoke\] expect genpage — 2\/3 \(genpage×2, none×1\)$/m);
+ assert.match(out.text(), /^ok 2 - #2 \[smoke\] expect none — 3\/3/m);
+ assert.match(out.text(), /^# cases 3 \(pass 3, fail 0, error 0\)$/m);
+ assert.match(out.text(), /^# cost >= \$0\.01 /m);
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
+ assert.equal(saved.cases.length, 3);
+ assert.equal(saved.cases[0].rate, 2 / 3);
+ assert.ok(saved.descriptions.genpage && saved.descriptions['app-builder'], 'records a description fingerprint per skill');
+ assert.deepEqual(results.summary.pass, 3);
+ } finally {
+ fs.rmSync(file, { force: true });
+ }
+});
+
+test('runRouting: a case under threshold → exit 1 with prompt + trap in the YAML block', async () => {
+ const out = collect();
+ const { exitCode } = await runRouting({ ...DEFAULTS, runs: 2, tier: 'smoke' }, {
+ evalsData: EVALS, plugin: PLUGIN, write: out.write,
+ runTrial: canned({ 1: [{ routedTo: 'genpage' }, { routedTo: 'genpage' }], 2: [{ routedTo: 'genpage' }, { routedTo: null }] }),
+ });
+ assert.equal(exitCode, 1);
+ assert.match(out.text(), /^not ok 2 - #2 \[smoke\] expect none — 1\/2/m);
+ assert.match(out.text(), /prompt: "power pages site"/);
+ assert.match(out.text(), /trap: "bleed"/);
+ assert.doesNotMatch(out.text(), /#3/, '--tier filters cases');
+});
+
+test('runRouting: every trial of a case errored → exit 2 (harness error, not a routing verdict)', async () => {
+ const out = collect();
+ const { exitCode } = await runRouting({ ...DEFAULTS, runs: 1, eval: 1 }, {
+ evalsData: EVALS, plugin: PLUGIN, write: out.write,
+ runTrial: async () => ({ routedTo: null, error: 'claude exited 1 before any routing decision' }),
+ });
+ assert.equal(exitCode, 2);
+ assert.match(out.text(), /error: "claude exited 1/);
+});
+
+test('runRouting: --compare prints a delta only for cases whose pass rate moved', async () => {
+ const prev = path.join(os.tmpdir(), `routing-prev-${process.pid}.json`);
+ fs.writeFileSync(prev, JSON.stringify({ cases: [{ id: 1, rate: 1 }, { id: 2, rate: 1 }] }));
+ try {
+ const out = collect();
+ await runRouting({ ...DEFAULTS, runs: 1, tier: 'smoke', compare: prev }, {
+ evalsData: EVALS, plugin: PLUGIN, write: out.write,
+ runTrial: canned({ 1: [{ routedTo: null }], 2: [{ routedTo: null }] }),
+ });
+ assert.match(out.text(), /^# delta #1: 1\.00 → 0\.00$/m);
+ assert.doesNotMatch(out.text(), /# delta #2/);
+ } finally {
+ fs.rmSync(prev, { force: true });
+ }
+});
+
+test('runRouting: invalid evals.json or an empty filter → exit 2 before any trial', async () => {
+ let launched = 0;
+ const runTrial = async () => { launched += 1; return { routedTo: null }; };
+ const bad = await runRouting({ ...DEFAULTS }, { evalsData: { evals: [{ id: 1, prompt: 'x', expect: 'nope' }] }, plugin: PLUGIN, write: () => {}, runTrial });
+ assert.equal(bad.exitCode, 2);
+ const none = await runRouting({ ...DEFAULTS, eval: 99 }, { evalsData: EVALS, plugin: PLUGIN, write: () => {}, runTrial });
+ assert.equal(none.exitCode, 2);
+ assert.equal(launched, 0);
+});
+
+test('CLI --dry-run prints the isolated invocation and launches nothing', () => {
+ const r = spawnSync(process.execPath, [RUNNER, '--dry-run', '--tier', 'smoke', '--agent', 'copilot'], { encoding: 'utf8' });
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stdout, /# dry run — would launch \d+ case\(s\) × 3 trial\(s\)/);
+ assert.match(r.stdout, /copilot .*--plugin-dir .*--available-tools skill view glob grep/);
+});
+
+// ---------- spawnTrial against a fake agent (real process plumbing) ----------
+
+function fakeTrial(mode, { prompt = 'build me a page', timeoutMs = 20000, agent = 'claude', env = {}, loadedSkills, loadError } = {}) {
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-fake-'));
+ return spawnTrial({
+ agent, bin: process.execPath, binArgs: [FAKE], args: [], env: { FAKE_AGENT_MODE: mode, ...env },
+ prompt, cwd, timeoutMs, plugin: PLUGIN, loadedSkills, loadError,
+ }).finally(() => fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
+}
+
+test('spawnTrial: a FAILED terminal result is an error, never a "none" decision (both CLIs, any exit code)', async () => {
+ // Graded as "none", a run that crashed after printing its result would pass every negative
+ // case. Exit 1 is caught by the exit-code check; exit 0 proves the failed RESULT is caught alone.
+ for (const exit of ['1', '0']) {
+ const claude = await fakeTrial('claude-failed', { agent: 'claude', env: { FAKE_AGENT_EXIT: exit } });
+ assert.equal(claude.routedTo, null);
+ assert.match(claude.error || '', exit === '1' ? /exited 1 before any routing decision/ : /claude result error_during_execution \(is_error\) before any routing decision/, `claude exit ${exit}`);
+ const copilot = await fakeTrial('copilot-failed', { agent: 'copilot', env: { FAKE_AGENT_EXIT: exit } });
+ assert.equal(copilot.routedTo, null);
+ assert.match(copilot.error || '', exit === '1' ? /exited 1 before any routing decision/ : /copilot result exitCode 1 before any routing decision/, `copilot exit ${exit}`);
+ }
+ // A successful run that answers in text is still the legitimate "none".
+ const ok = await fakeTrial('answer');
+ assert.equal(ok.error, null);
+});
+
+test('spawnTrial: prompt reaches the agent on stdin; a routed agent is killed at the decision', async () => {
+ const t = await fakeTrial('route-then-hang', { prompt: 'make me an app' });
+ assert.equal(t.routedTo, 'app-builder', 'the fake routes on the prompt text, proving stdin delivery');
+ assert.equal(t.error, null);
+ assert.equal(t.timedOut, false);
+ assert.ok(t.durationMs < 15000, `should stop at the decision, took ${t.durationMs}ms`);
+});
+
+test('spawnTrial: a text answer ends the run as a "none" decision', async () => {
+ const t = await fakeTrial('answer');
+ assert.equal(t.routedTo, null);
+ assert.equal(t.error, null);
+ assert.equal(t.result.costUsd, 0.001);
+});
+
+test('spawnTrial: exiting non-zero before any decision is an error carrying the stderr tail', async () => {
+ const t = await fakeTrial('crash');
+ assert.match(t.error, /exited 3 before any routing decision: Error: not signed in/);
+});
+
+test('spawnTrial: the plugin missing from the init skill list is an error, not a passing "none"', async () => {
+ const t = await fakeTrial('no-plugin');
+ assert.match(t.error, /plugin skills not loaded: app-builder, genpage/);
+});
+
+test('spawnTrial: a silent agent is killed at the timeout and reported as an error, not a "none"', async () => {
+ // Graded as `none`, a hung CLI would pass every negative case — a harness failure must read
+ // as a harness failure.
+ const t = await fakeTrial('hang', { timeoutMs: 1500 });
+ assert.equal(t.timedOut, true);
+ assert.equal(t.routedTo, null);
+ assert.match(t.error, /timed out with no transcript output/);
+});
+
+test('spawnTrial: a timeout AFTER transcript output is still an error, never a "none" decision', async () => {
+ // The gap a silent-agent test alone misses: Claude always streams an init event (and Copilot
+ // message deltas) before deciding, so "any output" must not turn a cut-off run into "none".
+ const t = await fakeTrial('init-then-hang', { timeoutMs: 1500 });
+ assert.equal(t.timedOut, true);
+ assert.equal(t.routedTo, null);
+ assert.match(t.error, /timed out before routing \(1 transcript events, no decision\)/);
+});
+
+test('spawnTrial: an absolute .cmd shim is launched through the shell (Windows)', { skip: process.platform !== 'win32' }, async () => {
+ // npm installs agent CLIs as .cmd shims on Windows, and Node refuses to spawn a batch file
+ // without a shell (EINVAL). The directory has a space in it to exercise command quoting.
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'routing shim '));
+ const shim = path.join(dir, 'agent.cmd');
+ fs.writeFileSync(shim, `@"${process.execPath}" "${FAKE}" %*\r\n`);
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-fake-'));
+ try {
+ const t = await spawnTrial({
+ agent: 'claude', bin: shim, args: [], env: { FAKE_AGENT_MODE: 'route-then-hang' },
+ prompt: 'build me a page', cwd, timeoutMs: 20000, plugin: PLUGIN,
+ });
+ assert.equal(t.error, null);
+ assert.equal(t.routedTo, 'genpage');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ }
+});
+
+test('frontmatterDescription: inline and folded block descriptions both hash their real text', () => {
+ const { frontmatterDescription, descriptionFingerprint } = require('../run-routing.js');
+ assert.equal(frontmatterDescription('---\nname: a\ndescription: Builds pages.\nuser-invocable: true\n---\nbody'), 'Builds pages.');
+ assert.equal(
+ frontmatterDescription('---\nname: t\ndescription: >\n Use this skill when\n telemetry is mentioned.\nuser-invocable: true\n---\n'),
+ 'Use this skill when telemetry is mentioned.',
+ );
+ assert.equal(frontmatterDescription('no frontmatter'), '');
+ const fp = descriptionFingerprint();
+ // The folded descriptions (report-issue, telemetry) used to hash the literal ">", so two
+ // different skills shared one fingerprint. Every skill's fingerprint must now be distinct.
+ assert.equal(new Set(Object.values(fp)).size, Object.keys(fp).length, JSON.stringify(fp));
+});
+
+test('spawnTrial: a missing executable resolves with an error instead of throwing', async () => {
+ const t = await spawnTrial({
+ agent: 'claude', bin: path.join(os.tmpdir(), 'definitely-not-an-agent.exe'), args: [], env: {},
+ prompt: 'x', cwd: os.tmpdir(), timeoutMs: 5000, plugin: PLUGIN,
+ });
+ assert.match(t.error, /could not start|exited/);
+});
+
+// ---------- Copilot skill-load preflight ----------
+
+const { copilotSkillInventory } = require('../run-routing.js');
+
+function inventory(shape) {
+ const pluginDir = path.join(os.tmpdir(), 'fake plugin dir', 'model-apps');
+ return copilotSkillInventory({ bin: process.execPath, binArgs: [FAKE], pluginDir, env: { FAKE_SKILL_LIST: shape }, cwd: os.tmpdir() });
+}
+
+test('copilotSkillInventory: plugin skills come from the plugin dir; builtins are neither loaded-plugin nor leaks', () => {
+ const inv = inventory('ok');
+ assert.deepEqual(inv.names, ['app-builder', 'genpage', 'report-issue', 'telemetry']);
+ assert.deepEqual(inv.leaks, []);
+ assert.equal(inv.error, undefined);
+});
+
+test('copilotSkillInventory: missing plugin skills, a leaked personal skill, and a failed or garbled listing', () => {
+ assert.deepEqual(inventory('missing').names, []);
+ assert.deepEqual(inventory('leak').leaks, ['brainstorming (personal)']);
+ assert.match(inventory('broken').error, /could not verify Copilot skill loading \(`skill list` exit 2\): Error: not signed in/);
+ assert.match(inventory('garbage').error, /unparseable output/);
+});
+
+test('spawnTrial(copilot): a successful text answer with the plugin skills NOT loaded is an error, not a "none"', async () => {
+ // The case Copilot's transcript cannot reveal: without the preflight inventory this run would
+ // grade as a clean "none" and pass every negative case.
+ const t = await fakeTrial('copilot-answer', { agent: 'copilot', loadedSkills: ['customize-cloud-agent'] });
+ assert.match(t.error || '', /plugin skills not loaded: app-builder, genpage, report-issue, telemetry/);
+ const ok = await fakeTrial('copilot-answer', { agent: 'copilot', loadedSkills: ['app-builder', 'genpage', 'report-issue', 'telemetry'] });
+ assert.equal(ok.error, null);
+ assert.equal(ok.routedTo, null);
+});
+
+test('spawnTrial: a preflight loadError fails the trial without launching the agent', async () => {
+ const t = await fakeTrial('route-then-hang', { agent: 'copilot', loadError: 'isolation leak: skills from outside the plugin are loaded: brainstorming (personal)' });
+ assert.match(t.error, /isolation leak/);
+ assert.equal(t.stdout, '', 'nothing was spawned');
+ assert.equal(t.routedTo, null);
+});
\ No newline at end of file
diff --git a/evals/model-apps/routing/tests/transcripts/claude-genpage.jsonl b/evals/model-apps/routing/tests/transcripts/claude-genpage.jsonl
new file mode 100644
index 000000000..6019b5149
--- /dev/null
+++ b/evals/model-apps/routing/tests/transcripts/claude-genpage.jsonl
@@ -0,0 +1,5 @@
+{"type":"system","subtype":"init","cwd":"/tmp/ws","session_id":"00000000-0000-0000-0000-000000000000","tools":["Glob","Grep","Read","Skill"],"skills":["model-apps:app-builder","model-apps:genpage","model-apps:report-issue","model-apps:telemetry","design"],"plugins":[{"name":"model-apps","path":"/repo/plugins/model-apps","source":"model-apps@inline","version":"2.9.0"}]}
+{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"I'll use the generative pages skill for this."}]}}
+{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"Skill","input":{"skill":"model-apps:genpage","args":"Add a generative page to my existing Sales Hub app."}}]}}
+{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"Launching skill: model-apps:genpage"}]}}
+{"type":"result","subtype":"success","num_turns":2,"total_cost_usd":0.0123}
diff --git a/evals/model-apps/routing/tests/transcripts/copilot-app-builder.jsonl b/evals/model-apps/routing/tests/transcripts/copilot-app-builder.jsonl
new file mode 100644
index 000000000..25a161aac
--- /dev/null
+++ b/evals/model-apps/routing/tests/transcripts/copilot-app-builder.jsonl
@@ -0,0 +1,8 @@
+{"type":"session.tools_updated","data":{"model":"claude-sonnet-5.5"}}
+{"type":"user.message","data":{"content":"Build me a model-driven app to manage equipment rentals."}}
+{"type":"assistant.turn_start","data":{"turnId":"0"}}
+{"type":"assistant.tool_call_delta","data":{"toolCallId":"toolu_02","toolName":"skill","inputDelta":"{\"skill\": \"app-"}}
+{"type":"assistant.message","data":{"messageId":"m1","content":"","toolRequests":[{"toolCallId":"toolu_02","name":"skill","arguments":{"skill":"app-builder"}}]}}
+{"type":"tool.execution_start","data":{"toolCallId":"toolu_02","toolName":"skill","arguments":{"skill":"app-builder"}}}
+{"type":"tool.execution_complete","data":{"toolCallId":"toolu_02","success":true}}
+{"type":"result","exitCode":0,"usage":{"premiumRequests":1}}
diff --git a/evals/model-apps/routing/tests/transcripts/copilot-none.jsonl b/evals/model-apps/routing/tests/transcripts/copilot-none.jsonl
new file mode 100644
index 000000000..4fa8bf5bd
--- /dev/null
+++ b/evals/model-apps/routing/tests/transcripts/copilot-none.jsonl
@@ -0,0 +1,4 @@
+{"type":"user.message","data":{"content":"Build a Power Pages site where customers can submit warranty claims."}}
+{"type":"assistant.message_delta","data":{"messageId":"m1","deltaContent":"Power Pages"}}
+{"type":"assistant.message","data":{"messageId":"m1","content":"Power Pages sites are built with the Power Pages tooling, not the model-apps skills.","toolRequests":[]}}
+{"type":"result","exitCode":0,"usage":{"premiumRequests":1}}
diff --git a/evals/model-apps/tests/eval-coverage-baseline.json b/evals/model-apps/tests/eval-coverage-baseline.json
index bbdbcc602..08c4d675e 100644
--- a/evals/model-apps/tests/eval-coverage-baseline.json
+++ b/evals/model-apps/tests/eval-coverage-baseline.json
@@ -11,122 +11,23 @@
"eval null is a common assertion. reason is the SKIP reason the check gives."
],
"genpage": {
- "uncaptured": [
- {
- "eval": 3,
- "reason": "Edit flow: needs a /genpage run that edits a page already deployed in an app."
- },
- {
- "eval": 6,
- "reason": "Mock-data analytics dashboard: no run captured yet."
- },
- {
- "eval": 8,
- "reason": "Needs a run in an environment with no model-driven app, so /genpage creates one."
- },
- {
- "eval": 9,
- "reason": "New tables with related sample data: no run captured yet."
- },
- {
- "eval": 12,
- "reason": "Plan revision: needs a run where the user asks for a change at plan approval."
- },
- {
- "eval": 14,
- "reason": "Filename collision: needs a run whose first plan gives two pages the same file name."
- },
- {
- "eval": 16,
- "reason": "Minimal existing-table page: no run captured yet."
- }
- ],
+ "uncaptured": [],
"unscored": [
- {
- "eval": 2,
- "status": "deferred",
- "text": "Phase 1 (Planner): Data source question is skipped or answered 'mock data' — no entity detection needed"
- },
{
"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 1a: Apps are presented to the user via AskUserQuestion using the actual Display Name and app-id GUID from pac model list output"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 1b: Pages are presented to the user via AskUserQuestion using the actual page names and page-id GUIDs from pac model genpage list output"
- },
{
"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": "deferred",
- "text": "Edit Phase 1c: Selection is restated to the user before proceeding to download"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 3: config.json is read; since dataSources contains 'contact', RuntimeTypes.ts is generated"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 4: edit-planner reads page.tsx, config.json, and prompt.txt from the <page-id>/ folder"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 5: Orchestrator reads genpage-edit-plan.md, rules.md, RuntimeTypes.ts, and page.tsx"
- },
- {
- "eval": 3,
- "status": "deferred",
- "text": "Edit Phase 5: Search implementation uses Fluent UI V9 SearchBox or Input; sort uses column header handlers"
- },
{
"eval": 3,
"status": "manual",
"text": "Edit Phase 5: Existing functionality is preserved per the edit plan's Preservation Constraints"
},
- {
- "eval": 4,
- "status": "deferred",
- "text": "Phase 1 (Planner): pac model list-tables --search 'incident,contact' is run; both entities confirmed as existing"
- },
- {
- "eval": 4,
- "status": "deferred",
- "text": "Phase 2: Entity-builder is SKIPPED"
- },
- {
- "eval": 4,
- "status": "deferred",
- "text": "Phase 4: pac model genpage generate-types --data-sources 'incident,contact' is run"
- },
- {
- "eval": 4,
- "status": "deferred",
- "text": "Phase 5 (Page Builder): Wizard sample (2-wizard-multi-step.tsx) is read"
- },
{
"eval": 4,
"status": "manual",
@@ -137,166 +38,16 @@
"status": "manual",
"text": "Phase 5 (Page Builder): Step 3 (review) shows a summary of entered data before submission"
},
- {
- "eval": 4,
- "status": "deferred",
- "text": "Phase 6: Upload includes --data-sources 'incident,contact'"
- },
- {
- "eval": 5,
- "status": "deferred",
- "text": "Phase 1 (Planner): task entity confirmed as existing; plan describes kanban with 3 columns mapped to task statecode/statuscode values"
- },
- {
- "eval": 5,
- "status": "deferred",
- "text": "Phase 4: RuntimeTypes.ts is read — status field enum values are identified for column mapping"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 1 (Planner): pac model list-tables --search confirms cr_candidate and cr_jobrequisition do NOT exist (exact logical-name match, not fuzzy)"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes entity definitions with columns, types, and a lookup relationship (cr_candidate → cr_jobrequisition)"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 1 (Planner): Because entities will be created, the planner asks the solution selection question via AskUserQuestion and records the choice in ## Environment as 'Solution: <uniqueName>' and 'Publisher Prefix: <prefix>'"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Reads Solution + Publisher Prefix from the plan's ## Environment"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): cr_jobrequisition (independent) is provisioned before cr_candidate (has lookup) to satisfy dependency ordering"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): provision-entities.js handles entity creation and column definitions atomically with internal propagation management"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Lookup relationship (cr_candidate → cr_jobrequisition) is provisioned via input JSON; provision-entities.js handles propagation internally"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): User is asked about sample data via AskUserQuestion"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js input JSON; parent references use $parent/match convention for dependency resolution"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Actual logical names are reported back (may be normalized by Dataverse); a transaction log at <working-dir>/genpage-entity-creation-log.md captures each successful operation"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 4: pac model genpage generate-types is run with the created entity names"
- },
- {
- "eval": 7,
- "status": "deferred",
- "text": "Phase 6: Upload includes --data-sources with both created entity names"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 1 (Planner): pac model list returns zero apps"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 1 (Planner): User is asked via AskUserQuestion whether to create a new app or cancel"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan records 'create new app' decision"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 1 (Planner): Because a new app will be created, the planner asks the solution selection question and records the choice in ## Environment"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 3: The new app-id returned from pac model create is stored for Phase 6"
- },
- {
- "eval": 8,
- "status": "deferred",
- "text": "Phase 6: Upload uses the newly created app-id"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 1 (Planner): cr_project and cr_milestone confirmed as NOT existing"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes a lookup relationship (cr_milestone → cr_project)"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 1 (Planner): Solution selection question is asked because new entities will be created"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): cr_project and cr_milestone entities are provisioned with lookup relationship (cr_milestone → cr_project) via provision-entities.js; dependency ordering is handled automatically"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Sample data is created because the user explicitly requested it in the prompt"
- },
{
"eval": 9,
"status": "manual",
"text": "Phase 2b (Entity Builder): Sample data is provisioned via provision-entities.js; realistic values (not lorem ipsum)"
},
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Sample records respect relationships (milestones reference projects via $parent/match convention)"
- },
- {
- "eval": 9,
- "status": "deferred",
- "text": "Phase 6: Deployment includes --data-sources with both entity names"
- },
{
"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 1 (Planner): Plan records cr_widget under Entity Creation Required"
- },
- {
- "eval": 10,
- "status": "deferred",
- "text": "Phase 2a: Orchestrator runs scripts/check-auth.js BEFORE invoking entity-builder; parses the returned JSON"
- },
{
"eval": 10,
"status": "deferred",
@@ -307,255 +58,20 @@
"status": "deferred",
"text": "Phase 2a: If ok:true but identitiesMatch:false, orchestrator proceeds but surfaces a one-line warning"
},
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes 3 pages in the Pages table with distinct file names and purposes"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 1 (Planner): Per-Page Specifications section has an entry for each of the 3 pages"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 5a: Orchestrator validates the plan — at least one page, unique filenames, each page has a matching Per-Page Specifications subsection"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 4: pac model genpage generate-types is run ONCE with --data-sources 'contact,appointment'; a single RuntimeTypes.ts is generated"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 5c: Each builder receives a distinct target filename — no two builders target the same file"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 5c: Each builder reads the same genpage-plan.md but extracts only its own page specification"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 5c: Each builder reads the same RuntimeTypes.ts for column verification"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 5c: Cross-page navigation (e.g., candidate list → candidate detail) uses quoted `\"PAGEREF_<filename>\"` placeholders, never invented GUIDs"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 6: All 3 pages are deployed via separate pac model genpage upload commands, each with the correct --code-file"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 6.5: If any .tsx contains PAGEREF_ tokens, orchestrator builds a filename→page-id map sorted by length desc, replaces quoted `\"PAGEREF_<name>\"` tokens with the matching GUID (word-boundary safe), and re-uploads only affected files with the full update flag set"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 6.5: Re-upload uses a DELTA --prompt (e.g. 'Resolve cross-page navigation placeholders to real page GUIDs') — NOT a copy of the original page description from Phase 6"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 6.5: Unresolved PAGEREF tokens (typos, missing siblings) cause an explicit error to the user — never silently shipped"
- },
- {
- "eval": 11,
- "status": "deferred",
- "text": "Phase 8: Summary table lists all 3 pages with their files, entities, and deployment status"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): Initial plan is presented via EnterPlanMode"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): User requests a revision (ExitPlanMode with changes-requested response)"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): Planner revises the plan based on user feedback and re-enters plan mode"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): Revised plan reflects the user's requested changes (search box added)"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): User approves the revised plan on the second presentation"
- },
- {
- "eval": 12,
- "status": "deferred",
- "text": "Phase 1 (Planner): genpage-plan.md reflects the approved (revised) version, not the initial version"
- },
{
"eval": 12,
"status": "manual",
"text": "Phase 5 (Page Builder): Generated code implements the revised plan (includes BOTH filter toolbar AND search box)"
},
- {
- "eval": 13,
- "status": "deferred",
- "text": "Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English"
- },
- {
- "eval": 13,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes a Localization section listing detected languages"
- },
{
"eval": 13,
"status": "deferred",
"text": "Phase 5 (Page Builder): Generated .tsx fetches usersettings via dataApi.retrieveRow and uses formatDate/formatNumber/formatCurrency helpers"
},
- {
- "eval": 13,
- "status": "deferred",
- "text": "Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan initially contains a Pages table with 2 pages"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 5a: Orchestrator reads the Pages table and detects duplicate filenames"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 5a: Orchestrator rewrites genpage-plan.md with unique filenames (e.g., account-list.tsx, account-edit.tsx) before dispatching builders"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 5b: Two page-builders are invoked in parallel with distinct target filenames"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 5b: No builder overwrites another builder's output (both .tsx files exist after Phase 5)"
- },
- {
- "eval": 14,
- "status": "deferred",
- "text": "Phase 6: Both pages are deployed with their distinct filenames"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 1 (Planner): cr_ticket is identified as NOT existing"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes choice column definitions for priority and status under Choice Columns, with numeric option values starting at 100000000"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 1 (Planner): Plan includes a datetime column for due date"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 1 (Planner): Solution selection question is asked (because new entity will be created) and recorded in ## Environment"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2a: scripts/check-auth.js returns ok:true before entity-builder is invoked"
- },
{
"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"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Priority picklist has 4 options starting at 100000000 (Low=100000000, Medium=100000001, High=100000002, Critical=100000003)"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Status picklist has 4 options starting at 100000000"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Solution is specified via provision-entities.js input JSON; verified through ## Environment → Solution: declaration"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 2b (Entity Builder): Transaction log (genpage-entity-creation-log.md) records each create with its returned metadataId"
- },
- {
- "eval": 15,
- "status": "deferred",
- "text": "Phase 4: pac model genpage generate-types picks up the enum registrations"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): genpage-plan.md is written and conforms to references/plan-schema.md"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): genpage-plan.md contains ALL required sections with exact headings: # Genpage Plan, ## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): ## Pages table has at least one row with columns Page, File, Purpose, Entities"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): ## Per-Page Specifications has one ### <Page Name> subsection for each row in ## Pages"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): File names in ## Pages are unique"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): Because the account entity exists, ## Entity Creation Required contains the literal string 'No entity creation required — all entities already exist.'"
- },
- {
- "eval": 16,
- "status": "deferred",
- "text": "Phase 1 (Planner): ## Existing Entities contains the entity logical name used for RuntimeTypes generation (account)"
- },
- {
- "eval": 19,
- "status": "deferred",
- "text": "Edit Phase 1b: After app selection, pac model genpage list --app-id <selected> is run to discover pages — orchestrator does NOT guess or invent page names"
- },
- {
- "eval": 19,
- "status": "deferred",
- "text": "Edit Phase 4: genpage-edit-plan.md is written to the working directory root (not inside <page-id>/)"
}
],
"neverGraded": [
@@ -618,6 +134,12 @@
"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"
+ },
+ {
+ "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"
}
]
},
diff --git a/evals/model-apps/tests/eval-coverage-contract.test.js b/evals/model-apps/tests/eval-coverage-contract.test.js
index 0fab1da31..e3a0887b9 100644
--- a/evals/model-apps/tests/eval-coverage-contract.test.js
+++ b/evals/model-apps/tests/eval-coverage-contract.test.js
@@ -162,7 +162,10 @@ function entityLogNameProblems({ docs, loaderName, legacyName, evalTexts }) {
return problems;
}
+// `**none**` is how a guide says the list is empty (every prompt captured); the regexes need a token
+// there, since `**` directly followed by `**` would read as bold markup rather than an empty list.
function parseIdList(text) {
+ if (/^\s*none\s*$/i.test(text)) return [];
return text.split(',').map((s) => s.trim()).filter(Boolean).flatMap((part) => {
const range = /^(\d+)\s*[–-]\s*(\d+)$/.exec(part);
if (!range) return [Number(part)];
@@ -213,7 +216,7 @@ function genpageGuideProblems(guide, facts) {
if (m) expect('common_code_assertions count', Number(m[1]), facts.codeCount);
m = find('the prompt definition count', /`evals`:\s*\*\*(\d+)\*\*\s+prompt definitions/);
if (m) expect('prompt definition count', Number(m[1]), facts.promptCount);
- m = find('the corpus sentence', /\*\*(\d+) fixture directories \/ (\d+) top-level TSX files\*\*,\s+representing (\d+) prompt IDs\.\s+IDs \*\*([\d,\s]+)\*\* have no fixture/);
+ m = find('the corpus sentence', /\*\*(\d+) fixture directories \/ (\d+) top-level TSX files\*\*,\s+representing (\d+) prompt IDs\.\s+IDs \*\*(none|[\d,\s]+)\*\* have no fixture/);
if (m) {
expect('fixture directory count', Number(m[1]), facts.fixtureDirs);
expect('top-level TSX count', Number(m[2]), facts.tsxFiles);
@@ -244,7 +247,7 @@ function genpageReadmeProblems(readme, facts) {
const actual = [facts.fixtureDirs, facts.tsxFiles, facts.representedIds];
if (JSON.stringify(said) !== JSON.stringify(actual)) problems.push(`fixtures/README.md counts: says ${JSON.stringify(said)}, actual ${JSON.stringify(actual)}`);
}
- const missing = /Registered prompts with no fixture:\s*\*\*([\d,\s]+)\*\*/.exec(readme);
+ const missing = /Registered prompts with no fixture:\s*\*\*(none|[\d,\s]+)\*\*/.exec(readme);
if (!missing) problems.push('fixtures/README.md: could not find the prompts with no fixture — update the README or this contract');
else if (JSON.stringify(parseIdList(missing[1])) !== JSON.stringify(facts.missingIds)) {
problems.push(`fixtures/README.md prompts with no fixture: says ${missing[1].trim()}, actual ${facts.missingIds.join(', ')}`);
@@ -390,11 +393,14 @@ test('the eval guides state the corpus as it is', () => {
test('negative controls: prompt, routing and registration drift is reported', () => {
const fixtureIds = new Set(genpageFixtures.map((f) => f.id));
const uncaptured = baseline.genpage.uncaptured;
- const [first] = uncaptured;
- assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: uncaptured.slice(1) }).join('\n'), new RegExp(`eval ${first.eval} has no fixture`));
- assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds: new Set([...fixtureIds, first.eval]), uncaptured }).join('\n'), /now has a fixture/);
+ // A synthetic prompt with no fixture, so these controls keep working when every real prompt is
+ // captured and the baseline's uncaptured list is empty.
+ const evalsPlus = [...genpageData.evals, { id: 9997, tier: 'full', prompt: 'x', expectations: [] }];
+ const first = { eval: 9997, reason: 'not captured yet' };
+ assert.match(uncapturedProblems({ evals: evalsPlus, fixtureIds, uncaptured }).join('\n'), /eval 9997 has no fixture/);
+ assert.match(uncapturedProblems({ evals: evalsPlus, fixtureIds: new Set([...fixtureIds, first.eval]), uncaptured: [...uncaptured, first] }).join('\n'), /now has a fixture/);
assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: [...uncaptured, { eval: 9999, reason: 'x' }] }).join('\n'), /no longer defines/);
- assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds, uncaptured: [{ ...first, reason: ' ' }, ...uncaptured.slice(1)] }).join('\n'), /needs a reason/);
+ assert.match(uncapturedProblems({ evals: evalsPlus, fixtureIds, uncaptured: [...uncaptured, { ...first, reason: ' ' }] }).join('\n'), /needs a reason/);
assert.match(uncapturedProblems({ evals: genpageData.evals, fixtureIds: new Set([...fixtureIds, 9998]), uncaptured }).join('\n'), /eval 9998, which evals.json does not define/);
const evals = structuredClone(genpageData.evals);
@@ -453,7 +459,7 @@ test('negative controls: entity-log and guide drift is reported', () => {
assert.match(genpageGuideProblems(guide, { ...facts, tiers: { ...facts.tiers, full: { ...facts.tiers.full, fixtures: facts.tiers.full.fixtures + 1 } } }).join('\n'), /--tier full stored fixtures/);
const readme = readText(path.join(GENPAGE, 'fixtures', 'README.md'));
assert.match(genpageReadmeProblems(readme, { ...facts, tsxFiles: facts.tsxFiles + 1 }).join('\n'), /counts: says/);
- assert.match(genpageReadmeProblems(readme, { ...facts, missingIds: [] }).join('\n'), /prompts with no fixture: says/);
+ assert.match(genpageReadmeProblems(readme, { ...facts, missingIds: [...facts.missingIds, 999] }).join('\n'), /prompts with no fixture: says/);
const appGuide = readText(path.join(APP_BUILDER, 'EVAL_GUIDE.md'));
const dirs = appBuilderFixtures.map((f) => f.dirName);
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 5869f9e95..4b58e53c6 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -1430,3 +1430,27 @@ reconcile, fail-closed), `process`, `generate-pages`, `teardown`, `round-trip` a
# From repo root:
node evals/model-apps/app-builder/run-app-builder.js
```
+
+### Skill routing — agent in the loop
+
+`evals/model-apps/routing/` grades which skill a real agent CLI (Copilot CLI or
+Claude Code, headless, isolated, only this plugin loaded) invokes for each of 20
+prompts: `/genpage` vs `/app-builder` from both sides of their boundary, plus
+negatives that share vocabulary (Power Pages, canvas, Power Automate, a generic
+React dashboard). The offline harnesses above grade what a run *produced* and
+cannot see a mis-route; both skill descriptions point at each other, so a
+wording change to one can start stealing the other's prompts. The agent is
+killed at its first plugin-skill call, so a trial costs about one model turn;
+cases are graded as a pass rate over N trials. **Run it when you edit a skill
+`description:`.** It is not a per-PR gate (cost, non-determinism):
+`model-apps-agent-evals.yml` runs it on a same-repo PR labelled
+`run-agent-evals`, weekly, and on demand, using Copilot CLI authenticated by the
+workflow's own `GITHUB_TOKEN` (`copilot-requests: write`) — no secret to
+provision. Its parsing/grading/process code is unit-tested on every PR against a
+fake agent. See [`evals/model-apps/routing/EVAL_GUIDE.md`](../../evals/model-apps/routing/EVAL_GUIDE.md).
+
+```bash
+node evals/model-apps/routing/run-routing.js --dry-run # what would launch
+node evals/model-apps/routing/run-routing.js --tier smoke --runs 1 # quick local check
+node evals/model-apps/routing/run-routing.js --out after.json --compare before.json
+```