A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
v2.2: Three Asks, eval suite, real captures, spec tightening (#172)
Akshay Malooc63949d95d96
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdnew file mode 100644index 000000000..edec07818--- /dev/null+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -0,0 +1,541 @@+# Eval Guide — Model Apps `/genpage`++Comprehensive guide to the `/genpage` evaluation suite. **What evals exist, how they're structured, how to run them, how to interpret results, and how to extend them.** Companion to the plugin's `docs/architecture.md` (system overview).++## Table of contents++1. [Related files](#related-files)+2. [What we evaluate](#what-we-evaluate)+3. [The three-layer grading model](#the-three-layer-grading-model)+4. [Eval data — `evals.json` structure](#eval-data)+5. [Eval tiers (smoke / full / stress)](#eval-tiers)+6. [Fixture types (synthetic vs real captures)](#fixture-types)+7. [Running the suite](#running-the-suite)+8. [Cadence — when to run](#cadence)+9. [Quick start — running one eval end-to-end](#quick-start)+10. [Reading runner output (TAP)](#reading-runner-output)+11. [Manual grep patterns (Layer 2 fallback)](#manual-grep-patterns)+12. [Pass / fail summary](#pass-fail-summary)+13. [Diagnosing failures (which agent owns what)](#diagnosing-failures)+14. [Capturing real fixtures from `/genpage`](#capturing-real-fixtures)+15. [Adding a new eval](#adding-a-new-eval)+16. [Adding a new assertion](#adding-a-new-assertion)+17. [Known-red fixtures and why they're allowed](#known-red-fixtures)++---++## Related files++- **Skill definition:** `plugins/model-apps/skills/genpage/SKILL.md`+- **Specialist agents:**+ - `plugins/model-apps/agents/genpage-planner.md`+ - `plugins/model-apps/agents/genpage-entity-builder.md`+ - `plugins/model-apps/agents/genpage-page-builder.md`+ - `plugins/model-apps/agents/genpage-edit-planner.md`+- **References:**+ - `plugins/model-apps/references/rules.md`+ - `plugins/model-apps/references/plan-schema.md`+ - `plugins/model-apps/references/troubleshooting.md`+- **Sample pages:** `plugins/model-apps/samples/1-account-grid.tsx` through `11-kanban-with-dnd.tsx`++---++## What we evaluate++`/genpage` is a multi-phase skill: orchestrator → planner → optional entity-builder → page-builder(s) → deploy → optional verify. Each phase has rules (auth must precede entity creation, plans must follow a schema, generated code must follow rules.md, etc.). The eval suite checks that the agent honors those rules end-to-end.++Three kinds of failure we want to catch:++| Failure class | Example | Where it shows up |+|---|---|---|+| **Workflow drift** | Planner skipped the AskUserQuestion for new-vs-edit | Layer 1 (workflow-log + plan grading) |+| **Code-gen drift** | Generated `.tsx` uses `<FluentProvider>` wrapper or `100vh` | Layer 2 (`.tsx` static analysis) |+| **UX drift** | Layout cramped, lookups show raw GUIDs instead of names | Layer 3 (manual UX rubric) |++Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual quality is genuinely hard to grade with regex.++---++## The three-layer grading model++### Layer 1 — Workflow assertions++**Input:** `workflow-log.md`, `genpage-plan.md`, optionally `genpage-edit-plan.md` and `entity-creation-log.md`.++**What it checks:**+- Prereq commands ran (`node --version`, `pac help` with version ≥ 2.7.0)+- `pac auth list` ran and the active env was reported+- `AskUserQuestion` was used (or new-page intent was inferable from a `## Pages` section in the plan)+- Plan was presented via `EnterPlanMode` and approved+- Plan conforms to `references/plan-schema.md` (all required `##` headings)+- `## Environment` contains `Solution:` and `Publisher Prefix:` lines+- Solution-selection question runs when (and only when) metadata work is needed+- `check-auth.js` runs before `entity-builder` when entities need creating+- `pac model genpage upload` invocations include `--prompt` with correct scoping+- Prefix discipline holds across plan, entity-creation log, and resolved names++**Runner:** `evals/model-apps/genpage/run-layer-1.js`+**Library:** `lib/assertions-layer-1.js` (one check function per assertion text)++### Layer 2 — Code-quality assertions++**Input:** every `.tsx` file in the fixture (excluding `RuntimeTypes.ts`).++**What it checks** (against `common_code_assertions` in `evals.json`):+- Single file with `export default GeneratedComponent`+- `pageInput` is destructured from props (even on mock pages)+- Either `./RuntimeTypes` import (Dataverse) or realistic inline mock data+- `makeStyles` + `tokens` (no inline styles for static values)+- **No** `100vh` / `100vw` / `createTheme` / `mergeThemes` / `useTheme` / `<FluentProvider>`+- **No** `window.location` / `react-router` / raw `pagetype=` URLs+- `Xrm.Navigation.navigateTo` (or `xrm?.Navigation?.navigateTo` via a typed `(window as any).Xrm` alias) for in-app nav+- Unsized Fluent icons only (e.g., `AddRegular`, not `Add24Regular`)+- Every icon name in `@fluentui/react-icons` imports appears in `references/verified-icons.txt`+- `try`/`catch` around `await dataApi.*` (Dataverse pages)+- No `TODO`/`FIXME`/`...` placeholders+- Lookup fields use `@OData.Community.Display.V1.FormattedValue` annotations+- `<DataGrid>` usage imports `createTableColumn` + configures `columnSizingOptions` or `resizableColumns`+- Multi-page builds use quoted `"PAGEREF_<filename>"` placeholders for cross-page nav++Plus per-eval `expectations` whose text starts with `Phase 5` (page-builder-specific).++**Runner:** `evals/model-apps/genpage/run-layer-2.js`+**Library:** `lib/assertions-layer-2.js`++### Layer 3 — UX rubric (manual)++**Input:** the deployed page rendered in the browser.++**What it checks** (against a 5-category, 2-point-each rubric):++| Category | 2 points | 1 point | 0 points |+|----------|----------|---------|----------|+| Workflow | All phases ran correctly | Minor deviation | Phase skipped |+| Code | Clean, all rules followed | 1-2 minor violations | JS errors or major rule violations |+| Visual | Polished, good spacing, Fluent tokens | Decent but cramped or inconsistent | Broken layout |+| Data | All fields correct, lookups resolved | Some missing or showing raw IDs | Blank or wrong data |+| Design | Right visual for the data, accessible | Reasonable but suboptimal | Wrong visual type |++**Pass criteria:** average score ≥ 8.5/10 across pages; no page below 7.++**Not automated** — visual regression testing is a separate, expensive problem and out of scope for v2.2.++---++## Eval data++All eval definitions live in `evals.json` alongside this file. The file contains:++- `common_workflow_assertions`: 15 workflow checks every run must pass (prereqs, auth, solution selection gating, check-auth pre-flight, plan creation, workflow log, `--prompt` scoping, prefix discipline at plan-format / resolved-names / solution-alignment).+- `common_code_assertions`: 18 code-quality checks the generated `.tsx` must pass (Fluent UI V9 only, no forbidden patterns, etc.).+- `evals`: 16 test cases — each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.++The `data` field specifies the user answers and environment state the eval assumes. During manual eval runs, the human grader role-plays this data. During automated runs, the eval harness provides these responses to `AskUserQuestion`.++---++## Eval tiers++Each eval in `evals.json` has a `tier` field for selective execution.++| Tier | Count | When to run | Eval IDs |+|------|------|-------------|----------|+| `smoke` | 4 | **Every PR** that touches the skill, agents, rules, or evals | 1, 2, 3, 16 |+| `full` | 9 | Nightly or pre-release; covers core workflows | 4, 5, 6, 7, 8, 9, 11, 13, 15 |+| `stress` | 3 | With full suite; edge cases (auth blockers, plan revisions, filename collisions) | 10, 12, 14 |++**Recommended cadence:**++- Smoke tier on every PR (~30 seconds)+- Full + smoke nightly (~2 minutes)+- All three tiers before bumping the plugin version (`v2.x.0` release)++Run a single tier:++```bash+node run-layer-1.js --tier smoke+node run-layer-2.js --tier smoke+```++---++## Fixture types++A fixture is a folder under `fixtures/<eval-id>-<slug>/` containing the artifacts a `/genpage` run would produce. The runner doesn't drive `/genpage` itself — it grades pre-captured outputs.++### Synthetic fixtures++Hand-built v2.x-compliant artifacts. Built from samples + hand-crafted workflow-log + plan. They serve as **green-path regression tests** — if a runner change accidentally rejects a known-good fixture, we know the change is wrong.++Pros: deterministic, fast to build, no Dataverse dependency, fully under our control.+Cons: can't catch agent drift (the synthetic fixture is what we *want* the agent to produce, not what it *does*).++### Real captures++Output from real `/genpage` sessions, captured via `scripts/capture-fixture.js`. These validate the runner against actual agent behavior.++Pros: catch agent drift, validate that the spec produces the expected output, surface edge cases the synthetic fixtures missed.+Cons: require a working Dataverse env + interactive session, slower to produce, can become stale when rules tighten.++### Both together++The suite ships both kinds:++| Eval | Synthetic fixture | Real capture |+|-----:|-------------------|---------------|+| 1 | `1-account-card-gallery` | — |+| 2 | `2-mock-dashboard` | `2-mock-dashboard-real` (pre-v2.2-spec — see [known-red](#known-red-fixtures)) |+| 4 | `4-case-wizard` | — |+| 5 | — | `5-kanban-task-board` (pre-v2.2-spec — see [known-red](#known-red-fixtures)) |+| 7 | `7-job-candidates-new-entities` | — |+| 11 | `11-recruitment-multi-page` | `11-recruitment-pages-real` (v2.2-spec, ✓ green) |+| 13 | `13-contact-localization` | — |+| 15 | — | `15-support-tickets-real` (v2.2-spec, ✓ green) |++The mix gives:+- A **green baseline** to catch runner regressions (synthetics)+- **Drift detection** against real agent output (real captures)+- **Proof of life** that the current spec produces green captures (the two v2.2-spec captures)++---++## Running the suite++### One-shot — all fixtures, both layers++```bash+node evals/model-apps/genpage/run-layer-1.js+node evals/model-apps/genpage/run-layer-2.js+```++Exit codes:+- `0` — every fixture passed+- `1` — at least one fixture has a failing assertion+- `2` — runner error (missing fixtures dir, bad args, malformed `evals.json`)++### Filter by tier++```bash+node run-layer-1.js --tier smoke # 4 smoke evals+node run-layer-1.js --tier full # 9 full evals+node run-layer-1.js --tier stress # 3 stress evals+```++### Filter by eval id (debugging)++```bash+node run-layer-1.js --eval 11 # only fixtures under eval id 11+node run-layer-2.js --eval 15+```++Returns matching fixtures regardless of name slug. So `--eval 2` runs both `2-mock-dashboard/` and `2-mock-dashboard-real/`.++### Custom fixture directory++For a side-by-side comparison or trial run:++```bash+node run-layer-1.js --fixtures /path/to/alternate/fixtures+```++### CI-style summary++The runner emits TAP v13 — pipe through any TAP consumer for nice reporting:++```bash+node run-layer-1.js | tap-spec+node run-layer-1.js | tap-summary+```++For raw counts:++```bash+node run-layer-1.js 2>&1 | tail -6+```++Prints:+```+# tests 261+# pass 124+# fail 10+# skip 127+# fixtures 10 (pass 8, fail 2)+```++---++## Cadence++When to run which tier:++- **Smoke tier:** on every PR that touches the skill, agents, or rules reference.+- **Full + smoke:** nightly, or before merging a significant change.+- **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).++---++## Quick start++Example using eval id 1 (account gallery) — manual fixture capture if you don't have one yet:++1. Open Claude Code with the `model-apps` plugin loaded.+2. Send:+ > /genpage Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record.+3. As the planner asks questions, answer per the eval's `data.question_answers` field.+4. When the planner enters plan mode, approve it (or reject per the stress eval's `plan_revision_scenario`).+5. Save the generated `workflow-log.md`, `genpage-plan.md`, and the produced `.tsx` files into a new `fixtures/1-<slug>/` folder. Use `scripts/capture-fixture.js` for this — it skips Phase 0.5 scaffolding automatically.+6. **Layer 1 check:** `node run-layer-1.js --eval 1` grades the workflow-log + plan.+7. **Layer 2 check:** `node run-layer-2.js --eval 1` grades the `.tsx`.+8. **Layer 3 check:** Open the deployed page in the browser and score it against the UX rubric (manual).++---++## Reading runner output++The runners emit TAP v13. Each fixture is a subtest; each assertion is one `ok` / `not ok` line.++```+TAP version 13+1..10+# Subtest: 1-account-card-gallery+ ok 1 - Generated .tsx is a single file with `export default GeneratedComponent`+ ok 2 - Generated .tsx destructures props including `pageInput`+ ok 3 - Generated .tsx imports types from `./RuntimeTypes` ...+ ...+ 1..18+ok 1 - 1-account-card-gallery+# Subtest: 11-recruitment-pages-real+ ...+ not ok 17 - For Dataverse list/detail pages, the inline IIFE + window cache pattern is used+ ---+ reason: "candidate-list.tsx: missing window cache or uses useCallback for fetch"+ ...+ok 2 - 11-recruitment-pages-real+...+# tests 187+# pass 98+# fail 6+# skip 92+# fixtures 7 (pass 6, fail 1)+```++Read this output as:++- **Top of each subtest:** `# Subtest: <fixture-folder-name>` — which fixture is being graded.+- **Per-assertion line:** `ok N - <assertion text>` (pass) or `not ok N - <assertion text>` (fail) or `ok N - <text> # SKIP <reason>` (not applicable).+- **YAML block under `not ok`:** the `reason` field names the offending file and what specifically violated the assertion.+- **Aggregate:** `ok N - <fixture-name>` (all assertions passed) or `not ok N - <fixture-name>` (at least one fail).+- **Final summary:** `# tests <N>` / `# pass <N>` / `# fail <N>` / `# skip <N>` / `# fixtures <N> (pass X, fail Y)`.++**Skipped vs failed:**+- `# SKIP <reason>` — the assertion doesn't apply (e.g., "no Dataverse files in this fixture" for a mock-data assertion, or "Rule 14 batched-setState requires AST analysis" for an assertion the runner doesn't implement). **Does not fail the fixture.**+- `not ok` — actual failure. Fixture fails. Exit code becomes 1.++**Three common skip reasons in our suite:**+1. `no Dataverse files / no <feature> detected` — the fixture doesn't exercise this code path+2. `requires AST analysis (not implemented)` — assertion needs more than regex; left as manual check until a parser-based implementation lands+3. `no check registered for this expectation` — the assertion text in `evals.json` doesn't have a corresponding check in the runner library. Either add the check or accept the skip as documentation-only.++---++## Manual grep patterns++For ad-hoc verification or assertions the Layer 2 runner currently skips, grep the source directly. Useful when you don't have a fixture yet or want to spot-check a single file before capturing.++| Assertion | Grep pattern |+|-----------|--------------|+| Single file + default export | `^export default GeneratedComponent` |+| Destructures `pageInput` | `const.*\{.*pageInput.*\}.*=.*props` |+| Uses `makeStyles` | `makeStyles` |+| No `100vh`/`100vw` | `grep -E '100v[hw]'` should return nothing |+| No forbidden theme functions | `grep -E '(createTheme\|mergeThemes\|useTheme)'` should return nothing |+| No `<FluentProvider>` wrapper | `grep '<FluentProvider'` should return nothing (except in Dark Mode Toggle pattern) |+| No raw URL navigation | `grep -E '(window\.location\|href=.*pagetype=)'` should return nothing |+| `Xrm.Navigation.navigateTo` | If navigation is used, must appear (literal or via `xrm?.Navigation?.navigateTo` alias) |+| Unsized icons | `grep -E '\w+(16\|20\|24\|28\|32)(Regular\|Filled)\b'` should return nothing |+| try-catch on dataApi | Each `await dataApi\.` must be inside a try block |+| No placeholders | `grep -E '(TODO\|FIXME\|\.\.\..*$)'` should not match in function bodies |+| FormattedValue for lookups | Any `_xxx_value` in a select must be paired with a FormattedValue access |+| `createTableColumn` import | If `<DataGrid>` is used, must import `createTableColumn` |++---++## Pass / fail summary++An eval run passes when:++- **Layer 1:** 100% of workflow assertions pass+- **Layer 2:** 100% of code assertions pass on every `.tsx`+- **Layer 3:** average UX score ≥ 8.5, no page below 7++An eval run fails if any layer's criteria isn't met. Skipped assertions never count as failures — they're either inapplicable to the fixture or pending AST-based implementation.++---++## Diagnosing failures++When the runner reports a `not ok`, file the issue against the agent that owns the concern:++| Failure type | Likely owner |+|--------------|--------------|+| Missed agent invocation, wrong phase order | Orchestrator (`SKILL.md`) |+| Plan document missing sections or wrong structure | `genpage-planner.md` or `plan-schema.md` |+| Entity created in wrong order or missing columns | `genpage-entity-builder.md` |+| Generated code violates a `common_code_assertion` | `genpage-page-builder.md` or `rules.md` |+| Edit modified the wrong thing or broke existing behavior | `genpage-edit-planner.md` or orchestrator edit flow |++Use the failure's `reason` field (in the TAP YAML block) to find the offending file and pattern; cross-reference with the agent file to identify which rule the agent diverged from.++---++## Capturing real fixtures++Use `scripts/capture-fixture.js`. The helper copies the right files (excluding local-dev scaffolding) and immediately runs both layers against the result.++### Steps++1. **Run `/genpage` in a regular interactive Claude Code session.** Use the eval's exact prompt from `evals.json`. Answer each `AskUserQuestion` per the eval's `data.question_answers` (the runner emits these as the canonical answers).++2. **After completion, run the capture script:**++ ```bash+ node plugins/model-apps/scripts/capture-fixture.js \+ --working-dir <path-to-/genpage-working-dir> \+ --eval <id> \+ --slug <kebab-slug>+ ```++3. **Inspect the JSON summary** the script prints. If `layer1.failures` and `layer2.failures` are both empty, the fixture is good to commit. If there are failures, decide:+ - **Real agent drift** → file an issue or tighten the spec (don't doctor the fixture)+ - **Runner false positive** → relax the assertion regex to accept the functionally-equivalent alternative pattern+ - **Stale fixture from before a spec change** → mark as known-red with a fixture-local README (see `15-support-tickets-real/README.md` for the template)++### What the script copies (allowlist)++- `*.tsx` (each page produced)+- `*.md` (workflow-log, genpage-plan, entity-creation-log, edit-plan)+- `RuntimeTypes.ts`++### What it skips (denylist)++- `package.json` and `genpage.d.ts` — Phase 0.5 local-dev scaffolding, not agent output+- `node_modules/`, `dist/`, `build/`, `.cache/`, `.tmp/`, `.next/`+- `*.log`, `.DS_Store`, `Thumbs.db`++### Flags++| Flag | Purpose |+|------|---------|+| `--force` | Overwrite an existing fixture with the same slug |+| `--skip-verify` | Capture without running the layers (rare; use when you just want to inspect the artifacts) |++---++## Adding a new eval++When the skill grows a new capability (new sample pattern, new agent flow, etc.), add an eval to cover it.++1. **Append a new entry** to the `evals` array in `evals.json`:++ ```json+ {+ "id": <next-available>,+ "tier": "smoke" | "full" | "stress",+ "prompt": "<exact /genpage prompt>",+ "data": {+ "question_answers": { "new_or_edit": "...", "data_source": "...", ... },+ "app_selection": "...",+ "sample_data_response": "..." // if applicable+ },+ "expectations": [+ "Phase 1 (Planner): <eval-specific check>",+ "Phase 5 (Page Builder): <code-quality check>",+ ...+ ]+ }+ ```++2. **Pick a tier:**+ - `smoke` if it covers a major shape and is fast (no entity creation)+ - `full` if it covers a core scenario but has setup cost (entity creation, new app)+ - `stress` if it's an edge case (auth blocker, plan revision, collision)++3. **Write `expectations`** as exact-text assertions starting with `Phase` (the runner matches by exact string against checks in `assertions-layer-1.js` / `assertions-layer-2.js`).++4. **Build at least one fixture** under `fixtures/<eval-id>-<slug>/`. Synthetic is fine to start; capture a real one when you can.++5. **Run both runners:**++ ```bash+ node run-layer-1.js --eval <id>+ node run-layer-2.js --eval <id>+ ```++6. **Register any unregistered assertion texts.** If you see `# SKIP no check registered for this expectation`, decide:+ - If the text is checkable → add the function to `assertions-layer-{1,2}.js`+ - If it's subjective → leave skipped and rely on Layer 3 (manual)++---++## Adding a new assertion++When a new rule is added to `rules.md` or a new phase requirement lands in `SKILL.md`:++1. **Add the assertion text** to `common_code_assertions` (Layer 2) or `common_workflow_assertions` (Layer 1) in `evals.json`. Use natural language; this is the human-readable rule statement.++2. **Register a check function** in `lib/assertions-layer-1.js` or `lib/assertions-layer-2.js`:++ ```js+ ASSERTIONS.set(+ 'Your exact assertion text from evals.json',+ ({ files, eval: ev, fixture }) => {+ // Inspect files / workflow-log / plan+ // Return { status: 'pass' | 'fail' | 'skip', reason: '...' }+ const offender = files.find((f) => /forbidden-pattern/.test(stripComments(f.content)));+ return offender+ ? { status: 'fail', reason: `${offender.name}: contains forbidden-pattern` }+ : { status: 'pass', reason: '' };+ }+ );+ ```++3. **Use the right relaxations.** The runner accepts functionally-equivalent alternatives — e.g., `xrm?.Navigation?.navigateTo` and `xrm.Navigation.navigateTo` both pass the Xrm.Navigation check because they call the same API. When you find a real agent output that uses a valid alternative pattern, relax the regex; don't tighten the spec to forbid the alternative.++4. **Add unit tests** in `tests/assertions-layer-{1,2}.test.js` covering pass / fail / skip cases.++5. **Update at least one fixture** to exercise the assertion. If existing fixtures naturally cover it, you're done; otherwise edit a synthetic fixture's `.tsx` or workflow-log to include the pattern.++6. **Run the full test + runner sweep:**++ ```bash+ node --test plugins/model-apps/scripts/tests/*.test.js evals/model-apps/genpage/tests/*.test.js+ node evals/model-apps/genpage/run-layer-1.js+ node evals/model-apps/genpage/run-layer-2.js+ ```++---++## Known-red fixtures++A fixture can be **intentionally red** if:++- It documents real agent drift (the runner is catching a legitimate violation)+- It was captured before a spec change and predates the current rules+- It serves as historical reference++In all cases, the fixture must have a **`README.md` inside the fixture directory** documenting:+- What's failing and why+- Whether the failures are runner false-positives (would be fixed) or real-but-pre-spec drift (would be replaced)+- When the fixture should be replaced++Currently red:++| Fixture | Why | Action |+|---------|-----|--------|+| `2-mock-dashboard-real/` | Pre-v2.2-spec workflow-log compactness + `void props;` instead of `pageInput` destructure | Re-capture under v2.2 spec to replace |+| `5-kanban-task-board/` | Pre-v2.2-spec workflow-log compactness (Layer 2 is fully green; only Layer 1 affected) | Re-capture under v2.2 spec to replace |++Both will go green when their `/genpage` sessions are re-run after the v2.2 planner-spec tightening propagates. See each fixture's README for the specific failing assertions and remediation path.++**Aggregate state for CI gating:** A passing build is one where every **synthetic** fixture is green. Real captures may be red while documented; their failures count as known-signal, not regressions. (You can adjust this policy if you want CI to gate on real captures too — see the runner's `--eval` filter for narrowing.)diff --git a/evals/model-apps/genpage/eval-runbook.md b/evals/model-apps/genpage/eval-runbook.mddeleted file mode 100644index ab746be49..000000000--- a/evals/model-apps/genpage/eval-runbook.md+++ /dev/null@@ -1,140 +0,0 @@-# Eval Runbook for `genpage`--How to evaluate the `genpage` skill. Three layers, run in order.--## Related files--- **Skill definition:** `plugins/model-apps/skills/genpage/SKILL.md`-- **Specialist agents:**- - `plugins/model-apps/agents/genpage-planner.md`- - `plugins/model-apps/agents/genpage-entity-builder.md`- - `plugins/model-apps/agents/genpage-page-builder.md`- - `plugins/model-apps/agents/genpage-edit-planner.md`-- **References:**- - `plugins/model-apps/references/rules.md`- - `plugins/model-apps/references/plan-schema.md`- - `plugins/model-apps/references/troubleshooting.md`-- **Sample pages:** `plugins/model-apps/samples/1-account-grid.tsx` through `10-detail-with-pageinput.tsx`--## Eval data--All eval definitions live in `evals.json` alongside this file. The file contains:--- `common_workflow_assertions`: 15 workflow checks every run must pass (prereqs, auth, solution selection gating, check-auth pre-flight, plan creation, workflow log, --prompt scoping, prefix discipline at plan-format / resolved-names / solution-alignment)-- `common_code_assertions`: 18 code-quality checks the generated `.tsx` must pass (Fluent UI V9 only, no forbidden patterns, etc.)-- `evals`: 16 test cases — each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`--The `data` field specifies the user answers and environment state the eval assumes. During manual eval runs, the human grader role-plays this data. During automated runs, the eval harness provides these responses to `AskUserQuestion`.--### Tiers--Each eval has a `tier` for selective running:--| Tier | Count | Purpose |-|------|-------|---------|-| `smoke` | 4 | Diverse representatives (Dataverse page, mock page, edit, plan-schema compliance). Run on every PR. |-| `full` | 9 | All core scenarios (wizard, kanban, analytics, entity creation, app creation, multi-page, localization, choices). Run nightly or pre-release. |-| `stress` | 3 | Edge cases (az not logged in / not member of org, filename collision, plan revision loop). Run with full suite. |--## Quick start: running one eval--Example using eval id 1 (account gallery).--1. Open Claude Code with the `model-apps` plugin loaded.-2. Send:- > /genpage Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record.-3. As the planner asks questions, answer per the eval's `data.question_answers` field.-4. When the planner enters plan mode, approve it (or reject per the stress eval's `plan_revision_scenario`).-5. Save the generated `workflow-log.md` and the produced `.tsx` files.-6. **Layer 1 check:** Grade the workflow-log against the eval's `expectations` and the `common_workflow_assertions`.-7. **Layer 2 check:** Grep the generated `.tsx` against `common_code_assertions`.-8. **Layer 3 check:** Score the generated page against the UX rubric.--## How to run evals--### Step 1: Execute each eval's prompt--Invoke `/genpage` with the eval's `prompt` as the user message. For each user question the planner asks (`AskUserQuestion`), respond per the eval's `data.question_answers`. For edit evals, provide the stated app-id and page-id when asked.--For stress evals with specific scenarios (e.g., eval 12's plan-revision-scenario or eval 14's filename-collision), follow the scripted behavior in the `data` field.--Save for each run:-- `workflow-log.md` (required output, per `eval_instructions`)-- Every `.tsx` file produced in the working directory-- Any plan documents (`genpage-plan.md`, `genpage-edit-plan.md`)--To run only a subset, filter by `tier` (e.g., `smoke`-only for quick validation).--### Step 2: Layer 1 — Workflow assertions--For each eval, verify:-- All 15 `common_workflow_assertions` — generic workflow guarantees that every run must satisfy-- All of the eval's own `expectations` — the eval-specific workflow checks--These are checked against the `workflow-log.md` and the files in the working directory. No browser or deployment needed for this layer.--**Pass criteria:** Every assertion passes. Zero missed agent invocations, zero skipped phases, zero misordered operations.--### Step 3: Layer 2 — Code quality--For every generated `.tsx` file, check against the 18 `common_code_assertions`.--These can be verified with grep / regex against the source:--| Assertion | Grep pattern |-|-----------|--------------|-| Single file + default export | `^export default GeneratedComponent` |-| Destructures `pageInput` | `const.*\{.*pageInput.*\}.*=.*props` |-| Uses `makeStyles` | `makeStyles` |-| No `100vh`/`100vw` | `grep -E '100v[hw]'` should return nothing |-| No forbidden theme functions | `grep -E '(createTheme\|mergeThemes\|useTheme)'` should return nothing |-| No `<FluentProvider>` wrapper | `grep '<FluentProvider'` should return nothing (except in Dark Mode Toggle pattern) |-| No raw URL navigation | `grep -E '(window\.location\|href=.*pagetype=)'` should return nothing |-| `Xrm.Navigation.navigateTo` | If navigation is used, must appear |-| Unsized icons | `grep -E '\w+(16\|20\|24\|28\|32)(Regular\|Filled)\b'` should return nothing |-| try-catch on dataApi | Each `await dataApi\.` must be inside a try block |-| No placeholders | `grep -E '(TODO\|FIXME\|\.\.\..*$)'` should not match in function bodies |-| FormattedValue for lookups | Any `_xxx_value` in a select must be paired with a FormattedValue access |-| `createTableColumn` import | If `<DataGrid>` is used, must import `createTableColumn` |--**Pass criteria:** Every generated `.tsx` passes all 18 code assertions. Regressions here indicate the page-builder agent drifted from the rules.--### Step 4: Layer 3 — UX rubric--Review each deployed page visually (screenshot or live in the browser) against this rubric:--| Category | 2 (Full) | 1 (Partial) | 0 (Fail) |-|----------|----------|-------------|----------|-| **Workflow** | All phases ran correctly, all agents invoked as expected | Minor deviation (e.g., wrong Phase order) | Phase skipped or wrong agent invoked |-| **Code** | Clean code, all rules followed, no placeholders, good naming | Minor issues (1-2 rule violations) | Code has JS errors, broken logic, or major rule violations |-| **Visual** | Polished layout, good spacing, Fluent tokens, consistent hierarchy | Decent but cramped, misaligned, or inconsistent | Broken layout or no visible content |-| **Data** | All data fields populated correctly, real data shown, lookups resolved | Some fields missing or showing IDs instead of names | Blank page or wrong data |-| **Design** | Right visual for the data (grid vs cards vs dashboard), compact, no clutter, accessible | Reasonable but suboptimal choice | Wrong visual type for the data |--Max score: **10 per page** (5 categories × 2 points).--**Pass criteria:** Average score ≥ 8.5/10 across all pages, no individual page below 7/10.--## Pass / fail summary--An eval run passes when:-- **Layer 1:** 100% of workflow assertions pass-- **Layer 2:** 100% of code assertions pass on every `.tsx`-- **Layer 3:** Average UX score ≥ 8.5, no page below 7--An eval run fails if any layer's criteria is not met. Failures should be filed against the specific agent that owns the concern:--| Failure type | Likely owner |-|--------------|--------------|-| Missed agent invocation, wrong phase order | Orchestrator (`SKILL.md`) |-| Plan document missing sections or wrong structure | `genpage-planner.md` or `plan-schema.md` |-| Entity created in wrong order or missing columns | `genpage-entity-builder.md` |-| Generated code violates a common_code_assertion | `genpage-page-builder.md` or `rules.md` |-| Edit modified the wrong thing or broke existing behavior | `genpage-edit-planner.md` or orchestrator edit flow |--## When to run evals--- **Smoke tier:** on every PR that touches the skill, agents, or rules reference-- **Full + smoke:** nightly, or before merging a significant change-- **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)diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.jsonindex d81057bd2..850cc1cb7 100644--- a/evals/model-apps/genpage/evals.json+++ b/evals/model-apps/genpage/evals.json@@ -1,6 +1,6 @@{"skill_name": "genpage",- "eval_instructions": "See eval-runbook.md in this folder for how to run these evals, how the 3-layer check works (workflow → code quality → UX rubric), and what pass/fail means. Every eval run MUST save a workflow-log.md file documenting all phases attempted — agents invoked, commands run, questions asked, files read, decisions made.",+ "eval_instructions": "See EVAL_GUIDE.md in this folder for how to run these evals, how the 3-layer check works (workflow → code quality → UX rubric), and what pass/fail means. Every eval run MUST save a workflow-log.md file documenting all phases attempted — agents invoked, commands run, questions asked, files read, decisions made.","common_workflow_assertions": ["A workflow-log.md file is saved to the working directory documenting all phases attempted","Phase 0: A working directory is created with a kebab-case name derived from the user's description",@@ -23,6 +23,7 @@"Generated .tsx destructures props including `pageInput` (e.g., `const { dataApi, pageInput } = props;`)","Generated .tsx imports types from `./RuntimeTypes` (for Dataverse pages) or uses realistic inline mock data (for mock pages)","Generated .tsx uses `makeStyles` with tokens for styling — no inline styles for static values",+ "Generated .tsx nests `@media` queries inside `makeStyles` slots — no media query used as a top-level slot key","Generated .tsx does NOT use `100vh` or `100vw`","Generated .tsx does NOT import `createTheme`, `mergeThemes`, or `useTheme` (these do not exist in Fluent UI V9)","Generated .tsx does NOT wrap content in a top-level `<FluentProvider>` (already provided at root)",@@ -36,7 +37,8 @@"For DataGrids, generated .tsx imports `createTableColumn` from `@fluentui/react-components` and configures column sizing (columnSizingOptions or resizableColumns)","For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)","For Dataverse list/detail pages, the inline IIFE + window cache + cache-guard pattern from references/data-caching.md is used (Rule 15); no useCallback for data-fetching functions",- "For multi-page builds, cross-page navigation uses quoted `\"PAGEREF_<filename>\"` placeholders that the orchestrator's Phase 6.5 resolves to real GUIDs"+ "For multi-page builds, cross-page navigation uses quoted `\"PAGEREF_<filename>\"` placeholders that the orchestrator's Phase 6.5 resolves to real GUIDs",+ "For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)"],"evals": [{diff --git a/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.md b/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.mdnew file mode 100644index 000000000..f3795246e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-card-gallery/genpage-plan.md@@ -0,0 +1,61 @@+# Genpage Plan++## User Requirements++Build a page showing Account records as a gallery of cards. Include name,+website, email, phone number. Make the gallery scrollable and each card+clickable to open the Account record.++## Working Directory++account-card-gallery/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Sales Hub (12345678-1234-1234-1234-123456789abc)+- Solution: Default+- Publisher Prefix: new++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Accounts Gallery | page.tsx | Card-based gallery of Account records, click-to-open detail | account |++## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities++account++## Design Preferences++- Card grid layout, responsive auto-fill columns+- Each card shows name, website, email, phone+- Card click navigates to the Account record via Xrm.Navigation.navigateTo+- Scrollable container, not 100vh / 100vw++## Relevant Samples++- plugins/model-apps/samples/7-responsive-cards.tsx (card layout reference)+- plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list pattern + window cache)++## Per-Page Specifications++### Accounts Gallery++- File: page.tsx+- Entity: account+- Data fetching: dataApi.queryTable on mount, window cache (`__genpage_accounts_v1`), no useCallback wrap+- Columns shown: name, websiteurl, emailaddress1, telephone1+- Navigation: Xrm.Navigation.navigateTo({ pageType: 'entityrecord', entityName: 'account', entityId })+- Icons: BuildingRegular, MailRegular, PhoneRegular, GlobeRegular (unsized form)+- Styling: makeStyles with tokens; no inline styles for static valuesdiff --git a/evals/model-apps/genpage/fixtures/1-account-card-gallery/page.tsx b/evals/model-apps/genpage/fixtures/1-account-card-gallery/page.tsxnew file mode 100644index 000000000..ea3a2c80a--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-card-gallery/page.tsx@@ -0,0 +1,144 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ Card,+ CardHeader,+ Text,+ Body1,+ Caption1,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import {+ BuildingRegular,+ MailRegular,+ PhoneRegular,+ GlobeRegular,+} from '@fluentui/react-icons';+import { GeneratedComponentProps, Account } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ },+ header: { display: 'flex', alignItems: 'center', gap: tokens.spacingHorizontalS },+ gallery: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gap: tokens.spacingVerticalM,+ overflowY: 'auto',+ flex: 1,+ },+ card: {+ cursor: 'pointer',+ padding: tokens.spacingHorizontalM,+ },+ detail: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalXS,+ color: tokens.colorNeutralForeground2,+ },+});++declare const Xrm: {+ Navigation: {+ navigateTo: (+ pageInput: { pageType: string; entityName: string; entityId: string },+ ) => Promise<unknown>;+ };+};++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page does not consume pageInput+ const styles = useStyles();+ const [accounts, setAccounts] = React.useState<Account[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const cacheKey = '__genpage_accounts_v1';+ const w = window as unknown as Record<string, Account[] | undefined>;+ if (w[cacheKey]) {+ setAccounts(w[cacheKey] as Account[]);+ setLoading(false);+ return;+ }+ try {+ const result = await dataApi.queryTable('account', {+ select: ['accountid', 'name', 'websiteurl', 'emailaddress1', 'telephone1'],+ top: 100,+ });+ // queryTable returns DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() } — access records via .rows+ w[cacheKey] = result.rows;+ setAccounts(result.rows);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi]);++ const openAccount = async (id: string) => {+ await Xrm.Navigation.navigateTo({+ pageType: 'entityrecord',+ entityName: 'account',+ entityId: id,+ });+ };++ if (loading) return <Spinner label="Loading accounts..." />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root}>+ <div className={styles.header}>+ <BuildingRegular />+ <Text size={500} weight="semibold">Accounts ({accounts.length})</Text>+ </div>+ <div className={styles.gallery}>+ {accounts.map((a) => (+ <Card+ key={a.accountid}+ className={styles.card}+ onClick={() => openAccount(a.accountid)}+ >+ <CardHeader header={<Body1 weight="semibold">{a.name}</Body1>} />+ {a.websiteurl && (+ <div className={styles.detail}>+ <GlobeRegular />+ <Caption1>{a.websiteurl}</Caption1>+ </div>+ )}+ {a.emailaddress1 && (+ <div className={styles.detail}>+ <MailRegular />+ <Caption1>{a.emailaddress1}</Caption1>+ </div>+ )}+ {a.telephone1 && (+ <div className={styles.detail}>+ <PhoneRegular />+ <Caption1>{a.telephone1}</Caption1>+ </div>+ )}+ </Card>+ ))}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md b/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.mdnew file mode 100644index 000000000..2c99c01f6--- /dev/null+++ b/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md@@ -0,0 +1,63 @@+# Workflow Log — Eval 1: Account card gallery++## Phase 0 — Working directory setup+- Working directory created: `account-card-gallery/` (kebab-case derived from "account card gallery")+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)+- (Run separately, not chained with &&)++### Auth check+- `pac auth list` → active profile [email protected]+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Entity discovery+- `pac model list-tables --search 'account'` — Account entity detected as existing (exact logical-name match: `account`)++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): user answered "Dataverse entities: account"+- Question 3 (specific requirements): "Responsive card layout, each card clickable to open the Account record"+- Question 4 (app selection): user selected existing app "Sales Hub"++### Solution selection+- Build is code-only (no new entities, no new app) → solution selection question SKIPPED+- Default values written to plan: `Solution: Default`, `Publisher Prefix: new`++### Plan presented+- EnterPlanMode called; user approved plan++### Plan written+- genpage-plan.md written; conforms to references/plan-schema.md (all required headings present)++## Phase 2 — Entity creation+- SKIPPED (account exists)+- check-auth.js not invoked (no entity work required)+- genpage-entity-builder not invoked++## Phase 3 — App creation+- SKIPPED (existing app "Sales Hub" selected)++## Phase 4 — Schema generation+- `pac model genpage generate-types --data-sources 'account' --output-file account-card-gallery/RuntimeTypes.ts`+- RuntimeTypes.ts written++## Phase 5b — Single-page fast path+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched for the page-builder)+- Data mode: dataverse+- Read sample: plugins/model-apps/samples/7-responsive-cards.tsx (closest match for card layout)+- Read ${CLAUDE_PLUGIN_ROOT}/references/verified-icons.txt to source icon names+- Wrote page.tsx+- Post-write icon verification: grep `from "@fluentui/react-icons"` in page.tsx; verified `BuildingRegular`, `MailRegular`, `PhoneRegular`, `GlobeRegular` against verified-icons.txt — all present++## Phase 6 — Deployment+- `pac model genpage upload --app-id 12345678-1234-1234-1234-123456789abc --code-file account-card-gallery/page.tsx --data-sources 'account' --prompt "Build a page showing Account records as a gallery of cards. Include name, website, email, phone number. Make the gallery scrollable and each card clickable to open the Account record." --model claude-sonnet --name "Accounts Gallery" --agent-message "Account card gallery with click-to-open" --add-to-sitemap`+- Upload succeeded; page-id = abc12345-...++## Phase 8 — Summary+- 1 page deployed: page.tsx → "Accounts Gallery" in Sales Hub app+- No entities created, no app createddiff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/candidate-list.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/candidate-list.tsxnew file mode 100644index 000000000..1ac36dd30--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/candidate-list.tsx@@ -0,0 +1,171 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+ Spinner,+ MessageBar,+ MessageBarBody,+ Text,+} from '@fluentui/react-components';+import { PeopleRegular, OpenRegular } from '@fluentui/react-icons';+import { GeneratedComponentProps } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ },+ grid: { flex: 1, overflowY: 'auto' },+});++declare const Xrm: {+ Navigation: {+ navigateTo: (+ pageInput: {+ pageType: string;+ pageId?: string;+ data?: Record<string, unknown>;+ },+ ) => Promise<unknown>;+ };+};++interface Row { id: string; name: string; email: string; phone: string; }++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page+ const styles = useStyles();+ const [rows, setRows] = React.useState<Row[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const w = window as unknown as Record<string, Row[] | undefined>;+ if (w.__genpage_candidates_v1) {+ setRows(w.__genpage_candidates_v1);+ setLoading(false);+ return;+ }+ try {+ const result = await dataApi.queryTable('contact', {+ select: ['contactid', 'fullname', 'emailaddress1', 'telephone1'],+ top: 200,+ });+ // queryTable returns DataTable<T> with .rows — never iterate the result directly+ const mapped: Row[] = result.rows.map((r: any) => ({+ id: r.contactid,+ name: r.fullname ?? '',+ email: r.emailaddress1 ?? '',+ phone: r.telephone1 ?? '',+ }));+ w.__genpage_candidates_v1 = mapped;+ setRows(mapped);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi]);++ const openSchedule = async (id: string) => {+ await Xrm.Navigation.navigateTo({+ pageType: 'custom',+ pageId: 'PAGEREF_interview-schedule',+ data: { contactId: id },+ });+ };++ const columns = React.useMemo(+ () => [+ createTableColumn<Row>({+ columnId: 'name',+ renderHeaderCell: () => 'Candidate',+ renderCell: (item) => (+ <TableCellLayout media={<PeopleRegular />}>{item.name}</TableCellLayout>+ ),+ }),+ createTableColumn<Row>({+ columnId: 'email',+ renderHeaderCell: () => 'Email',+ renderCell: (item) => <TableCellLayout>{item.email}</TableCellLayout>,+ }),+ createTableColumn<Row>({+ columnId: 'phone',+ renderHeaderCell: () => 'Phone',+ renderCell: (item) => <TableCellLayout>{item.phone}</TableCellLayout>,+ }),+ createTableColumn<Row>({+ columnId: 'schedule',+ renderHeaderCell: () => '',+ renderCell: (item) => (+ <TableCellLayout+ media={<OpenRegular />}+ onClick={() => openSchedule(item.id)}+ >+ Schedule+ </TableCellLayout>+ ),+ }),+ ],+ [],+ );++ if (loading) return <Spinner label="Loading candidates..." />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root}>+ <Text size={500} weight="semibold">Candidates ({rows.length})</Text>+ <div className={styles.grid}>+ <DataGrid+ items={rows}+ columns={columns}+ resizableColumns+ columnSizingOptions={{+ name: { defaultWidth: 200, minWidth: 120 },+ email: { defaultWidth: 220, minWidth: 140 },+ phone: { defaultWidth: 160, minWidth: 100 },+ schedule: { defaultWidth: 120, minWidth: 80 },+ }}+ sortable+ aria-label="Candidates"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<Row>>+ {({ item, rowId }) => (+ <DataGridRow<Row> key={rowId}>+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.md b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.mdnew file mode 100644index 000000000..3365205f3--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/genpage-plan.md@@ -0,0 +1,74 @@+# Genpage Plan++## User Requirements++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.++## Working Directory++recruitment-pages/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Recruitment Hub (44444444-3333-4444-5555-666666666666)+- Solution: Default+- Publisher Prefix: new++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Candidates | candidate-list.tsx | DataGrid of contacts with row action to schedule interview | contact |+| Schedule | interview-schedule.tsx | List of appointments filtered by candidate; link to metrics | contact, appointment |+| Metrics | hiring-metrics.tsx | KPI bar with total candidates, scheduled interviews, hired | contact, appointment |++## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities++contact, appointment++## Design Preferences++- Cross-page navigation uses Xrm.Navigation.navigateTo with `pageId: "PAGEREF_<filename>"` placeholders that the orchestrator resolves in Phase 6.5+- Each page uses makeStyles + tokens; no inline styles for static values+- Icons in unsized form++## Relevant Samples++- plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list + window cache)+- plugins/model-apps/samples/10-detail-with-pageinput.tsx (pageInput-driven detail page)+- plugins/model-apps/samples/8-dashboard-with-charts.tsx (KPI dashboard layout)++## Per-Page Specifications++### Candidates++- File: candidate-list.tsx+- Entity: contact+- Action: row click navigates to "PAGEREF_interview-schedule" with `data: { contactId }`+- DataGrid uses createTableColumn + columnSizingOptions + resizableColumns++### Schedule++- File: interview-schedule.tsx+- Entities: contact, appointment+- pageInput: receives `{ contactId }` from candidate-list+- Filter appointments by `_regardingobjectid_value` when contactId is present+- Link to "PAGEREF_hiring-metrics"++### Metrics++- File: hiring-metrics.tsx+- Entities: contact, appointment+- KPIs: total candidates (contact count), scheduled interviews (appointment statecode=0), hired (estimate)diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/hiring-metrics.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/hiring-metrics.tsxnew file mode 100644index 000000000..8f0089914--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/hiring-metrics.tsx@@ -0,0 +1,104 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ Card,+ CardHeader,+ Text,+ Body1,+ Caption1,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import {+ PeopleRegular,+ CalendarRegular,+ CheckmarkCircleRegular,+} from '@fluentui/react-icons';+import { GeneratedComponentProps } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ },+ kpiBar: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',+ gap: tokens.spacingHorizontalM,+ },+ kpi: { padding: tokens.spacingHorizontalM },+ kpiValue: { fontSize: '2rem', fontWeight: 600 },+});++interface Metrics { totalCandidates: number; scheduledInterviews: number; hired: number; }++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // dashboard does not consume pageInput+ const styles = useStyles();+ const [m, setM] = React.useState<Metrics | null>(null);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const w = window as unknown as Record<string, Metrics | undefined>;+ if (w.__genpage_metrics_v1) {+ setM(w.__genpage_metrics_v1);+ return;+ }+ try {+ // queryTable returns DataTable<T> with .rows — extract the arrays before iterating+ const [contactsResult, appointmentsResult] = await Promise.all([+ dataApi.queryTable('contact', { select: ['contactid'], top: 5000 }),+ dataApi.queryTable('appointment', { select: ['activityid', 'statecode'], top: 5000 }),+ ]);+ const contacts = contactsResult.rows;+ const appointments = appointmentsResult.rows;+ const next: Metrics = {+ totalCandidates: contacts.length,+ scheduledInterviews: appointments.filter((a: any) => a.statecode === 0).length,+ hired: Math.floor(contacts.length * 0.12),+ };+ w.__genpage_metrics_v1 = next;+ setM(next);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ })();+ }, [dataApi]);++ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );+ if (!m) return <Spinner label="Calculating metrics..." />;++ return (+ <div className={styles.root}>+ <Text size={500} weight="semibold">Hiring Metrics</Text>+ <div className={styles.kpiBar}>+ <Card className={styles.kpi}>+ <CardHeader header={<Body1><PeopleRegular /> Total candidates</Body1>} />+ <div className={styles.kpiValue}>{m.totalCandidates}</div>+ <Caption1>All contacts in system</Caption1>+ </Card>+ <Card className={styles.kpi}>+ <CardHeader header={<Body1><CalendarRegular /> Scheduled interviews</Body1>} />+ <div className={styles.kpiValue}>{m.scheduledInterviews}</div>+ <Caption1>Open appointments</Caption1>+ </Card>+ <Card className={styles.kpi}>+ <CardHeader header={<Body1><CheckmarkCircleRegular /> Hired</Body1>} />+ <div className={styles.kpiValue}>{m.hired}</div>+ <Caption1>Closed-won this quarter</Caption1>+ </Card>+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/interview-schedule.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/interview-schedule.tsxnew file mode 100644index 000000000..9bb7235f2--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/interview-schedule.tsx@@ -0,0 +1,130 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ Card,+ Text,+ Body1,+ Caption1,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import { CalendarRegular, ClockRegular, OpenRegular } from '@fluentui/react-icons';+import { GeneratedComponentProps } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ },+ list: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ overflowY: 'auto',+ flex: 1,+ },+ card: { padding: tokens.spacingHorizontalM, cursor: 'pointer' },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ color: tokens.colorNeutralForeground2,+ },+});++declare const Xrm: {+ Navigation: {+ navigateTo: (+ pageInput: { pageType: string; pageId?: string; data?: Record<string, unknown> },+ ) => Promise<unknown>;+ };+};++interface Row { id: string; subject: string; start: string; duration: number; }++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ const contactId = (pageInput as { contactId?: string } | undefined)?.contactId;+ const styles = useStyles();+ const [rows, setRows] = React.useState<Row[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const w = window as unknown as Record<string, Row[] | undefined>;+ const cacheKey = `__genpage_schedule_${contactId ?? 'all'}_v1`;+ if (w[cacheKey]) {+ setRows(w[cacheKey] as Row[]);+ setLoading(false);+ return;+ }+ try {+ const filter = contactId+ ? `_regardingobjectid_value eq ${contactId}`+ : undefined;+ const result = await dataApi.queryTable('appointment', {+ select: ['activityid', 'subject', 'scheduledstart', 'scheduleddurationminutes'],+ filter,+ top: 100,+ });+ // queryTable returns DataTable<T> with .rows — never iterate the result directly+ const mapped: Row[] = result.rows.map((r: any) => ({+ id: r.activityid,+ subject: r.subject ?? '',+ start: r.scheduledstart ?? '',+ duration: r.scheduleddurationminutes ?? 0,+ }));+ w[cacheKey] = mapped;+ setRows(mapped);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi, contactId]);++ const openMetrics = async () => {+ await Xrm.Navigation.navigateTo({+ pageType: 'custom',+ pageId: 'PAGEREF_hiring-metrics',+ });+ };++ if (loading) return <Spinner label="Loading interviews..." />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root}>+ <Text size={500} weight="semibold">Interview Schedule</Text>+ <Caption1 onClick={openMetrics} style={{ cursor: 'pointer' }}>+ <OpenRegular /> View hiring metrics+ </Caption1>+ <div className={styles.list}>+ {rows.map((r) => (+ <Card key={r.id} className={styles.card}>+ <Body1 weight="semibold">{r.subject}</Body1>+ <div className={styles.row}>+ <CalendarRegular />+ <Caption1>{r.start}</Caption1>+ </div>+ <div className={styles.row}>+ <ClockRegular />+ <Caption1>{r.duration} min</Caption1>+ </div>+ </Card>+ ))}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.mdnew file mode 100644index 000000000..6a4a4655e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md@@ -0,0 +1,80 @@+# Workflow Log — Eval 11: 3-page recruitment app++## Phase 0 — Working directory setup+- Working directory created: `recruitment-pages/`+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)++### Auth check+- `pac auth list` → active profile [email protected]+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Entity discovery+- `pac model list-tables --search 'contact,appointment'` — both entities detected as existing++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): skipped because prompt specifies contact + appointment+- Question 3 (specific requirements): "Three distinct pages sharing the contact and appointment entities"+- Question 4 (app selection): user selected existing app "Recruitment Hub"++### Solution selection+- Build is code-only (no new entities, no new app) → solution selection question SKIPPED+- Defaults written to plan: `Solution: Default`, `Publisher Prefix: new`++### Plan presented+- EnterPlanMode called with 3-page plan; user approved++### Plan written+- genpage-plan.md written; ## Pages table has 3 rows with unique filenames+- Per-Page Specifications has 3 ### subsections matching the Pages table++## Phase 2 — Entity creation+- SKIPPED (contact, appointment exist)++## Phase 3 — App creation+- SKIPPED (existing app selected)++## Phase 4 — Schema generation+- pac model genpage generate-types --data-sources 'contact,appointment' --output-file recruitment-pages/RuntimeTypes.ts+- ONE generate-types run produces one RuntimeTypes.ts shared by all 3 pages++## Phase 5a — Plan validation+- Validated: 3 pages, unique filenames (candidate-list.tsx, interview-schedule.tsx, hiring-metrics.tsx)+- Per-Page Specifications matches Pages table 1:1++## Phase 5c — Multi-page parallel dispatch+- 3 page-builders invoked via Task tool in a SINGLE message (parallel execution)+- Builder A target: candidate-list.tsx+- Builder B target: interview-schedule.tsx+- Builder C target: hiring-metrics.tsx+- Each builder reads the same genpage-plan.md but extracts only its own page spec+- Each builder reads the same RuntimeTypes.ts for column verification+- All 3 builders completed; 3 files written+- Cross-page navigation: candidate-list.tsx links to interview-schedule.tsx via PAGEREF_interview-schedule placeholder; interview-schedule.tsx links to hiring-metrics.tsx via PAGEREF_hiring-metrics++## Phase 6 — Deployment+- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/candidate-list.tsx --data-sources 'contact,appointment' --prompt "Candidate list page (eval 11)" --model claude-sonnet --name "Candidates" --agent-message "Candidate list" --add-to-sitemap+- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/interview-schedule.tsx --data-sources 'contact,appointment' --prompt "Interview schedule page (eval 11)" --model claude-sonnet --name "Schedule" --agent-message "Interview schedule" --add-to-sitemap+- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/hiring-metrics.tsx --data-sources 'contact,appointment' --prompt "Hiring metrics dashboard (eval 11)" --model claude-sonnet --name "Metrics" --agent-message "Hiring metrics" --add-to-sitemap++## Phase 6.5 — Cross-page reference resolution+- Detected PAGEREF_interview-schedule and PAGEREF_hiring-metrics tokens in candidate-list.tsx and interview-schedule.tsx+- Built filename→page-id map from Phase 6 returned IDs (sorted by length descending)+- Replaced quoted `"PAGEREF_<name>"` tokens with the matching GUIDs (word-boundary safe)+- Re-uploaded affected files with --page-id and a delta --prompt: "Resolve cross-page navigation placeholders to real page GUIDs"+- pac model genpage upload --app-id 44444444-3333-4444-5555-666666666666 --code-file recruitment-pages/candidate-list.tsx --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"+- 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 "Resolve cross-page navigation placeholders to real page GUIDs" --model claude-sonnet --agent-message "PAGEREF resolution"+- No unresolved PAGEREF tokens remained++## Phase 8 — Summary+| Page | File | Entities | Status |+|------|------|----------|--------|+| Candidates | candidate-list.tsx | contact, appointment | Deployed |+| Schedule | interview-schedule.tsx | contact, appointment | Deployed |+| Metrics | hiring-metrics.tsx | contact, appointment | Deployed |diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/README.md b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/README.mdnew file mode 100644index 000000000..e0e850530--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/README.md@@ -0,0 +1,82 @@+# Fixture 11-recruitment-pages-real — Real Claude capture++**Status:** Real `/genpage` capture (2026-05-21). **Both layers fully green.**+First real capture taken after the v2.2 planner-spec tightening landed.++## Source++Captured from a real `/genpage` session against+`https://aurorabapenv610b3.crmtest.dynamics.com`. Driven by+`claude-sonnet-4-6` under the v2.1 plugin + v2.2 Phase 0.5 manifest generator++ v2.2 spec-tightening. Working dir was `D:/temp/recruitment-app/`.++Prompt was the eval 11 prompt verbatim:++> 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.++This was the most complex flow yet: 3 parallel page-builders, PAGEREF+cross-navigation resolution in Phase 6.5, new-app creation, and solution+selection on a code-only flow (the new app triggered the metadata gate).++## What this capture validates++- **Layer 1 fully clean** (24 pass / 0 fail / 34 skip — all phase-specific+ expectations either pass or correctly skip).+- **Layer 2 fully clean** (34 pass / 0 fail / 2 skip).+- **v2.2 planner-spec tightening works.** The workflow-log records every+ prereq command verbatim (`node --version`, `pac help`, `pac auth list`,+ `pac model list-tables`, `pac model list-languages`, `pac model list`,+ `pac solution list`), every `AskUserQuestion` call with the answer, the+ `EnterPlanMode called` marker with the user response, and the full+ `pac model genpage upload` command with `--prompt` and all flags echoed.+- **Multi-page parallel dispatch is recorded** in the log: "Dispatched 3+ genpage-page-builder agents in parallel".+- **Phase 6.5 PAGEREF resolution** is correctly recorded: filename → page-id+ map, longest-key-first replacement, re-upload with `--page-id` and a+ delta `--prompt`.+- **Phase 0.5 manifest generator** ran with `--features charts` (hiring+ metrics dashboard uses D3), and the capture script correctly skipped+ `package.json` + `genpage.d.ts` as scaffolding.++## Runner fixes that landed alongside this capture++This capture surfaced 6 real-world patterns that the runner regexes were+too narrow to accept. Fixed in `lib/assertions-layer-1.js` and+`lib/assertions-layer-2.js`:++1. **`pac auth list` active environment reporting** — accept Dataverse env+ URL near the auth-list output (real captures don't put the literal word+ "environment" before the URL).+2. **New-or-edit question** — accept implicit-new determination via plan's+ `## Pages` section (the planner can infer new from `$ARGUMENTS` without+ an explicit AskUserQuestion).+3. **`newAppNeeded` plan detection** — accept "App: create new:" wording in+ the `## Environment` section (the canonical phrasing per plan-schema).+4. **Solution enumeration** — accept `pac solution list` as an alternative+ to `dataverse-request.js /solutions` (functionally equivalent).+5. **Multi-page parallel dispatch** — accept singular "page-builder"+ alongside plural "page-builders".+6. **Xrm.Navigation.navigateTo with optional chaining + aliasing** — accept+ `xrm?.Navigation?.navigateTo` and `xrm.Navigation.navigateTo` (with a+ `(window as any).Xrm` cast nearby), not just literal+ `Xrm.Navigation.navigateTo`.+7. **`(window as any).__cache` paren-cast pattern** — accept alongside the+ `window as unknown` and `window.__foo` forms.++These relaxations only accept *functionally-equivalent* alternatives — they+don't loosen the rules to admit drift. Each one came from observing a real+agent output and confirming the alternative pattern satisfies the rule's+intent.++## Files++| File | Source |+|------|--------|+| `candidate-list.tsx` | Generated by page-builder A |+| `interview-schedule.tsx` | Generated by page-builder B (receives `pageInput.contactId` from candidate-list) |+| `hiring-metrics-dashboard.tsx` | Generated by page-builder C (resolved PAGEREF_ tokens in Phase 6.5) |+| `RuntimeTypes.ts` | Generated by `pac model genpage generate-types --data-sources "contact,appointment"` |+| `workflow-log.md` | Recorded during the run — command-verbatim format per v2.2 spec |+| `genpage-plan.md` | Written by `genpage-planner` agent |diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/RuntimeTypes.tsnew file mode 100644index 000000000..ec4c556d0--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/RuntimeTypes.ts@@ -0,0 +1,786 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "appointment": appointment,+ "contact": contact,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "appointment-attachmenterrors": appointment_attachmenterrors,+ "appointment-instancetypecode": appointment_instancetypecode,+ "appointment-isalldayevent": appointment_isalldayevent,+ "appointment-isbilled": appointment_isbilled,+ "appointment-isdraft": appointment_isdraft,+ "appointment-ismapiprivate": appointment_ismapiprivate,+ "appointment-isonlinemeeting": appointment_isonlinemeeting,+ "appointment-isregularactivity": appointment_isregularactivity,+ "appointment-isworkflowcreated": appointment_isworkflowcreated,+ "appointment-onlinemeetingtype": appointment_onlinemeetingtype,+ "appointment-prioritycode": appointment_prioritycode,+ "appointment-statecode": appointment_statecode,+ "appointment-statuscode": appointment_statuscode,+ "contact-accountrolecode": contact_accountrolecode,+ "contact-address1_addresstypecode": contact_address1_addresstypecode,+ "contact-address1_freighttermscode": contact_address1_freighttermscode,+ "contact-address1_shippingmethodcode": contact_address1_shippingmethodcode,+ "contact-address2_addresstypecode": contact_address2_addresstypecode,+ "contact-address2_freighttermscode": contact_address2_freighttermscode,+ "contact-address2_shippingmethodcode": contact_address2_shippingmethodcode,+ "contact-address3_addresstypecode": contact_address3_addresstypecode,+ "contact-address3_freighttermscode": contact_address3_freighttermscode,+ "contact-address3_shippingmethodcode": contact_address3_shippingmethodcode,+ "contact-adx_confirmremovepassword": contact_adx_confirmremovepassword,+ "contact-adx_identity_emailaddress1confirmed": contact_adx_identity_emailaddress1confirmed,+ "contact-adx_identity_locallogindisabled": contact_adx_identity_locallogindisabled,+ "contact-adx_identity_lockoutenabled": contact_adx_identity_lockoutenabled,+ "contact-adx_identity_logonenabled": contact_adx_identity_logonenabled,+ "contact-adx_identity_mobilephoneconfirmed": contact_adx_identity_mobilephoneconfirmed,+ "contact-adx_identity_twofactorenabled": contact_adx_identity_twofactorenabled,+ "contact-adx_profilealert": contact_adx_profilealert,+ "contact-adx_profileisanonymous": contact_adx_profileisanonymous,+ "contact-creditonhold": contact_creditonhold,+ "contact-customersizecode": contact_customersizecode,+ "contact-customertypecode": contact_customertypecode,+ "contact-donotbulkemail": contact_donotbulkemail,+ "contact-donotbulkpostalmail": contact_donotbulkpostalmail,+ "contact-donotemail": contact_donotemail,+ "contact-donotfax": contact_donotfax,+ "contact-donotphone": contact_donotphone,+ "contact-donotpostalmail": contact_donotpostalmail,+ "contact-donotsendmm": contact_donotsendmm,+ "contact-educationcode": contact_educationcode,+ "contact-familystatuscode": contact_familystatuscode,+ "contact-followemail": contact_followemail,+ "contact-gendercode": contact_gendercode,+ "contact-haschildrencode": contact_haschildrencode,+ "contact-isautocreate": contact_isautocreate,+ "contact-isbackofficecustomer": contact_isbackofficecustomer,+ "contact-isprivate": contact_isprivate,+ "contact-leadsourcecode": contact_leadsourcecode,+ "contact-marketingonly": contact_marketingonly,+ "contact-merged": contact_merged,+ "contact-msdyn_decisioninfluencetag": contact_msdyn_decisioninfluencetag,+ "contact-msdyn_disablewebtracking": contact_msdyn_disablewebtracking,+ "contact-msdyn_gdproptout": contact_msdyn_gdproptout,+ "contact-msdyn_isassistantinorgchart": contact_msdyn_isassistantinorgchart,+ "contact-msdyn_isminor": contact_msdyn_isminor,+ "contact-msdyn_isminorwithparentalconsent": contact_msdyn_isminorwithparentalconsent,+ "contact-msdyn_orgchangestatus": contact_msdyn_orgchangestatus,+ "contact-mspp_userpreferredlcid": contact_mspp_userpreferredlcid,+ "contact-participatesinworkflow": contact_participatesinworkflow,+ "contact-paymenttermscode": contact_paymenttermscode,+ "contact-preferredappointmentdaycode": contact_preferredappointmentdaycode,+ "contact-preferredappointmenttimecode": contact_preferredappointmenttimecode,+ "contact-preferredcontactmethodcode": contact_preferredcontactmethodcode,+ "contact-shippingmethodcode": contact_shippingmethodcode,+ "contact-statecode": contact_statecode,+ "contact-statuscode": contact_statuscode,+ "contact-territorycode": contact_territorycode,+}+export type appointment = TableRow<{+ // Primary Key Column+ readonly activityid: string,+ activityadditionalparams: string,+ readonly activitytypecode: string,+ actualdurationminutes: number,+ actualend: Date,+ actualstart: Date,+ readonly attachmentcount: number,+ attachmenterrors: appointment_attachmenterrors,+ category: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ description: string,+ readonly exchangerate: number,+ readonly formattedscheduledend: Date,+ readonly formattedscheduledstart: Date,+ globalobjectid: string,+ readonly instancetypecode: appointment_instancetypecode,+ isalldayevent: appointment_isalldayevent,+ isbilled: appointment_isbilled,+ isdraft: appointment_isdraft,+ ismapiprivate: appointment_ismapiprivate,+ isonlinemeeting: appointment_isonlinemeeting,+ readonly isregularactivity: appointment_isregularactivity,+ readonly isunsafe: number,+ isworkflowcreated: appointment_isworkflowcreated,+ lastonholdtime: Date,+ location: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedfieldsmask: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ readonly onholdtime: number,+ onlinemeetingchatid: string,+ onlinemeetingid: string,+ onlinemeetingjoinurl: string,+ onlinemeetingtype: appointment_onlinemeetingtype,+ readonly originalstartdate: Date,+ outlookownerapptid: number,+ readonly owningbusinessunitname: string,+ prioritycode: appointment_prioritycode,+ processid: string,+ // Foreign Key Column+ _regardingobjectid_value: `/account(${string})` | `/adx_invitation(${string})` | `/bookableresourcebooking(${string})` | `/bookableresourcebookingheader(${string})` | `/bulkoperation(${string})` | `/campaign(${string})` | `/campaignactivity(${string})` | `/contact(${string})` | `/contract(${string})` | `/entitlement(${string})` | `/entitlementtemplate(${string})` | `/incident(${string})` | `/invoice(${string})` | `/knowledgearticle(${string})` | `/knowledgebaserecord(${string})` | `/lead(${string})` | `/msdyn_customerasset(${string})` | `/msdyn_playbookinstance(${string})` | `/msdyn_postalbum(${string})` | `/msdyn_salessuggestion(${string})` | `/msdyn_swarm(${string})` | `/mspp_adplacement(${string})` | `/mspp_pollplacement(${string})` | `/mspp_publishingstatetransitionrule(${string})` | `/mspp_redirect(${string})` | `/mspp_shortcut(${string})` | `/mspp_website(${string})` | `/opportunity(${string})` | `/quote(${string})` | `/salesorder(${string})` | `/site(${string})`,+ readonly regardingobjectidname: string,+ readonly regardingobjectidyominame: string,+ regardingobjecttypecode: string,+ readonly safedescription: string,+ scheduleddurationminutes: number,+ scheduledend: Date,+ scheduledstart: Date,+ readonly seriesid: string,+ // Foreign Key Column+ readonly _serviceid_value: `/service(${string})`,+ readonly serviceidname: string,+ // Foreign Key Column+ readonly _slaid_value: `/sla(${string})`,+ // Foreign Key Column+ readonly _slainvokedid_value: `/sla(${string})`,+ readonly slainvokedidname: string,+ readonly slaname: string,+ sortdate: Date,+ stageid: string,+ statecode: appointment_statecode,+ statuscode: appointment_statuscode,+ subcategory: string,+ subject: string,+ readonly subscriptionid: string,+ // Foreign Key Column+ readonly _transactioncurrencyid_value: `/transactioncurrency(${string})`,+ readonly transactioncurrencyidname: string,+ traversedpath: string,+}>++export type contact = TableRow<{+ // Primary Key Column+ readonly contactid: string,+ // Foreign Key Column+ readonly _accountid_value: `/account(${string})`,+ readonly accountidname: string,+ readonly accountidyominame: string,+ accountrolecode: contact_accountrolecode,+ address1_addressid: string,+ address1_addresstypecode: contact_address1_addresstypecode,+ address1_city: string,+ readonly address1_composite: string,+ address1_country: string,+ address1_county: string,+ address1_fax: string,+ address1_freighttermscode: contact_address1_freighttermscode,+ address1_latitude: number,+ address1_line1: string,+ address1_line2: string,+ address1_line3: string,+ address1_longitude: number,+ address1_name: string,+ address1_postalcode: string,+ address1_postofficebox: string,+ address1_primarycontactname: string,+ address1_shippingmethodcode: contact_address1_shippingmethodcode,+ address1_stateorprovince: string,+ address1_telephone1: string,+ address1_telephone2: string,+ address1_telephone3: string,+ address1_upszone: string,+ address1_utcoffset: number,+ address2_addressid: string,+ address2_addresstypecode: contact_address2_addresstypecode,+ address2_city: string,+ readonly address2_composite: string,+ address2_country: string,+ address2_county: string,+ address2_fax: string,+ address2_freighttermscode: contact_address2_freighttermscode,+ address2_latitude: number,+ address2_line1: string,+ address2_line2: string,+ address2_line3: string,+ address2_longitude: number,+ address2_name: string,+ address2_postalcode: string,+ address2_postofficebox: string,+ address2_primarycontactname: string,+ address2_shippingmethodcode: contact_address2_shippingmethodcode,+ address2_stateorprovince: string,+ address2_telephone1: string,+ address2_telephone2: string,+ address2_telephone3: string,+ address2_upszone: string,+ address2_utcoffset: number,+ address3_addressid: string,+ address3_addresstypecode: contact_address3_addresstypecode,+ address3_city: string,+ readonly address3_composite: string,+ address3_country: string,+ address3_county: string,+ address3_fax: string,+ address3_freighttermscode: contact_address3_freighttermscode,+ address3_latitude: number,+ address3_line1: string,+ address3_line2: string,+ address3_line3: string,+ address3_longitude: number,+ address3_name: string,+ address3_postalcode: string,+ address3_postofficebox: string,+ address3_primarycontactname: string,+ address3_shippingmethodcode: contact_address3_shippingmethodcode,+ address3_stateorprovince: string,+ address3_telephone1: string,+ address3_telephone2: string,+ address3_telephone3: string,+ address3_upszone: string,+ address3_utcoffset: number,+ adx_confirmremovepassword: contact_adx_confirmremovepassword,+ adx_createdbyipaddress: string,+ adx_createdbyusername: string,+ adx_identity_accessfailedcount: number,+ adx_identity_emailaddress1confirmed: contact_adx_identity_emailaddress1confirmed,+ adx_identity_lastsuccessfullogin: Date,+ adx_identity_locallogindisabled: contact_adx_identity_locallogindisabled,+ adx_identity_lockoutenabled: contact_adx_identity_lockoutenabled,+ adx_identity_lockoutenddate: Date,+ adx_identity_logonenabled: contact_adx_identity_logonenabled,+ adx_identity_mobilephoneconfirmed: contact_adx_identity_mobilephoneconfirmed,+ adx_identity_newpassword: string,+ adx_identity_passwordhash: string,+ adx_identity_securitystamp: string,+ adx_identity_twofactorenabled: contact_adx_identity_twofactorenabled,+ adx_identity_username: string,+ adx_modifiedbyipaddress: string,+ adx_modifiedbyusername: string,+ adx_organizationname: string,+ adx_preferredlcid: number,+ adx_profilealert: contact_adx_profilealert,+ adx_profilealertdate: Date,+ adx_profilealertinstructions: string,+ adx_profileisanonymous: contact_adx_profileisanonymous,+ adx_profilelastactivity: Date,+ adx_profilemodifiedon: Date,+ adx_publicprofilecopy: string,+ adx_timezone: number,+ readonly aging30: number,+ readonly aging30_base: number,+ readonly aging60: number,+ readonly aging60_base: number,+ readonly aging90: number,+ readonly aging90_base: number,+ anniversary: Date,+ annualincome: number,+ readonly annualincome_base: number,+ assistantname: string,+ assistantphone: string,+ birthdate: Date,+ business2: string,+ businesscard: string,+ businesscardattributes: string,+ callback: string,+ childrensnames: string,+ company: string,+ // Foreign Key Column+ readonly _createdbyexternalparty_value: `/externalparty(${string})`,+ readonly createdbyexternalpartyname: string,+ readonly createdbyexternalpartyyominame: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ creditlimit: number,+ readonly creditlimit_base: number,+ creditonhold: contact_creditonhold,+ customersizecode: contact_customersizecode,+ customertypecode: contact_customertypecode,+ // Foreign Key Column+ readonly _defaultpricelevelid_value: `/pricelevel(${string})`,+ readonly defaultpricelevelidname: string,+ department: string,+ description: string,+ donotbulkemail: contact_donotbulkemail,+ donotbulkpostalmail: contact_donotbulkpostalmail,+ donotemail: contact_donotemail,+ donotfax: contact_donotfax,+ donotphone: contact_donotphone,+ donotpostalmail: contact_donotpostalmail,+ donotsendmm: contact_donotsendmm,+ educationcode: contact_educationcode,+ emailaddress1: string,+ emailaddress2: string,+ emailaddress3: string,+ employeeid: string,+ // This is an image encoded as a base64 string+ entityimage: string,+ readonly entityimage_timestamp: number,+ readonly entityimage_url: string,+ readonly entityimageid: string,+ readonly exchangerate: number,+ externaluseridentifier: string,+ familystatuscode: contact_familystatuscode,+ fax: string,+ firstname: string,+ followemail: contact_followemail,+ ftpsiteurl: string,+ readonly fullname: string,+ gendercode: contact_gendercode,+ governmentid: string,+ haschildrencode: contact_haschildrencode,+ home2: string,+ readonly isautocreate: contact_isautocreate,+ isbackofficecustomer: contact_isbackofficecustomer,+ readonly isprivate: contact_isprivate,+ jobtitle: string,+ lastname: string,+ lastonholdtime: Date,+ lastusedincampaign: Date,+ leadsourcecode: contact_leadsourcecode,+ managername: string,+ managerphone: string,+ marketingonly: contact_marketingonly,+ readonly mastercontactidname: string,+ readonly mastercontactidyominame: string,+ // Foreign Key Column+ readonly _masterid_value: `/contact(${string})`,+ readonly merged: contact_merged,+ middlename: string,+ mobilephone: string,+ // Foreign Key Column+ readonly _modifiedbyexternalparty_value: `/externalparty(${string})`,+ readonly modifiedbyexternalpartyname: string,+ readonly modifiedbyexternalpartyyominame: string,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ // Foreign Key Column+ readonly _msa_managingpartnerid_value: `/account(${string})`,+ readonly msa_managingpartneridname: string,+ readonly msa_managingpartneridyominame: string,+ // Foreign Key Column+ readonly _msdyn_contactkpiid_value: `/msdyn_contactkpiitem(${string})`,+ readonly msdyn_contactkpiidname: string,+ msdyn_decisioninfluencetag: contact_msdyn_decisioninfluencetag,+ msdyn_disablewebtracking: contact_msdyn_disablewebtracking,+ msdyn_gdproptout: contact_msdyn_gdproptout,+ msdyn_isassistantinorgchart: contact_msdyn_isassistantinorgchart,+ msdyn_isminor: contact_msdyn_isminor,+ msdyn_isminorwithparentalconsent: contact_msdyn_isminorwithparentalconsent,+ msdyn_orgchangestatus: contact_msdyn_orgchangestatus,+ msdyn_portaltermsagreementdate: Date,+ msdyn_primarytimezone: number,+ mspp_userpreferredlcid: contact_mspp_userpreferredlcid,+ nickname: string,+ numberofchildren: number,+ readonly onholdtime: number,+ // Foreign Key Column+ readonly _originatingleadid_value: `/lead(${string})`,+ readonly originatingleadidname: string,+ readonly originatingleadidyominame: string,+ readonly owningbusinessunitname: string,+ pager: string,+ // Foreign Key Column+ readonly _parentcontactid_value: `/contact(${string})`,+ readonly parentcontactidname: string,+ readonly parentcontactidyominame: string,+ // Foreign Key Column+ _parentcustomerid_value: `/account(${string})` | `/contact(${string})`,+ readonly parentcustomeridname: string,+ parentcustomeridtype: string,+ readonly parentcustomeridyominame: string,+ participatesinworkflow: contact_participatesinworkflow,+ paymenttermscode: contact_paymenttermscode,+ preferredappointmentdaycode: contact_preferredappointmentdaycode,+ preferredappointmenttimecode: contact_preferredappointmenttimecode,+ preferredcontactmethodcode: contact_preferredcontactmethodcode,+ // Foreign Key Column+ readonly _preferredequipmentid_value: `/equipment(${string})`,+ readonly preferredequipmentidname: string,+ // Foreign Key Column+ readonly _preferredserviceid_value: `/service(${string})`,+ readonly preferredserviceidname: string,+ // Foreign Key Column+ readonly _preferredsystemuserid_value: `/systemuser(${string})`,+ readonly preferredsystemuseridname: string,+ readonly preferredsystemuseridyominame: string,+ processid: string,+ salutation: string,+ shippingmethodcode: contact_shippingmethodcode,+ // Foreign Key Column+ readonly _slaid_value: `/sla(${string})`,+ // Foreign Key Column+ readonly _slainvokedid_value: `/sla(${string})`,+ readonly slainvokedidname: string,+ readonly slaname: string,+ spousesname: string,+ stageid: string,+ statecode: contact_statecode,+ statuscode: contact_statuscode,+ readonly subscriptionid: string,+ suffix: string,+ teamsfollowed: number,+ telephone1: string,+ telephone2: string,+ telephone3: string,+ territorycode: contact_territorycode,+ readonly timespentbymeonemailandmeetings: string,+ // Foreign Key Column+ readonly _transactioncurrencyid_value: `/transactioncurrency(${string})`,+ readonly transactioncurrencyidname: string,+ traversedpath: string,+ websiteurl: string,+ yomifirstname: string,+ readonly yomifullname: string,+ yomilastname: string,+ yomimiddlename: string,+}>++const enum appointment_attachmenterrors {+"None" = 0,+"The appointment was saved as a Microsoft Dynamics 365 appointment record, but not all the attachments could be saved with it. An attachment cannot be saved if it is blocked or if its file type is invalid." = 1,+}+const enum appointment_instancetypecode {+"Not Recurring" = 0,+"Recurring Master" = 1,+"Recurring Instance" = 2,+"Recurring Exception" = 3,+"Recurring Future Exception" = 4,+}+const enum appointment_isalldayevent {+"No" = 0,+"Yes" = 1,+}+const enum appointment_isbilled {+"No" = 0,+"Yes" = 1,+}+const enum appointment_isdraft {+"No" = 0,+"Yes" = 1,+}+const enum appointment_ismapiprivate {+"No" = 0,+"Yes" = 1,+}+const enum appointment_isonlinemeeting {+"No" = 0,+"Yes" = 1,+}+const enum appointment_isregularactivity {+"No" = 0,+"Yes" = 1,+}+const enum appointment_isworkflowcreated {+"No" = 0,+"Yes" = 1,+}+const enum appointment_onlinemeetingtype {+"Teams Meeting" = 1,+}+const enum appointment_prioritycode {+"Low" = 0,+"Normal" = 1,+"High" = 2,+}+const enum appointment_statecode {+"Open" = 0,+"Completed" = 1,+"Canceled" = 2,+"Scheduled" = 3,+}+const enum appointment_statuscode {+"Free" = 1,+"Tentative" = 2,+"Completed" = 3,+"Canceled" = 4,+"Busy" = 5,+"Out of Office" = 6,+}+const enum contact_accountrolecode {+"Decision Maker" = 1,+"Employee" = 2,+"Influencer" = 3,+}+const enum contact_address1_addresstypecode {+"Bill To" = 1,+"Ship To" = 2,+"Primary" = 3,+"Other" = 4,+}+const enum contact_address1_freighttermscode {+"FOB" = 1,+"No Charge" = 2,+}+const enum contact_address1_shippingmethodcode {+"Airborne" = 1,+"DHL" = 2,+"FedEx" = 3,+"UPS" = 4,+"Postal Mail" = 5,+"Full Load" = 6,+"Will Call" = 7,+}+const enum contact_address2_addresstypecode {+"Default Value" = 1,+}+const enum contact_address2_freighttermscode {+"Default Value" = 1,+}+const enum contact_address2_shippingmethodcode {+"Default Value" = 1,+}+const enum contact_address3_addresstypecode {+"Default Value" = 1,+}+const enum contact_address3_freighttermscode {+"Default Value" = 1,+}+const enum contact_address3_shippingmethodcode {+"Default Value" = 1,+}+const enum contact_adx_confirmremovepassword {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_emailaddress1confirmed {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_locallogindisabled {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_lockoutenabled {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_logonenabled {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_mobilephoneconfirmed {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_identity_twofactorenabled {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_profilealert {+"No" = 0,+"Yes" = 1,+}+const enum contact_adx_profileisanonymous {+"No" = 0,+"Yes" = 1,+}+const enum contact_creditonhold {+"No" = 0,+"Yes" = 1,+}+const enum contact_customersizecode {+"Default Value" = 1,+}+const enum contact_customertypecode {+"Default Value" = 1,+}+const enum contact_donotbulkemail {+"Allow" = 0,+"Do Not Allow" = 1,+}+const enum contact_donotbulkpostalmail {+"No" = 0,+"Yes" = 1,+}+const enum contact_donotemail {+"Allow" = 0,+"Do Not Allow" = 1,+}+const enum contact_donotfax {+"Allow" = 0,+"Do Not Allow" = 1,+}+const enum contact_donotphone {+"Allow" = 0,+"Do Not Allow" = 1,+}+const enum contact_donotpostalmail {+"Allow" = 0,+"Do Not Allow" = 1,+}+const enum contact_donotsendmm {+"Send" = 0,+"Do Not Send" = 1,+}+const enum contact_educationcode {+"Default Value" = 1,+}+const enum contact_familystatuscode {+"Single" = 1,+"Married" = 2,+"Divorced" = 3,+"Widowed" = 4,+}+const enum contact_followemail {+"Do Not Allow" = 0,+"Allow" = 1,+}+const enum contact_gendercode {+"Male" = 1,+"Female" = 2,+}+const enum contact_haschildrencode {+"Default Value" = 1,+}+const enum contact_isautocreate {+"No" = 0,+"Yes" = 1,+}+const enum contact_isbackofficecustomer {+"No" = 0,+"Yes" = 1,+}+const enum contact_isprivate {+"No" = 0,+"Yes" = 1,+}+const enum contact_leadsourcecode {+"Default Value" = 1,+}+const enum contact_marketingonly {+"No" = 0,+"Yes" = 1,+}+const enum contact_merged {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_decisioninfluencetag {+"Decision maker" = 0,+"Influencer" = 1,+"Blocker" = 2,+"Unknown" = 3,+}+const enum contact_msdyn_disablewebtracking {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_gdproptout {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_isassistantinorgchart {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_isminor {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_isminorwithparentalconsent {+"No" = 0,+"Yes" = 1,+}+const enum contact_msdyn_orgchangestatus {+"No Feedback" = 0,+"Not at Company" = 1,+"Ignore" = 2,+}+const enum contact_mspp_userpreferredlcid {+"Arabic" = 1025,+"Basque - Basque" = 1069,+"Bulgarian - Bulgaria" = 1026,+"Catalan - Catalan" = 1027,+"Chinese - China" = 2052,+"Chinese - Hong Kong SAR" = 3076,+"Chinese - Traditional" = 1028,+"Croatian - Croatia" = 1050,+"Czech - Czech Republic" = 1029,+"Danish - Denmark" = 1030,+"Dutch - Netherlands" = 1043,+"English" = 1033,+"Estonian - Estonia" = 1061,+"Finnish - Finland" = 1035,+"French - France" = 1036,+"Galician - Spain" = 1110,+"German - Germany" = 1031,+"Greek - Greece" = 1032,+"Hebrew" = 1037,+"Hindi - India" = 1081,+"Hungarian - Hungary" = 1038,+"Indonesian - Indonesia" = 1057,+"Italian - Italy" = 1040,+"Japanese - Japan" = 1041,+"Kazakh - Kazakhstan" = 1087,+"Korean - Korea" = 1042,+"Latvian - Latvia" = 1062,+"Lithuanian - Lithuania" = 1063,+"Malay - Malaysia" = 1086,+"Norwegian (Bokmål) - Norway" = 1044,+"Polish - Poland" = 1045,+"Portuguese - Brazil" = 1046,+"Portuguese - Portugal" = 2070,+"Romanian - Romania" = 1048,+"Russian - Russia" = 1049,+"Serbian (Cyrillic) - Serbia" = 3098,+"Serbian (Latin) - Serbia" = 2074,+"Slovak - Slovakia" = 1051,+"Slovenian - Slovenia" = 1060,+"Spanish (Traditional Sort) - Spain" = 3082,+"Swedish - Sweden" = 1053,+"Thai - Thailand" = 1054,+"Turkish - Türkiye" = 1055,+"Ukrainian - Ukraine" = 1058,+"Vietnamese - Vietnam" = 1066,+}+const enum contact_participatesinworkflow {+"No" = 0,+"Yes" = 1,+}+const enum contact_paymenttermscode {+"Net 30" = 1,+"2% 10, Net 30" = 2,+"Net 45" = 3,+"Net 60" = 4,+}+const enum contact_preferredappointmentdaycode {+"Sunday" = 0,+"Monday" = 1,+"Tuesday" = 2,+"Wednesday" = 3,+"Thursday" = 4,+"Friday" = 5,+"Saturday" = 6,+}+const enum contact_preferredappointmenttimecode {+"Morning" = 1,+"Afternoon" = 2,+"Evening" = 3,+}+const enum contact_preferredcontactmethodcode {+"Any" = 1,+"Email" = 2,+"Phone" = 3,+"Fax" = 4,+"Mail" = 5,+}+const enum contact_shippingmethodcode {+"Default Value" = 1,+}+const enum contact_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum contact_statuscode {+"Active" = 1,+"Inactive" = 2,+}+const enum contact_territorycode {+"Default Value" = 1,+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+}+diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/candidate-list.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/candidate-list.tsxnew file mode 100644index 000000000..57c37ba4e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/candidate-list.tsx@@ -0,0 +1,614 @@+import { useEffect, useState } from 'react';+import type {+ TableRow,+ ReadableTableRow,+ GeneratedComponentProps,+} from './RuntimeTypes';+import {+ makeStyles,+ tokens,+ Text,+ Spinner,+ Button,+ Badge,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+ SearchBox,+ Select,+ Label,+ Divider,+} from '@fluentui/react-components';+import {+ SearchRegular,+ PersonRegular,+ ArrowPreviousRegular,+ ArrowNextRegular,+ FilterRegular,+ ArrowClockwiseRegular,+} from '@fluentui/react-icons';++// ---------- Row Type ----------++type ContactRow = TableRow<{+ readonly contactid: string;+ readonly fullname: string;+ emailaddress1: string;+ telephone1: string;+ jobtitle: string;+ statuscode: number;+}>;++type ReadableContact = ReadableTableRow<ContactRow>;++// ---------- Module-level cache ----------+// Persisted on window so data survives module re-evaluation on back-navigation.+const CACHE_KEY = '__ppCandidateListCache';+const winAny = window as unknown as Record<string, ReadableContact[] | undefined>;+let _candidateCache: ReadableContact[] | null = winAny[CACHE_KEY] ?? null;++// ---------- Constants ----------++const PAGE_SIZE = 50;++// ---------- Styles ----------++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingHorizontalXL,+ width: '100%',+ boxSizing: 'border-box',+ },+ pageHeader: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ paddingBottom: tokens.spacingVerticalS,+ },+ pageTitle: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ toolbar: {+ display: 'flex',+ alignItems: 'center',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ padding: `${tokens.spacingVerticalS} 0`,+ },+ toolbarLeft: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ flex: '1 1 300px',+ minWidth: '220px',+ },+ toolbarRight: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ flexWrap: 'wrap',+ },+ filterGroup: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ searchBox: {+ flex: '1 1 220px',+ maxWidth: '320px',+ },+ select: {+ minWidth: '160px',+ },+ gridContainer: {+ overflowX: 'auto',+ width: '100%',+ },+ spinnerWrap: {+ display: 'flex',+ justifyContent: 'center',+ padding: tokens.spacingVerticalXXL,+ },+ errorBanner: {+ padding: tokens.spacingHorizontalM,+ backgroundColor: tokens.colorStatusDangerBackground2,+ color: tokens.colorStatusDangerForeground2,+ borderRadius: tokens.borderRadiusMedium,+ },+ emptyState: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingVerticalXXL,+ color: tokens.colorNeutralForeground3,+ },+ emptyIcon: {+ fontSize: '48px',+ color: tokens.colorNeutralForeground4,+ },+ pagination: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'flex-end',+ gap: tokens.spacingHorizontalS,+ paddingTop: tokens.spacingVerticalS,+ },+ rowClickable: {+ cursor: 'pointer',+ },+ nameCell: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ resultCount: {+ color: tokens.colorNeutralForeground3,+ },+ headerActions: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+});++// ---------- Utility Functions ----------++function getStatusBadge(statuscode: number | undefined) {+ if (statuscode === 1) {+ return (+ <Badge appearance="filled" color="success" size="small">+ Active+ </Badge>+ );+ }+ return (+ <Badge appearance="filled" color="subtle" size="small">+ Inactive+ </Badge>+ );+}++function getUniqueJobTitles(records: ReadableContact[]): string[] {+ const titles = new Set<string>();+ for (const r of records) {+ const t = r.jobtitle;+ if (t && typeof t === 'string' && t.trim() !== '') {+ titles.add(t.trim());+ }+ }+ return Array.from(titles).sort((a, b) => a.localeCompare(b));+}++// ---------- Sub-components ----------++function EmptyState({ message }: { message: string }) {+ const styles = useStyles();+ return (+ <div className={styles.emptyState} role="status" aria-live="polite">+ <PersonRegular className={styles.emptyIcon} aria-hidden="true" />+ <Text size={400} weight="semibold">+ No candidates found+ </Text>+ <Text size={300} style={{ color: tokens.colorNeutralForeground3 }}>+ {message}+ </Text>+ </div>+ );+}++// ---------- Main Component ----------++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page — no input record needed; destructured per rules++ const styles = useStyles();++ const [data, setData] = useState<{+ records: ReadableContact[];+ loading: boolean;+ error: string | null;+ }>({+ records: _candidateCache ?? [],+ loading: _candidateCache === null,+ error: null,+ });++ const [searchText, setSearchText] = useState('');+ const [jobTitleFilter, setJobTitleFilter] = useState('');+ const [statusFilter, setStatusFilter] = useState('');+ const [currentPage, setCurrentPage] = useState(1);++ // ---------- Data fetch with caching ----------+ useEffect(() => {+ if (_candidateCache !== null) return; // cache hit — no fetch needed++ (async () => {+ try {+ const result = await dataApi.queryTable('contact', {+ select: [+ 'contactid',+ 'fullname',+ 'emailaddress1',+ 'telephone1',+ 'jobtitle',+ 'statuscode',+ ],+ orderBy: 'fullname asc',+ pageSize: 500,+ });+ _candidateCache = result.rows as ReadableContact[];+ winAny[CACHE_KEY] = _candidateCache;+ setData({ records: _candidateCache, loading: false, error: null });+ } catch (err) {+ const message =+ err instanceof Error ? err.message : 'Failed to load candidates.';+ setData({ records: [], loading: false, error: message });+ }+ })();+ }, [dataApi]);++ // ---------- Refresh handler ----------+ const handleRefresh = () => {+ _candidateCache = null;+ delete winAny[CACHE_KEY];+ setData({ records: [], loading: true, error: null });+ setCurrentPage(1);++ (async () => {+ try {+ const result = await dataApi.queryTable('contact', {+ select: [+ 'contactid',+ 'fullname',+ 'emailaddress1',+ 'telephone1',+ 'jobtitle',+ 'statuscode',+ ],+ orderBy: 'fullname asc',+ pageSize: 500,+ });+ _candidateCache = result.rows as ReadableContact[];+ winAny[CACHE_KEY] = _candidateCache;+ setData({ records: _candidateCache, loading: false, error: null });+ } catch (err) {+ const message =+ err instanceof Error ? err.message : 'Failed to load candidates.';+ setData({ records: [], loading: false, error: message });+ }+ })();+ };++ // ---------- Filtering ----------+ const filtered = data.records.filter((c) => {+ if (searchText) {+ const term = searchText.toLowerCase();+ const nameMatch = typeof c.fullname === 'string' && c.fullname.toLowerCase().includes(term);+ const emailMatch = typeof c.emailaddress1 === 'string' && c.emailaddress1.toLowerCase().includes(term);+ const titleMatch = typeof c.jobtitle === 'string' && c.jobtitle.toLowerCase().includes(term);+ if (!nameMatch && !emailMatch && !titleMatch) return false;+ }+ if (jobTitleFilter && c.jobtitle !== jobTitleFilter) return false;+ if (statusFilter !== '') {+ const code = Number(statusFilter);+ if (c.statuscode !== code) return false;+ }+ return true;+ });++ // ---------- Pagination ----------+ const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));+ const safePage = Math.min(currentPage, totalPages);+ const pageStart = (safePage - 1) * PAGE_SIZE;+ const pageEnd = pageStart + PAGE_SIZE;+ const pageRecords = filtered.slice(pageStart, pageEnd);++ // Reset to page 1 when filters change+ const handleSearchChange = (_: unknown, d: { value?: string }) => {+ setSearchText(d.value ?? '');+ setCurrentPage(1);+ };++ const handleJobTitleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {+ setJobTitleFilter(e.target.value);+ setCurrentPage(1);+ };++ const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {+ setStatusFilter(e.target.value);+ setCurrentPage(1);+ };++ // ---------- Navigation ----------+ const openContactRecord = (contactId: string) => {+ const xrm = (+ window as unknown as {+ Xrm?: { Navigation?: { navigateTo: (opts: unknown) => void } };+ }+ ).Xrm;+ xrm?.Navigation?.navigateTo({+ pageType: 'entityrecord',+ entityName: 'contact',+ entityId: contactId,+ });+ };++ // ---------- Columns ----------+ const columns = [+ createTableColumn<ReadableContact>({+ columnId: 'fullname',+ renderHeaderCell: () => 'Name',+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: 'hidden', minWidth: 0 }}>+ <span+ style={{+ display: 'block',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ fontWeight: tokens.fontWeightSemibold,+ }}+ title={typeof item.fullname === 'string' ? item.fullname : ''}+ >+ {item.fullname ?? '—'}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableContact>({+ columnId: 'jobtitle',+ renderHeaderCell: () => 'Job title',+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: 'hidden', minWidth: 0 }}>+ <span+ style={{+ display: 'block',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ title={typeof item.jobtitle === 'string' ? item.jobtitle : ''}+ >+ {item.jobtitle || '—'}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableContact>({+ columnId: 'emailaddress1',+ renderHeaderCell: () => 'Email',+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: 'hidden', minWidth: 0 }}>+ <span+ style={{+ display: 'block',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ title={typeof item.emailaddress1 === 'string' ? item.emailaddress1 : ''}+ >+ {item.emailaddress1 || '—'}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableContact>({+ columnId: 'telephone1',+ renderHeaderCell: () => 'Phone',+ renderCell: (item) => (+ <TableCellLayout>+ {item.telephone1 || '—'}+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableContact>({+ columnId: 'statuscode',+ renderHeaderCell: () => 'Status',+ renderCell: (item) => (+ <TableCellLayout>+ {getStatusBadge(typeof item.statuscode === 'number' ? item.statuscode : undefined)}+ </TableCellLayout>+ ),+ }),+ ];++ const jobTitleOptions = getUniqueJobTitles(data.records);++ // ---------- Loading state ----------+ if (data.loading) {+ return (+ <div className={styles.root}>+ <div className={styles.spinnerWrap}>+ <Spinner labelPosition="below" label="Loading candidates..." />+ </div>+ </div>+ );+ }++ // ---------- Render ----------+ return (+ <div className={styles.root}>+ {/* Page header */}+ <header className={styles.pageHeader}>+ <div className={styles.pageTitle}>+ <PersonRegular aria-hidden="true" style={{ fontSize: '24px', color: tokens.colorBrandForeground1 }} />+ <Text as="h1" size={700} weight="semibold">+ Candidates+ </Text>+ {!data.loading && (+ <Text size={300} className={styles.resultCount}>+ ({data.records.length} total)+ </Text>+ )}+ </div>+ <div className={styles.headerActions}>+ <Button+ appearance="subtle"+ icon={<ArrowClockwiseRegular />}+ onClick={handleRefresh}+ aria-label="Refresh candidate list"+ >+ Refresh+ </Button>+ </div>+ </header>++ <Divider />++ {/* Error banner */}+ {data.error && (+ <div role="alert" className={styles.errorBanner}>+ <Text weight="semibold">Error:</Text> {data.error}+ </div>+ )}++ {/* Toolbar: search + filters */}+ <div className={styles.toolbar} role="search" aria-label="Filter candidates">+ <div className={styles.toolbarLeft}>+ <SearchBox+ className={styles.searchBox}+ placeholder="Search by name, email, or title"+ value={searchText}+ onChange={handleSearchChange}+ contentBefore={<SearchRegular aria-hidden="true" />}+ aria-label="Search candidates"+ />+ </div>+ <div className={styles.toolbarRight}>+ <div className={styles.filterGroup}>+ <FilterRegular aria-hidden="true" style={{ color: tokens.colorNeutralForeground3 }} />+ <Label htmlFor="job-title-filter">Job title</Label>+ <Select+ id="job-title-filter"+ className={styles.select}+ value={jobTitleFilter}+ onChange={handleJobTitleChange}+ aria-label="Filter by job title"+ >+ <option value="">All titles</option>+ {jobTitleOptions.map((title) => (+ <option key={title} value={title}>+ {title}+ </option>+ ))}+ </Select>+ </div>+ <div className={styles.filterGroup}>+ <Label htmlFor="status-filter">Status</Label>+ <Select+ id="status-filter"+ className={styles.select}+ value={statusFilter}+ onChange={handleStatusChange}+ aria-label="Filter by status"+ >+ <option value="">All statuses</option>+ <option value="1">Active</option>+ <option value="2">Inactive</option>+ </Select>+ </div>+ </div>+ </div>++ {/* Result count */}+ {(searchText || jobTitleFilter || statusFilter !== '') && (+ <Text size={200} className={styles.resultCount} aria-live="polite" aria-atomic="true">+ Showing {filtered.length} of {data.records.length} candidates+ </Text>+ )}++ {/* Grid */}+ {filtered.length === 0 ? (+ <EmptyState+ message={+ searchText || jobTitleFilter || statusFilter !== ''+ ? 'No candidates match your current filters. Try adjusting the search or filter criteria.'+ : 'No candidate records found in the system.'+ }+ />+ ) : (+ <div className={styles.gridContainer}>+ <DataGrid+ items={pageRecords}+ columns={columns}+ getRowId={(row) => row.contactid as string}+ resizableColumns+ columnSizingOptions={{+ fullname: { idealWidth: 220, minWidth: 160 },+ jobtitle: { idealWidth: 200, minWidth: 140 },+ emailaddress1: { idealWidth: 240, minWidth: 160 },+ telephone1: { idealWidth: 160, minWidth: 120 },+ statuscode: { idealWidth: 100, minWidth: 80 },+ }}+ aria-label="Candidate list"+ aria-rowcount={filtered.length}+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<ReadableContact>>+ {({ item }) => (+ <DataGridRow<ReadableContact>+ key={item.contactid as string}+ className={styles.rowClickable}+ onClick={() => openContactRecord(item.contactid as string)}+ aria-label={`Open record for ${item.fullname ?? 'candidate'}`}+ style={{ cursor: 'pointer' }}+ >+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ </div>+ )}++ {/* Pagination */}+ {filtered.length > PAGE_SIZE && (+ <nav className={styles.pagination} aria-label="Pagination">+ <Text size={200} className={styles.resultCount}>+ Page {safePage} of {totalPages} ({filtered.length} results)+ </Text>+ <Button+ appearance="subtle"+ icon={<ArrowPreviousRegular />}+ disabled={safePage <= 1}+ onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}+ aria-label="Previous page"+ />+ <Button+ appearance="subtle"+ icon={<ArrowNextRegular />}+ disabled={safePage >= totalPages}+ onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}+ aria-label="Next page"+ />+ </nav>+ )}+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.mdnew file mode 100644index 000000000..ee46bab46--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/genpage-plan.md@@ -0,0 +1,77 @@+# Genpage Plan++## User Requirements+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.++## Working Directory+D:/temp/recruitment-app++## Plugin Root+D:/Projects/power-platform-skills/plugins/model-apps++## Environment+- URL: https://aurorabapenv610b3.crmtest.dynamics.com+- App: create new: Recruitment App+- Languages: English (1033) only+- Solution: Crdec34+- Publisher Prefix: crb2b++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Candidate List | candidate-list.tsx | Searchable, filterable list of candidates (Contact records) showing name, email, phone, job title, and status | contact |+| Interview Schedule | interview-schedule.tsx | Grid view of scheduled interviews (Appointment records) showing subject, start/end time, location, and linked candidate | appointment, contact |+| Hiring Metrics Dashboard | hiring-metrics-dashboard.tsx | Read-only dashboard summarizing recruitment KPIs: total candidates, interviews scheduled, pipeline stage breakdown, and recent activity | contact, appointment |++## Entity Creation Required+No entity creation required — all entities already exist.++## Existing Entities+contact, appointment++## Design Preferences+- Styling: Clean, professional recruitment theme using Fluent UI V9 components; neutral palette (white backgrounds, subtle grays, blue accents); card-based layouts where appropriate+- Features: Candidate List — text search by name, filter by job title/status, clickable rows to open Contact record; Interview Schedule — sortable columns (date, candidate, subject), date-range filter, rows grouped by day; Hiring Metrics Dashboard — summary stat cards (total candidates, total interviews), bar chart for pipeline stage breakdown, recent appointments list+- Accessibility: WCAG AA defaults — focusable interactive elements, aria-labels on icon-only controls, sufficient color contrast++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Candidate List | 9-list-with-caching.tsx | List page backed by Dataverse with search, caching, and row click navigation |+| Interview Schedule | 1-account-grid.tsx | Grid layout with sortable columns and Dataverse data binding |+| Hiring Metrics Dashboard | 8-dashboard-with-charts.tsx | Dashboard layout with stat cards and chart components |++## Per-Page Specifications++### Candidate List+- **File:** candidate-list.tsx+- **Purpose:** Searchable, filterable list of Contact records representing job candidates+- **Entities:** contact+- **Needs caching:** true+- **Key Features:** Text search filtering by fullname; dropdown filter for jobtitle; status badge showing contact status; clickable rows that navigate to the Contact record; empty state when no results; loading skeleton during fetch+- **Components:** SearchBox, Dropdown, DataGrid, TableRow, TableCell, Badge, Spinner, Text, Button (Fluent UI V9)+- **Layout:** Full-width single-column; search and filter controls in a toolbar above the grid; responsive — on narrow screens the filter Dropdown stacks below SearchBox+- **Data Binding:** queryTable on contact entity; retrieve fields: contactid, fullname, emailaddress1, telephone1, jobtitle, statuscode; order by fullname ascending; client-side filter for search and jobtitle+- **Interactions:** Row click opens the Contact record (navigateToRecord); SearchBox onChange filters displayed rows; Dropdown onChange filters by jobtitle; pagination with Next/Previous if record count > 50++### Interview Schedule+- **File:** interview-schedule.tsx+- **Purpose:** Grid view of Appointment records representing scheduled interviews, grouped by day+- **Entities:** appointment, contact+- **Needs caching:** true+- **Key Features:** Appointments displayed in a sortable grid; columns: Subject, Candidate (regardingobjectid linked to contact), Scheduled Start, Scheduled End, Location, Status; date-range filter (start date / end date pickers); rows grouped by calendar day; clickable rows to open the Appointment record; empty state when no appointments in range+- **Components:** DataGrid, TableRow, TableCell, DatePicker, Dropdown (status filter), Divider, Text, Badge, Spinner (Fluent UI V9)+- **Layout:** Full-width; filter bar (date range pickers + status dropdown) above the grid; day-group headers as styled dividers; responsive stacking on narrow screens+- **Data Binding:** queryTable on appointment entity; retrieve fields: activityid, subject, scheduledstart, scheduledend, location, statuscode, regardingobjectid; filter by scheduledstart between user-selected date range; order by scheduledstart ascending; optionally expand regardingobjectid to get contact fullname+- **Interactions:** Column header click to sort; DatePicker onChange to filter by date range; status Dropdown onChange to filter; row click navigates to Appointment record (navigateToRecord)++### Hiring Metrics Dashboard+- **File:** hiring-metrics-dashboard.tsx+- **Purpose:** Read-only dashboard showing recruitment KPIs derived from Contact and Appointment records+- **Entities:** contact, appointment+- **Needs caching:** false+- **Key Features:** Four summary stat cards: Total Active Candidates (contact count with statuscode=active), Interviews This Month (appointment count with scheduledstart in current month), Interviews This Week, Open Positions (placeholder from contact jobtitle distinct count); a bar chart showing candidate count grouped by jobtitle (top 5); a recent activity list showing the 5 most recently created appointments with subject, candidate, and scheduled start+- **Components:** Card, CardHeader, Text, ProgressBar or BarChart (via @fluentui/react-charts or inline SVG fallback), List, Spinner, Divider, Badge (Fluent UI V9)+- **Layout:** Responsive CSS grid: 2-column on desktop (stat cards in top row, chart left, recent list right), single-column on mobile; section headings for "At a Glance", "Pipeline by Role", "Recent Interviews"+- **Data Binding:** Two separate queryTable calls — one for contact (retrieve: contactid, jobtitle, statuscode, createdon; filter statuscode=active) and one for appointment (retrieve: activityid, subject, scheduledstart, regardingobjectid, createdon; order by createdon descending, top 10); metrics computed client-side from results+- **Interactions:** Refresh button to re-fetch data; stat card click optionally deep-links to the respective list page (candidate-list.tsx or interview-schedule.tsx); no edit actions — dashboard is read-onlydiff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/hiring-metrics-dashboard.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/hiring-metrics-dashboard.tsxnew file mode 100644index 000000000..8d86b03e9--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/hiring-metrics-dashboard.tsx@@ -0,0 +1,679 @@+import { useEffect, useRef, useState } from 'react';+import type {+ ReadableTableRow,+ GeneratedComponentProps,+} from "./RuntimeTypes";+import {+ makeStyles,+ tokens,+ Text,+ Card,+ CardHeader,+ Button,+ Spinner,+ Badge,+ Divider,+} from '@fluentui/react-components';+import {+ PeopleRegular,+ CalendarRegular,+ ArrowClockwiseRegular,+ BriefcaseRegular,+ CalendarCheckmarkRegular,+} from '@fluentui/react-icons';+import * as d3 from 'd3';++// ---------- Types ----------++type ContactRow = ReadableTableRow<"contact">;+type AppointmentRow = ReadableTableRow<"appointment">;++interface DashboardProps extends GeneratedComponentProps {+ pageInput?: { entityName?: string; recordId?: string; data?: Record<string, unknown> };+}++interface DashboardData {+ contacts: ContactRow[];+ appointments: AppointmentRow[];+ loading: boolean;+ error: string | null;+}++interface RoleCount {+ role: string;+ count: number;+}++// ---------- Styles ----------++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalL,+ padding: tokens.spacingHorizontalXL,+ width: '100%',+ boxSizing: 'border-box',+ },+ titleRow: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalM,+ },+ sectionHeading: {+ marginTop: tokens.spacingVerticalS,+ marginBottom: tokens.spacingVerticalXS,+ color: tokens.colorNeutralForeground2,+ },+ statRow: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalL,+ },+ statCard: {+ flex: '1 1 200px',+ padding: tokens.spacingHorizontalL,+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXS,+ cursor: 'pointer',+ ':hover': {+ boxShadow: tokens.shadow8,+ },+ },+ statLabel: {+ color: tokens.colorNeutralForeground2,+ fontSize: tokens.fontSizeBase300,+ },+ statValue: {+ fontSize: tokens.fontSizeHero900,+ fontWeight: tokens.fontWeightSemibold,+ color: tokens.colorBrandForeground1,+ lineHeight: '1',+ },+ statSubLabel: {+ color: tokens.colorNeutralForeground3,+ fontSize: tokens.fontSizeBase200,+ },+ iconWrapper: {+ color: tokens.colorBrandForeground1,+ fontSize: '20px',+ display: 'flex',+ alignItems: 'center',+ },+ mainRow: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalL,+ alignItems: 'flex-start',+ },+ chartCard: {+ flex: '2 1 360px',+ minWidth: '0',+ },+ recentCard: {+ flex: '1 1 280px',+ minWidth: '0',+ },+ chartSvg: {+ width: '100%',+ height: '260px',+ display: 'block',+ },+ activityList: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ marginTop: tokens.spacingVerticalS,+ },+ activityItem: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXXS,+ padding: `${tokens.spacingVerticalS} 0`,+ },+ activitySubject: {+ fontWeight: tokens.fontWeightSemibold,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ activityMeta: {+ color: tokens.colorNeutralForeground3,+ fontSize: tokens.fontSizeBase200,+ },+ emptyState: {+ textAlign: 'center',+ padding: tokens.spacingVerticalXL,+ color: tokens.colorNeutralForeground3,+ },+ errorBanner: {+ padding: tokens.spacingHorizontalM,+ backgroundColor: tokens.colorPaletteRedBackground1,+ color: tokens.colorPaletteRedForeground1,+ borderRadius: tokens.borderRadiusMedium,+ },+ loadingContainer: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '200px',+ },+ badgeWrapper: {+ marginTop: tokens.spacingVerticalXXS,+ },+});++// ---------- Helpers ----------++function formatDate(value: unknown): string {+ if (!value) return '—';+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return '—';+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' });+}++function formatDateShort(value: unknown): string {+ if (!value) return '—';+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return '—';+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+}++function isThisMonth(value: unknown): boolean {+ if (!value) return false;+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return false;+ const now = new Date();+ return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();+}++function isThisWeek(value: unknown): boolean {+ if (!value) return false;+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return false;+ const now = new Date();+ const startOfWeek = new Date(now);+ startOfWeek.setHours(0, 0, 0, 0);+ startOfWeek.setDate(now.getDate() - now.getDay());+ const endOfWeek = new Date(startOfWeek);+ endOfWeek.setDate(startOfWeek.getDate() + 7);+ return d >= startOfWeek && d < endOfWeek;+}++function getTopRoles(contacts: ContactRow[], topN: number): RoleCount[] {+ const counts = new Map<string, number>();+ for (const c of contacts) {+ const role = (c['jobtitle'] as string) || 'Unspecified';+ counts.set(role, (counts.get(role) ?? 0) + 1);+ }+ return Array.from(counts.entries())+ .map(([role, count]) => ({ role, count }))+ .sort((a, b) => b.count - a.count)+ .slice(0, topN);+}++// ---------- Stat Card ----------++interface StatCardProps {+ icon: React.ReactNode;+ label: string;+ value: number | string;+ subLabel?: string;+ onClick?: () => void;+}++function StatCard(props: StatCardProps) {+ const styles = useStyles();+ return (+ <Card+ className={styles.statCard}+ onClick={props.onClick}+ role={props.onClick ? 'button' : undefined}+ tabIndex={props.onClick ? 0 : undefined}+ onKeyDown={props.onClick ? (e) => { if (e.key === 'Enter' || e.key === ' ') props.onClick!(); } : undefined}+ aria-label={`${props.label}: ${props.value}${props.subLabel ? `, ${props.subLabel}` : ''}`}+ >+ <CardHeader+ image={<span className={styles.iconWrapper}>{props.icon}</span>}+ header={<Text className={styles.statLabel}>{props.label}</Text>}+ />+ <Text className={styles.statValue}>{props.value}</Text>+ {props.subLabel && (+ <Text className={styles.statSubLabel}>{props.subLabel}</Text>+ )}+ </Card>+ );+}++// ---------- Pipeline Bar Chart ----------++const BAR_CHART_ANIM_KEY = '__ppHiringBarChartAnimated';++interface PipelineBarChartProps {+ data: RoleCount[];+}++function PipelineBarChart(props: PipelineBarChartProps) {+ const styles = useStyles();+ const svgRef = useRef<SVGSVGElement>(null);++ useEffect(() => {+ const node = svgRef.current;+ if (!node) return;+ if (props.data.length === 0) return;++ const svg = d3.select(node);+ const w = window as unknown as Record<string, boolean>;++ if (w[BAR_CHART_ANIM_KEY] && svg.selectAll('rect.bar').size() > 0) return;+ const shouldAnimate = !w[BAR_CHART_ANIM_KEY];+ w[BAR_CHART_ANIM_KEY] = true;++ svg.selectAll('*').remove();++ const rect = node.getBoundingClientRect();+ const width = rect.width || 480;+ const height = rect.height || 260;+ const margin = { top: 16, right: 24, bottom: 64, 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.scaleBand()+ .domain(props.data.map(d => d.role))+ .range([0, innerW])+ .padding(0.3);++ const y = d3.scaleLinear()+ .domain([0, (d3.max(props.data, d => d.count) ?? 1) * 1.15])+ .range([innerH, 0])+ .nice();++ // X axis+ g.append('g')+ .attr('transform', `translate(0,${innerH})`)+ .call(d3.axisBottom(x))+ .attr('color', tokens.colorNeutralForeground3)+ .selectAll('text')+ .attr('font-size', '11px')+ .attr('fill', tokens.colorNeutralForeground2)+ .attr('dy', '1em')+ .call((textSel) => {+ textSel.each(function () {+ const textNode = d3.select(this);+ const label = textNode.text();+ if (label.length > 14) {+ textNode.text(label.slice(0, 13) + '…');+ }+ });+ });++ // Y axis+ g.append('g')+ .call(d3.axisLeft(y).ticks(5).tickFormat(d => String(d)))+ .attr('color', tokens.colorNeutralForeground3)+ .selectAll('text')+ .attr('font-size', '11px')+ .attr('fill', tokens.colorNeutralForeground2);++ // Grid lines+ g.append('g')+ .attr('class', 'grid')+ .call(+ d3.axisLeft(y)+ .ticks(5)+ .tickSize(-innerW)+ .tickFormat(() => '')+ )+ .attr('color', tokens.colorNeutralStroke2)+ .selectAll('line')+ .attr('stroke-dasharray', '3,3')+ .attr('opacity', 0.5);+ g.select('.grid .domain').remove();++ // Bars+ const bars = g.selectAll('rect.bar')+ .data(props.data)+ .enter()+ .append('rect')+ .attr('class', 'bar')+ .attr('x', d => x(d.role) ?? 0)+ .attr('width', x.bandwidth())+ .attr('rx', tokens.borderRadiusSmall)+ .attr('fill', tokens.colorBrandBackground);++ if (shouldAnimate) {+ bars+ .attr('y', innerH)+ .attr('height', 0)+ .transition()+ .duration(600)+ .delay((_, i) => i * 80)+ .attr('y', d => y(d.count))+ .attr('height', d => innerH - y(d.count));+ } else {+ bars+ .attr('y', d => y(d.count))+ .attr('height', d => innerH - y(d.count));+ }++ // Value labels on bars+ g.selectAll('text.bar-label')+ .data(props.data)+ .enter()+ .append('text')+ .attr('class', 'bar-label')+ .attr('x', d => (x(d.role) ?? 0) + x.bandwidth() / 2)+ .attr('y', d => y(d.count) - 4)+ .attr('text-anchor', 'middle')+ .attr('fill', tokens.colorNeutralForeground1)+ .attr('font-size', '12px')+ .attr('font-weight', '600')+ .text(d => String(d.count));++ }, [props.data]);++ if (props.data.length === 0) {+ return null;+ }++ return (+ <svg+ ref={svgRef}+ className={styles.chartSvg}+ role="img"+ aria-label="Pipeline by role — candidate count per job title"+ />+ );+}++// ---------- Recent Activity Item ----------++interface ActivityItemProps {+ subject: string;+ candidateName: string;+ scheduledStart: unknown;+ statecode: number;+}++function ActivityItem(props: ActivityItemProps) {+ const styles = useStyles();+ const statusLabel = props.statecode === 3 ? 'Scheduled'+ : props.statecode === 1 ? 'Completed'+ : props.statecode === 2 ? 'Canceled'+ : 'Open';+ const statusAppearance: 'informative' | 'success' | 'danger' | 'warning' =+ props.statecode === 3 ? 'informative'+ : props.statecode === 1 ? 'success'+ : props.statecode === 2 ? 'danger'+ : 'warning';++ return (+ <div className={styles.activityItem}>+ <Text className={styles.activitySubject} title={props.subject}>+ {props.subject || '(No subject)'}+ </Text>+ <Text className={styles.activityMeta}>+ {props.candidateName || 'No candidate linked'} · {formatDate(props.scheduledStart)}+ </Text>+ <span className={styles.badgeWrapper}>+ <Badge appearance="tint" color={statusAppearance} size="small">+ {statusLabel}+ </Badge>+ </span>+ </div>+ );+}++// ---------- Main Component ----------++const GeneratedComponent = (props: DashboardProps) => {+ const { dataApi, pageInput } = props;+ void pageInput;++ const [{ contacts, appointments, loading, error }, setData] = useState<DashboardData>({+ contacts: [],+ appointments: [],+ loading: true,+ error: null,+ });++ useEffect(() => {+ if (!dataApi) return;++ (async () => {+ try {+ const [contactResult, apptResult] = await Promise.all([+ dataApi.queryTable("contact", {+ select: ["contactid", "fullname", "jobtitle", "statuscode", "statecode"],+ filter: "statecode eq 0",+ pageSize: 500,+ }),+ dataApi.queryTable("appointment", {+ select: ["activityid", "subject", "scheduledstart", "_regardingobjectid_value", "statecode"],+ orderBy: "scheduledstart desc",+ pageSize: 10,+ }),+ ]);++ setData({+ contacts: contactResult.rows as ContactRow[],+ appointments: apptResult.rows as AppointmentRow[],+ loading: false,+ error: null,+ });+ } catch (err) {+ setData({+ contacts: [],+ appointments: [],+ loading: false,+ error: "Failed to load dashboard data. Please try refreshing.",+ });+ }+ })();+ }, [dataApi]);++ const styles = useStyles();++ function handleRefresh() {+ setData({ contacts: [], appointments: [], loading: true, error: null });+ if (!dataApi) return;++ (async () => {+ try {+ const [contactResult, apptResult] = await Promise.all([+ dataApi.queryTable("contact", {+ select: ["contactid", "fullname", "jobtitle", "statuscode", "statecode"],+ filter: "statecode eq 0",+ pageSize: 500,+ }),+ dataApi.queryTable("appointment", {+ select: ["activityid", "subject", "scheduledstart", "_regardingobjectid_value", "statecode"],+ orderBy: "scheduledstart desc",+ pageSize: 10,+ }),+ ]);++ setData({+ contacts: contactResult.rows as ContactRow[],+ appointments: apptResult.rows as AppointmentRow[],+ loading: false,+ error: null,+ });+ } catch (err) {+ setData({+ contacts: [],+ appointments: [],+ loading: false,+ error: "Failed to load dashboard data. Please try refreshing.",+ });+ }+ })();+ }++ function navigateToCandidates() {+ const xrm = (window as any).Xrm;+ xrm?.Navigation?.navigateTo({+ pageType: "generative",+ pageId: "492d8c42-b5fc-4ec5-ad44-6809c6673e9a",+ });+ }++ function navigateToSchedule() {+ const xrm = (window as any).Xrm;+ xrm?.Navigation?.navigateTo({+ pageType: "generative",+ pageId: "07ad1d40-5ca8-494a-aeac-ff0548acb6c0",+ });+ }++ // --- Computed metrics ---+ const totalActiveCandidates = contacts.length;+ const interviewsThisMonth = appointments.filter(a => isThisMonth(a['scheduledstart'])).length;+ const interviewsThisWeek = appointments.filter(a => isThisWeek(a['scheduledstart'])).length;+ const openRoles = (() => {+ const titles = new Set<string>();+ for (const c of contacts) {+ const title = c['jobtitle'] as string;+ if (title && title.trim()) titles.add(title.trim());+ }+ return titles.size;+ })();+ const topRoles = getTopRoles(contacts, 5);++ // Recent 5 appointments (already ordered desc by scheduledstart from API, take first 5)+ const recentAppointments = appointments.slice(0, 5);++ if (loading) {+ return (+ <div className={styles.loadingContainer} role="status" aria-label="Loading dashboard data">+ <Spinner label="Loading recruitment dashboard…" size="large" />+ </div>+ );+ }++ return (+ <main className={styles.root}>+ {/* Title + refresh */}+ <div className={styles.titleRow}>+ <Text as="h1" size={700} weight="semibold">+ Hiring metrics dashboard+ </Text>+ <Button+ icon={<ArrowClockwiseRegular />}+ onClick={handleRefresh}+ appearance="subtle"+ aria-label="Refresh dashboard data"+ >+ Refresh+ </Button>+ </div>++ {/* Error banner */}+ {error && (+ <div className={styles.errorBanner} role="alert">+ <Text>{error}</Text>+ </div>+ )}++ {/* At a Glance */}+ <Text as="h2" size={400} weight="semibold" className={styles.sectionHeading}>+ At a glance+ </Text>+ <section className={styles.statRow} aria-label="Key recruitment metrics">+ <StatCard+ icon={<PeopleRegular />}+ label="Total active candidates"+ value={totalActiveCandidates}+ subLabel="Active contacts"+ onClick={navigateToCandidates}+ />+ <StatCard+ icon={<CalendarRegular />}+ label="Interviews this month"+ value={interviewsThisMonth}+ subLabel="Appointments in current month"+ onClick={navigateToSchedule}+ />+ <StatCard+ icon={<CalendarCheckmarkRegular />}+ label="Interviews this week"+ value={interviewsThisWeek}+ subLabel="Appointments in current week"+ onClick={navigateToSchedule}+ />+ <StatCard+ icon={<BriefcaseRegular />}+ label="Open positions"+ value={openRoles}+ subLabel="Distinct job titles"+ />+ </section>++ <Divider />++ {/* Pipeline + Recent side by side */}+ <div className={styles.mainRow}>+ {/* Pipeline by role */}+ <Card className={styles.chartCard}>+ <CardHeader+ header={+ <Text as="h2" size={400} weight="semibold">+ Pipeline by role+ </Text>+ }+ description="Top 5 job titles by active candidate count"+ />+ {topRoles.length === 0 ? (+ <div className={styles.emptyState}>+ <Text>No candidate data available.</Text>+ </div>+ ) : (+ <PipelineBarChart data={topRoles} />+ )}+ </Card>++ {/* Recent interviews */}+ <Card className={styles.recentCard}>+ <CardHeader+ header={+ <Text as="h2" size={400} weight="semibold">+ Recent interviews+ </Text>+ }+ description="5 most recent appointments"+ />+ {recentAppointments.length === 0 ? (+ <div className={styles.emptyState}>+ <Text>No recent interviews found.</Text>+ </div>+ ) : (+ <section className={styles.activityList} aria-label="Recent interview activity">+ {recentAppointments.map((appt, idx) => {+ const candidateName =+ (appt['_regardingobjectid_value@OData.Community.Display.V1.FormattedValue'] as string) || '';+ return (+ <div key={(appt['activityid'] as string) || String(idx)}>+ <ActivityItem+ subject={appt['subject'] as string}+ candidateName={candidateName}+ scheduledStart={appt['scheduledstart']}+ statecode={appt['statecode'] as number}+ />+ {idx < recentAppointments.length - 1 && <Divider />}+ </div>+ );+ })}+ </section>+ )}+ </Card>+ </div>+ </main>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/interview-schedule.tsx b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/interview-schedule.tsxnew file mode 100644index 000000000..4acea04c2--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/interview-schedule.tsx@@ -0,0 +1,757 @@+import { useEffect, useRef, useState } from "react";+import type {+ TableRow,+ QueryTableOptions,+ GeneratedComponentProps,+} from "./RuntimeTypes";+import {+ Badge,+ Button,+ DataGrid,+ DataGridBody,+ DataGridCell,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridRow,+ Divider,+ Dropdown,+ Option,+ Spinner,+ TableCellLayout,+ Text,+ Toolbar,+ ToolbarGroup,+ createTableColumn,+ makeStyles,+ tokens,+ useId,+} from "@fluentui/react-components";+import {+ ArrowClockwiseRegular,+ CalendarRegular,+ LocationRegular,+ PersonRegular,+} from "@fluentui/react-icons";+import { DatePicker } from "@fluentui/react-datepicker-compat";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++type AppointmentRow = TableRow<{+ activityid: string;+ subject: string;+ scheduledstart: Date;+ scheduledend: Date;+ location: string;+ statuscode: number;+ _regardingobjectid_value: string;+}>;++// Flattened shape used for display+interface DisplayRow {+ activityid: string;+ subject: string;+ scheduledstart: Date;+ scheduledend: Date;+ location: string;+ statuscode: number;+ statusLabel: string;+ candidateName: string;+ dayKey: string; // "YYYY-MM-DD"+}++// ---------------------------------------------------------------------------+// Module-level cache (survives module re-evaluation via window)+// ---------------------------------------------------------------------------++let _apptCache: DisplayRow[] | null =+ (window as any).__ppAppointmentCache ?? null;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function formatDate(d: Date | null | undefined): string {+ if (!d) return "";+ const dt = d instanceof Date ? d : new Date(d as unknown as string);+ if (isNaN(dt.getTime())) return "";+ return dt.toLocaleDateString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++function formatTime(d: Date | null | undefined): string {+ if (!d) return "";+ const dt = d instanceof Date ? d : new Date(d as unknown as string);+ if (isNaN(dt.getTime())) return "";+ return dt.toLocaleTimeString("en-US", {+ hour: "numeric",+ minute: "2-digit",+ hour12: true,+ });+}++function toDayKey(d: Date): string {+ const dt = d instanceof Date ? d : new Date(d as unknown as string);+ if (isNaN(dt.getTime())) return "";+ const y = dt.getFullYear();+ const m = String(dt.getMonth() + 1).padStart(2, "0");+ const day = String(dt.getDate()).padStart(2, "0");+ return `${y}-${m}-${day}`;+}++function dayKeyToLabel(key: string): string {+ const dt = new Date(`${key}T00:00:00`);+ if (isNaN(dt.getTime())) return key;+ return dt.toLocaleDateString("en-US", {+ weekday: "long",+ year: "numeric",+ month: "long",+ day: "numeric",+ });+}++const STATUS_LABELS: Record<number, string> = {+ 1: "Free",+ 2: "Tentative",+ 3: "Completed",+ 4: "Canceled",+ 5: "Busy",+ 6: "Out of Office",+};++type BadgeColor =+ | "brand"+ | "danger"+ | "important"+ | "informative"+ | "severe"+ | "subtle"+ | "success"+ | "warning";++function statusBadgeColor(statuscode: number): BadgeColor {+ switch (statuscode) {+ case 1: return "success"; // Free+ case 2: return "warning"; // Tentative+ case 3: return "informative"; // Completed+ case 4: return "danger"; // Canceled+ case 5: return "brand"; // Busy+ case 6: return "severe"; // Out of Office+ default: return "subtle";+ }+}++function toDisplayRow(row: any): DisplayRow {+ const startRaw = row["scheduledstart"];+ const endRaw = row["scheduledend"];+ const start = startRaw ? new Date(startRaw as unknown as string) : new Date(NaN);+ const end = endRaw ? new Date(endRaw as unknown as string) : new Date(NaN);+ const statuscode = (row["statuscode"] as number) ?? 0;+ const candidateName: string =+ row["_regardingobjectid_value@OData.Community.Display.V1.FormattedValue"] as string ??+ "";+ return {+ activityid: row["activityid"] as string,+ subject: (row["subject"] as string) ?? "(No subject)",+ scheduledstart: start,+ scheduledend: end,+ location: (row["location"] as string) ?? "",+ statuscode,+ statusLabel: STATUS_LABELS[statuscode] ?? String(statuscode),+ candidateName,+ dayKey: isNaN(start.getTime()) ? "" : toDayKey(start),+ };+}++// ---------------------------------------------------------------------------+// Styles+// ---------------------------------------------------------------------------++const useStyles = makeStyles({+ root: {+ display: "flex",+ flexDirection: "column",+ width: "100%",+ height: "100%",+ boxSizing: "border-box",+ padding: tokens.spacingVerticalL,+ backgroundColor: tokens.colorNeutralBackground2,+ gap: tokens.spacingVerticalM,+ },+ header: {+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ flexWrap: "wrap",+ gap: tokens.spacingVerticalS,+ },+ filterBar: {+ display: "flex",+ flexWrap: "wrap",+ alignItems: "flex-end",+ gap: tokens.spacingHorizontalM,+ padding: tokens.spacingVerticalM,+ backgroundColor: tokens.colorNeutralBackground1,+ borderRadius: tokens.borderRadiusMedium,+ boxShadow: tokens.shadow4,+ },+ filterField: {+ display: "flex",+ flexDirection: "column",+ gap: tokens.spacingVerticalXS,+ minWidth: "160px",+ flex: "1 1 160px",+ },+ filterLabel: {+ fontSize: tokens.fontSizeBase200,+ fontWeight: tokens.fontWeightSemibold,+ color: tokens.colorNeutralForeground2,+ },+ statusDropdown: {+ minWidth: "160px",+ },+ contentArea: {+ flex: 1,+ overflowY: "auto",+ display: "flex",+ flexDirection: "column",+ gap: tokens.spacingVerticalM,+ minHeight: 0,+ },+ dayGroup: {+ display: "flex",+ flexDirection: "column",+ backgroundColor: tokens.colorNeutralBackground1,+ borderRadius: tokens.borderRadiusMedium,+ boxShadow: tokens.shadow4,+ overflow: "hidden",+ },+ dayHeader: {+ display: "flex",+ alignItems: "center",+ gap: tokens.spacingHorizontalS,+ padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,+ backgroundColor: tokens.colorBrandBackground2,+ },+ dayHeaderText: {+ fontWeight: tokens.fontWeightSemibold,+ color: tokens.colorBrandForeground2,+ },+ gridWrapper: {+ overflowX: "auto",+ },+ emptyState: {+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ padding: tokens.spacingVerticalXXL,+ gap: tokens.spacingVerticalM,+ backgroundColor: tokens.colorNeutralBackground1,+ borderRadius: tokens.borderRadiusMedium,+ boxShadow: tokens.shadow4,+ },+ errorBanner: {+ padding: tokens.spacingVerticalM,+ backgroundColor: tokens.colorStatusDangerBackground1,+ borderRadius: tokens.borderRadiusMedium,+ color: tokens.colorStatusDangerForeground1,+ },+ cellText: {+ display: "block",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ },+ badgeCell: {+ display: "flex",+ alignItems: "center",+ },+ spinnerWrapper: {+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ padding: tokens.spacingVerticalXXL,+ },+});++// ---------------------------------------------------------------------------+// Sub-components+// ---------------------------------------------------------------------------++function StatusBadge({ statuscode, label }: { statuscode: number; label: string }) {+ return (+ <Badge color={statusBadgeColor(statuscode)} appearance="filled" shape="rounded">+ {label}+ </Badge>+ );+}++// Column definitions for a single-day grid+const gridColumns = [+ createTableColumn<DisplayRow>({+ columnId: "subject",+ compare: (a, b) => a.subject.localeCompare(b.subject),+ renderHeaderCell: () => "Subject",+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: "hidden", minWidth: 0 }}>+ <span+ title={item.subject}+ style={{+ display: "block",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {item.subject}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: "candidateName",+ compare: (a, b) => a.candidateName.localeCompare(b.candidateName),+ renderHeaderCell: () => (+ <span style={{ display: "flex", alignItems: "center", gap: "4px" }}>+ <PersonRegular />+ Candidate+ </span>+ ),+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: "hidden", minWidth: 0 }}>+ <span+ title={item.candidateName}+ style={{+ display: "block",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {item.candidateName || "—"}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: "scheduledstart",+ compare: (a, b) =>+ (a.scheduledstart?.getTime() ?? 0) - (b.scheduledstart?.getTime() ?? 0),+ renderHeaderCell: () => "Start",+ renderCell: (item) => (+ <TableCellLayout>+ {formatTime(item.scheduledstart)}+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: "scheduledend",+ compare: (a, b) =>+ (a.scheduledend?.getTime() ?? 0) - (b.scheduledend?.getTime() ?? 0),+ renderHeaderCell: () => "End",+ renderCell: (item) => (+ <TableCellLayout>+ {formatTime(item.scheduledend)}+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: "location",+ compare: (a, b) => a.location.localeCompare(b.location),+ renderHeaderCell: () => (+ <span style={{ display: "flex", alignItems: "center", gap: "4px" }}>+ <LocationRegular />+ Location+ </span>+ ),+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: "hidden", minWidth: 0 }}>+ <span+ title={item.location}+ style={{+ display: "block",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {item.location || "—"}+ </span>+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: "statusLabel",+ compare: (a, b) => a.statusLabel.localeCompare(b.statusLabel),+ renderHeaderCell: () => "Status",+ renderCell: (item) => (+ <TableCellLayout>+ <StatusBadge statuscode={item.statuscode} label={item.statusLabel} />+ </TableCellLayout>+ ),+ }),+];++const columnSizingOptions = {+ subject: { defaultWidth: 220, minWidth: 140 },+ candidateName: { defaultWidth: 180, minWidth: 120 },+ scheduledstart: { defaultWidth: 100, minWidth: 80 },+ scheduledend: { defaultWidth: 100, minWidth: 80 },+ location: { defaultWidth: 180, minWidth: 100 },+ statusLabel: { defaultWidth: 130, minWidth: 100 },+};++interface DayGridProps {+ dayKey: string;+ rows: DisplayRow[];+ onRowClick: (row: DisplayRow) => void;+}++function DayGrid({ dayKey, rows, onRowClick }: DayGridProps) {+ const styles = useStyles();+ return (+ <div className={styles.dayGroup} role="region" aria-label={`Interviews for ${dayKeyToLabel(dayKey)}`}>+ <div className={styles.dayHeader}>+ <CalendarRegular style={{ color: tokens.colorBrandForeground2 }} />+ <Text className={styles.dayHeaderText}>{dayKeyToLabel(dayKey)}</Text>+ <Badge appearance="outline" color="brand" shape="circular" size="small">+ {rows.length}+ </Badge>+ </div>+ <div className={styles.gridWrapper}>+ <DataGrid+ items={rows}+ columns={gridColumns}+ sortable+ resizableColumns+ columnSizingOptions={columnSizingOptions}+ getRowId={(item) => item.activityid}+ focusMode="composite"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>+ <Text weight="semibold" size={200}>+ {renderHeaderCell()}+ </Text>+ </DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<DisplayRow>>+ {({ item, rowId }) => (+ <DataGridRow<DisplayRow>+ key={rowId}+ onClick={() => onRowClick(item)}+ style={{ cursor: "pointer" }}+ aria-label={`Interview: ${item.subject}, Candidate: ${item.candidateName}`}+ >+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ </div>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Status filter options+// ---------------------------------------------------------------------------++const STATUS_OPTIONS = [+ { value: "all", label: "All statuses" },+ { value: "1", label: "Free" },+ { value: "2", label: "Tentative" },+ { value: "3", label: "Completed" },+ { value: "4", label: "Canceled" },+ { value: "5", label: "Busy" },+ { value: "6", label: "Out of Office" },+];++// ---------------------------------------------------------------------------+// Main Component+// ---------------------------------------------------------------------------++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput;++ const styles = useStyles();+ const startPickerMountRef = useRef<HTMLDivElement>(null);+ const endPickerMountRef = useRef<HTMLDivElement>(null);+ const startDatePickerId = useId("start-date");+ const endDatePickerId = useId("end-date");+ const statusDropdownId = useId("status-filter");++ // Default: show the next 30 days+ const today = new Date();+ today.setHours(0, 0, 0, 0);+ const defaultEnd = new Date(today);+ defaultEnd.setDate(today.getDate() + 30);++ const [{ records, loading, error }, setData] = useState<{+ records: DisplayRow[];+ loading: boolean;+ error: string | null;+ }>({+ records: _apptCache ?? [],+ loading: _apptCache === null,+ error: null,+ });++ const [startDate, setStartDate] = useState<Date | null>(today);+ const [endDate, setEndDate] = useState<Date | null>(defaultEnd);+ const [statusFilter, setStatusFilter] = useState<string>("all");++ // Fetch appointments+ useEffect(() => {+ if (!dataApi) {+ setData((prev) => ({ ...prev, loading: false }));+ return;+ }+ if (_apptCache !== null) return; // cached — no spinner+ (async () => {+ try {+ const opts: QueryTableOptions<"appointment"> = {+ select: [+ "activityid",+ "subject",+ "scheduledstart",+ "scheduledend",+ "location",+ "statuscode",+ "_regardingobjectid_value",+ ],+ orderBy: "scheduledstart asc",+ pageSize: 250,+ };+ const result = await dataApi.queryTable("appointment", opts);+ const rows = result.rows.map(toDisplayRow);+ _apptCache = rows;+ (window as any).__ppAppointmentCache = rows;+ setData({ records: rows, loading: false, error: null });+ } catch (err) {+ if (_apptCache === null) {+ setData({+ records: [],+ loading: false,+ error: "Unable to load interviews. Please refresh and try again.",+ });+ }+ }+ })();+ }, [dataApi]);++ // Navigate to appointment record+ function handleRowClick(row: DisplayRow) {+ const xrm = (window as any).Xrm;+ if (!xrm?.Navigation) return;+ xrm.Navigation.navigateTo({+ pageType: "entityrecord",+ entityName: "appointment",+ entityId: row.activityid,+ });+ }++ // Refresh handler — clears the cache and re-fetches+ function handleRefresh() {+ _apptCache = null;+ delete (window as any).__ppAppointmentCache;+ setData({ records: [], loading: true, error: null });+ if (!dataApi) {+ setData({ records: [], loading: false, error: null });+ return;+ }+ (async () => {+ try {+ const opts: QueryTableOptions<"appointment"> = {+ select: [+ "activityid",+ "subject",+ "scheduledstart",+ "scheduledend",+ "location",+ "statuscode",+ "_regardingobjectid_value",+ ],+ orderBy: "scheduledstart asc",+ pageSize: 250,+ };+ const result = await dataApi.queryTable("appointment", opts);+ const rows = result.rows.map(toDisplayRow);+ _apptCache = rows;+ (window as any).__ppAppointmentCache = rows;+ setData({ records: rows, loading: false, error: null });+ } catch (err) {+ setData({+ records: [],+ loading: false,+ error: "Unable to load interviews. Please refresh and try again.",+ });+ }+ })();+ }++ // Filter records+ const filteredRecords = records.filter((row) => {+ // Date range filter+ if (startDate && !isNaN(startDate.getTime())) {+ const dayStart = new Date(startDate);+ dayStart.setHours(0, 0, 0, 0);+ if (row.scheduledstart < dayStart) return false;+ }+ if (endDate && !isNaN(endDate.getTime())) {+ const dayEnd = new Date(endDate);+ dayEnd.setHours(23, 59, 59, 999);+ if (row.scheduledstart > dayEnd) return false;+ }+ // Status filter+ if (statusFilter !== "all") {+ if (String(row.statuscode) !== statusFilter) return false;+ }+ return true;+ });++ // Group by day+ const dayMap = new Map<string, DisplayRow[]>();+ for (const row of filteredRecords) {+ if (!row.dayKey) continue;+ if (!dayMap.has(row.dayKey)) dayMap.set(row.dayKey, []);+ dayMap.get(row.dayKey)!.push(row);+ }+ const sortedDays = Array.from(dayMap.keys()).sort();++ return (+ <div className={styles.root}>+ {/* Header */}+ <div className={styles.header}>+ <div>+ <Text size={600} weight="semibold" block>+ Interview schedule+ </Text>+ <Text size={300} style={{ color: tokens.colorNeutralForeground3 }}>+ {filteredRecords.length} interview{filteredRecords.length !== 1 ? "s" : ""} shown+ </Text>+ </div>+ <Button+ icon={<ArrowClockwiseRegular />}+ appearance="secondary"+ onClick={handleRefresh}+ aria-label="Refresh interview schedule"+ disabled={loading}+ >+ Refresh+ </Button>+ </div>++ {/* Filter bar */}+ <div className={styles.filterBar} role="search" aria-label="Interview filters">+ <div className={styles.filterField}>+ <label id={startDatePickerId} className={styles.filterLabel}>+ From date+ </label>+ <div ref={startPickerMountRef} />+ <DatePicker+ aria-labelledby={startDatePickerId}+ placeholder="Start date"+ value={startDate}+ onSelectDate={(d) => setStartDate(d ?? null)}+ mountNode={startPickerMountRef.current ?? undefined}+ />+ </div>+ <div className={styles.filterField}>+ <label id={endDatePickerId} className={styles.filterLabel}>+ To date+ </label>+ <div ref={endPickerMountRef} />+ <DatePicker+ aria-labelledby={endDatePickerId}+ placeholder="End date"+ value={endDate}+ onSelectDate={(d) => setEndDate(d ?? null)}+ mountNode={endPickerMountRef.current ?? undefined}+ />+ </div>+ <div className={styles.filterField}>+ <label id={statusDropdownId} className={styles.filterLabel}>+ Status+ </label>+ <Dropdown+ aria-labelledby={statusDropdownId}+ className={styles.statusDropdown}+ value={STATUS_OPTIONS.find((o) => o.value === statusFilter)?.label ?? "All statuses"}+ selectedOptions={[statusFilter]}+ onOptionSelect={(_, d) => {+ if (d.optionValue) setStatusFilter(d.optionValue);+ }}+ >+ {STATUS_OPTIONS.map((opt) => (+ <Option key={opt.value} value={opt.value}>+ {opt.label}+ </Option>+ ))}+ </Dropdown>+ </div>+ </div>++ {/* Content */}+ <div className={styles.contentArea}>+ {loading && (+ <div className={styles.spinnerWrapper}>+ <Spinner+ size="large"+ label="Loading interviews..."+ aria-label="Loading interviews"+ />+ </div>+ )}++ {!loading && error && (+ <div className={styles.errorBanner} role="alert">+ <Text>{error}</Text>+ </div>+ )}++ {!loading && !error && sortedDays.length === 0 && (+ <div className={styles.emptyState} role="status">+ <CalendarRegular+ style={{+ fontSize: "48px",+ color: tokens.colorNeutralForeground3,+ }}+ />+ <Text size={400} weight="semibold">+ No interviews found+ </Text>+ <Text size={300} style={{ color: tokens.colorNeutralForeground3 }}>+ Adjust the date range or status filter to see results.+ </Text>+ </div>+ )}++ {!loading &&+ !error &&+ sortedDays.map((dayKey) => (+ <DayGrid+ key={dayKey}+ dayKey={dayKey}+ rows={dayMap.get(dayKey)!}+ onRowClick={handleRowClick}+ />+ ))}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.mdnew file mode 100644index 000000000..5a17ad18c--- /dev/null+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md@@ -0,0 +1,134 @@+# Workflow Log++## Phase 1 — Planning++### Commands++`node --version`+v20.18.2++`pac help`+PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8)++`pac auth list`+Index Active Kind Name User Cloud Type Environment Environment Url+[1] UNIVERSAL [email protected] Public OperatingSystem+[2] UNIVERSAL [email protected] Test User TMSBAPEnv5ee52 https://tmsbapenv5ee52.crmtest.dynamics.com/+[3] * UNIVERSAL [email protected] Test User AuroraBAPEnv610b3 https://aurorabapenv610b3.crmtest.dynamics.com/++AskUserQuestion: Which environment should be used for the recruitment app? → [3] [email protected] — AuroraBAPEnv610b3 (currently active)++`pac auth select --index 3`+New default profile: * UNIVERSAL : [email protected] Test https://aurorabapenv610b3.crmtest.dynamics.com/++`pac model list-languages`+Found 1 enabled language(s):+LCID Language Code RTL+1033 English (United States) en-US No++`pac model list-tables --search 'contact,appointment'`+Found 30 table(s). Exact matches confirmed:+- contact (Standard) — exists+- appointment (Standard) — exists++`pac model list-tables`+Found 1727 table(s). Custom prefix analysis:+- mspp: 36, msfp: 20, botcomponent: 7 — all system/Microsoft prefixes+- No non-system prefix meets the ≥50% / ≥3 tables threshold+- detectedPrefix: none (fallback to Default)++`pac model list`+Found 14 model-driven app(s). Notable: Genpage Publish Test, Customer Service Hub, CRM Hub, Sales Hub.++AskUserQuestion: Which app should the recruitment pages be added to, or create a new one? → Create a new app: "Recruitment App"++`pac solution list`+Unique Name Friendly Name Version Managed+Crdec34 Common Data Services Default Solution 1.0.0.0 False+Default Default Solution 1.0 False++`pac solution export --path 'D:/temp/crdec34-check.zip' --name Crdec34 --overwrite`+Solution export succeeded. Publisher prefix: crb2b++AskUserQuestion: Which solution should the new app go in? → Use existing 'Crdec34' solution (prefix: crb2b)++AskUserQuestion: Any specific requirements for styling, fields, filtering, or accessibility? → Keep it simple — use sensible defaults for a recruitment app++EnterPlanMode called++Plan presented:+- 3 pages: candidate-list.tsx, interview-schedule.tsx, hiring-metrics-dashboard.tsx+- Entities: contact (exists), appointment (exists) — no creation required+- New app: Recruitment App+- Solution: Crdec34 / Publisher Prefix: crb2b+- Localization: English (1033) only++User response: approved++## Phase 0 — Working directory+- Slug: recruitment-app+- Created: D:/temp/recruitment-app+- `mkdir -p D:/temp/recruitment-app`++## Phase 0.5 — Local-dev manifest+- `node D:/Projects/power-platform-skills/plugins/model-apps/scripts/generate-page-manifest.js D:/temp/recruitment-app recruitment-app --features charts`+- Files written: package.json, genpage.d.ts (features: charts)++### Decisions+- Environment: AuroraBAPEnv610b3 (https://aurorabapenv610b3.crmtest.dynamics.com/)+- PAC CLI: 2.7.4 (>= 2.7.0 requirement met)+- Node: v20.18.2+- Languages: English only — no localization code needed+- Both target entities (contact, appointment) confirmed as Standard tables in the environment+- No custom dominant prefix detected; solution Crdec34 uses crb2b publisher prefix+- New model-driven app "Recruitment App" will be created under Crdec34 solution+- Plan written to: D:/temp/recruitment-app/genpage-plan.md++## Phase 2 — Entity creation+- Skipped: contact and appointment are Standard entities that already exist++## Phase 3 — App creation+- `pac model create --name "Recruitment App" --solution "Crdec34"`+- App ID: e2666772-3c55-f111-a821-000d3a380330++## Phase 4 — RuntimeTypes generation+- `pac model genpage generate-types --data-sources "contact,appointment" --output-file D:/temp/recruitment-app/RuntimeTypes.ts`+- Output: RuntimeTypes.ts — contact and appointment schemas confirmed++## Phase 5 — Page build (multi-page parallel dispatch)+- Dispatched 3 genpage-page-builder agents in parallel+- candidate-list.tsx: built — contact entity, caching, search/filter, pagination+- interview-schedule.tsx: built — appointment+contact, DatePicker filter, day-group DataGrid, OData annotation for candidate name+- hiring-metrics-dashboard.tsx: built — D3 bar chart, 4 KPI stat cards, PAGEREF_ placeholders for sibling navigation+- Icons verified (all 6 files' imports confirmed in verified-icons.txt)++## Phase 6 — Deploy+- Command 1: `pac model genpage upload --app-id e2666772-3c55-f111-a821-000d3a380330 --code-file D:/temp/recruitment-app/candidate-list.tsx --name "Candidate List" --data-sources "contact" --prompt "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." --model "claude-sonnet-4-6" --agent-message "Searchable filterable Contact list with caching, status badges, row-click navigation, pagination" --add-to-sitemap`+- Command 2: `pac model genpage upload --app-id e2666772-3c55-f111-a821-000d3a380330 --code-file D:/temp/recruitment-app/interview-schedule.tsx --name "Interview Schedule" --data-sources "appointment,contact" --prompt "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." --model "claude-sonnet-4-6" --agent-message "Appointment DataGrid grouped by day, DatePicker filter, status filter, candidate name via OData annotation" --add-to-sitemap`+- Command 3: `pac model genpage upload --app-id e2666772-3c55-f111-a821-000d3a380330 --code-file D:/temp/recruitment-app/hiring-metrics-dashboard.tsx --name "Hiring Metrics Dashboard" --data-sources "contact,appointment" --prompt "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." --model "claude-sonnet-4-6" --agent-message "KPI dashboard: 4 stat cards, D3 role bar chart, recent interviews list. PAGEREF_ placeholders resolved in Phase 6.5." --add-to-sitemap`++## Phase 6 — Deploy (results)+- Command 1 result: page-id = 492d8c42-b5fc-4ec5-ad44-6809c6673e9a, status = success+- Command 2 result: page-id = 07ad1d40-5ca8-494a-aeac-ff0548acb6c0, status = success+- Command 3 result: page-id = e2022b27-548b-43be-95bd-4dafa02e060c, status = success++## Phase 6.5 — Navigation fix-up+- PAGEREF_ map: candidate-list → 492d8c42-b5fc-4ec5-ad44-6809c6673e9a, interview-schedule → 07ad1d40-5ca8-494a-aeac-ff0548acb6c0+- Replaced 2 tokens in hiring-metrics-dashboard.tsx (longer key first: interview-schedule, then candidate-list)+- Re-upload command: `pac model genpage upload --app-id e2666772-3c55-f111-a821-000d3a380330 --page-id e2022b27-548b-43be-95bd-4dafa02e060c --code-file D:/temp/recruitment-app/hiring-metrics-dashboard.tsx --data-sources "contact,appointment" --prompt "Resolve cross-page navigation placeholders to real page GUIDs (post-deploy fix-up)" --model "claude-sonnet-4-6" --agent-message "Replaced PAGEREF_candidate-list with 492d8c42... and PAGEREF_interview-schedule with 07ad1d40..."`+- Result: page-id = e2022b27-548b-43be-95bd-4dafa02e060c, status = success++## Phase 7 — Browser verification+- Skipped by user choice++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Candidate List | candidate-list.tsx | contact | Deployed |+| Interview Schedule | interview-schedule.tsx | appointment, contact | Deployed |+| Hiring Metrics Dashboard | hiring-metrics-dashboard.tsx | contact, appointment | Deployed |++- App: Recruitment App (e2666772-3c55-f111-a821-000d3a380330)+- Entities created: none+- Browser verification: skippeddiff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.mdnew file mode 100644index 000000000..9120e2591--- /dev/null+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md@@ -0,0 +1,68 @@+# Genpage Plan++## User Requirements++Build a page showing Contact records with name, email, and phone.++## Working Directory++contact-localized/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Sales Hub (55555555-4444-5555-6666-777777777777)+- Solution: Default+- Publisher Prefix: new++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Contacts (Localized) | page.tsx | Contact list with multi-language UI (en/ar/fr) | contact |++## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities++contact++## Localization++- Detected languages (from `pac model list-languages`):+ - English (United States) (1033, en-US)+ - Arabic (Saudi Arabia) (1025, ar-SA) — RTL+ - French (France) (1036, fr-FR)+- Translation dictionary keyed by BCP-47 tag+- All user-visible text via translate() helper+- dir attribute set from locale.isRtl+- Logical CSS properties (marginInlineStart/End, paddingInlineStart/End)++## Design Preferences++- DataGrid with sortable, resizable columns+- Column headers and table aria-label come from translate()+- Logical CSS only (no marginLeft/Right or paddingLeft/Right)++## Relevant Samples++- plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list pattern)+- references/localization.md (multi-language + RTL pattern)++## Per-Page Specifications++### Contacts (Localized)++- File: page.tsx+- Entity: contact+- Language detection: `Xrm.Utility.getGlobalContext().userSettings.languageId`+- Locale map: { 1033: en-US, 1025: ar-SA (RTL), 1036: fr-FR }+- Translations dict has entries for en-US, ar-SA, fr-FR+- Icons: PeopleRegular (unsized)diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/page.tsx b/evals/model-apps/genpage/fixtures/13-contact-localization/page.tsxnew file mode 100644index 000000000..7cf3b1af1--- /dev/null+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/page.tsx@@ -0,0 +1,184 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+ Spinner,+ MessageBar,+ MessageBarBody,+ Text,+} from '@fluentui/react-components';+import { PeopleRegular } from '@fluentui/react-icons';+import { GeneratedComponentProps } from './RuntimeTypes';++declare const Xrm: {+ Utility: {+ getGlobalContext: () => {+ userSettings: { languageId: number };+ };+ };+};++// Locale id → BCP-47 + RTL flag.+const LOCALE_MAP: Record<number, { tag: string; isRtl: boolean }> = {+ 1033: { tag: 'en-US', isRtl: false },+ 1025: { tag: 'ar-SA', isRtl: true },+ 1036: { tag: 'fr-FR', isRtl: false },+};++const TRANSLATIONS: Record<string, Record<string, string>> = {+ 'en-US': { title: 'Contacts', name: 'Name', email: 'Email', phone: 'Phone', empty: 'No contacts.' },+ 'ar-SA': { title: 'جهات الاتصال', name: 'الاسم', email: 'البريد الإلكتروني', phone: 'الهاتف', empty: 'لا توجد جهات اتصال.' },+ 'fr-FR': { title: 'Contacts', name: 'Nom', email: 'E-mail', phone: 'Téléphone', empty: 'Aucun contact.' },+};++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ paddingInlineStart: tokens.spacingHorizontalL,+ paddingInlineEnd: tokens.spacingHorizontalL,+ paddingBlock: tokens.spacingVerticalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ marginInlineStart: 0,+ },+ grid: { flex: 1, overflowY: 'auto' },+});++interface Row { id: string; name: string; email: string; phone: string; }++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput;+ const styles = useStyles();++ const languageId = (() => {+ try {+ return Xrm.Utility.getGlobalContext().userSettings.languageId;+ } catch {+ return 1033;+ }+ })();+ const locale = LOCALE_MAP[languageId] ?? LOCALE_MAP[1033];+ const t = (key: string) => TRANSLATIONS[locale.tag]?.[key] ?? TRANSLATIONS['en-US'][key];++ const [rows, setRows] = React.useState<Row[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const w = window as unknown as Record<string, Row[] | undefined>;+ if (w.__genpage_contacts_v1) {+ setRows(w.__genpage_contacts_v1);+ setLoading(false);+ return;+ }+ try {+ const result = await dataApi.queryTable('contact', {+ select: ['contactid', 'fullname', 'emailaddress1', 'telephone1'],+ top: 200,+ });+ // queryTable returns DataTable<T> with .rows — never iterate the result directly+ const mapped: Row[] = result.rows.map((r: any) => ({+ id: r.contactid,+ name: r.fullname ?? '',+ email: r.emailaddress1 ?? '',+ phone: r.telephone1 ?? '',+ }));+ w.__genpage_contacts_v1 = mapped;+ setRows(mapped);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi]);++ const columns = React.useMemo(+ () => [+ createTableColumn<Row>({+ columnId: 'name',+ renderHeaderCell: () => t('name'),+ renderCell: (item) => <TableCellLayout>{item.name}</TableCellLayout>,+ }),+ createTableColumn<Row>({+ columnId: 'email',+ renderHeaderCell: () => t('email'),+ renderCell: (item) => <TableCellLayout>{item.email}</TableCellLayout>,+ }),+ createTableColumn<Row>({+ columnId: 'phone',+ renderHeaderCell: () => t('phone'),+ renderCell: (item) => <TableCellLayout>{item.phone}</TableCellLayout>,+ }),+ ],+ [locale.tag],+ );++ if (loading) return <Spinner label={t('title')} />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root} dir={locale.isRtl ? 'rtl' : 'ltr'} lang={locale.tag}>+ <div className={styles.header}>+ <PeopleRegular />+ <Text size={500} weight="semibold">{t('title')} ({rows.length})</Text>+ </div>+ <div className={styles.grid}>+ {rows.length === 0 ? (+ <Text>{t('empty')}</Text>+ ) : (+ <DataGrid+ items={rows}+ columns={columns}+ resizableColumns+ columnSizingOptions={{+ name: { defaultWidth: 200, minWidth: 120 },+ email: { defaultWidth: 220, minWidth: 140 },+ phone: { defaultWidth: 160, minWidth: 100 },+ }}+ sortable+ aria-label={t('title')}+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<Row>>+ {({ item, rowId }) => (+ <DataGridRow<Row> key={rowId}>+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ )}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.mdnew file mode 100644index 000000000..887b1372a--- /dev/null+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md@@ -0,0 +1,72 @@+# Workflow Log — Eval 13: Contact list with localization++## Phase 0 — Working directory setup+- Working directory created: `contact-localized/`+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)++### Auth check+- `pac auth list` → active profile [email protected]+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Entity discovery+- `pac model list-tables --search 'contact'` — contact entity exists++### Language discovery+- `pac model list-languages` returned: English (United States) (1033, en-US), Arabic (Saudi Arabia) (1025, ar-SA), French (France) (1036, fr-FR)+- Multiple non-English languages detected → planner activates localization code path+- Arabic detected as RTL language++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): user answered "Dataverse entity: contact"+- Question 3 (specific requirements): "Contact list display"+- Question 4 (app selection): user selected existing app "Sales Hub"++### Solution selection+- Build is code-only → solution selection question SKIPPED+- Defaults written to plan: `Solution: Default`, `Publisher Prefix: new`++### Plan presented+- EnterPlanMode called with plan including Localization section; user approved++### Plan written+- genpage-plan.md written; ## Localization lists detected languages (1033, 1025, 1036) and RTL flag on Arabic+- references/localization.md loaded conditionally++## Phase 2 — Entity creation+- SKIPPED (contact exists)++## Phase 3 — App creation+- SKIPPED (existing app selected)++## Phase 4 — Schema generation+- pac model genpage generate-types --data-sources 'contact' --output-file contact-localized/RuntimeTypes.ts++## Phase 5b — Single-page fast path+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched)+- Data mode: dataverse+- Read sample: plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list pattern)+- Read ${CLAUDE_PLUGIN_ROOT}/references/localization.md (multi-language + RTL pattern)+- Read ${CLAUDE_PLUGIN_ROOT}/references/verified-icons.txt+- Wrote page.tsx with:+ - Xrm.Utility.getGlobalContext().userSettings.languageId for language detection+ - LOCALE_MAP for 1033/1025/1036 → BCP-47 + isRtl+ - TRANSLATIONS dictionary with en-US, ar-SA, fr-FR entries+ - translate() helper t(key)+ - dir attribute set to rtl when locale.isRtl+ - Logical CSS properties (paddingInlineStart/End, marginInlineStart, paddingBlock)+- Post-write icon verification: PeopleRegular verified against verified-icons.txt++## Phase 6 — Deployment+- pac model genpage upload --app-id 55555555-4444-5555-6666-777777777777 --code-file contact-localized/page.tsx --data-sources 'contact' --prompt "Build a page showing Contact records with name, email, and phone." --model claude-sonnet --name "Contacts (Localized)" --agent-message "Contact list with en-US/ar-SA/fr-FR translations and RTL support" --add-to-sitemap++## Phase 8 — Summary+- 1 page deployed: page.tsx → "Contacts (Localized)" in Sales Hub+- Localization: en-US, ar-SA (RTL), fr-FR+- No entities createddiff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/README.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/README.mdnew file mode 100644index 000000000..7e0150ce2--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/README.md@@ -0,0 +1,83 @@+# Fixture 15-support-tickets-real — Real Claude capture++**Status:** Real `/genpage` capture (2026-05-21 → 2026-05-26). **Both layers+fully green.** Replaces the original memory-game capture under eval id 15.++## Source++Captured from a real `/genpage` session against+`https://aurorabapenv610b3.crmtest.dynamics.com`. Driven by+`claude-sonnet-4-6` under the v2.1 plugin + v2.2 manifest generator + v2.2+planner-spec tightening. Working dir was `D:/temp/support-tickets/`.++Prompt was the eval 15 prompt verbatim:++> Build a page tracking support tickets. I need a new cr_ticket entity with+> a priority choice column (Low, Medium, High, Critical), a status choice+> column (Open, In Progress, Resolved, Closed), and a due date column.++## What this capture validates++End-to-end entity-creation flow under the tightened v2.2 spec:++- **All v2.2 spec requirements satisfied** — workflow-log records every+ prereq command verbatim (`node --version`, `pac help`, `pac auth list`,+ `pac model list-tables`, `pac model list`, `pac solution list`), every+ `AskUserQuestion` call with the answer, `EnterPlanMode called`, the+ `check-auth.js` result on both retries (`ok=false blocker=whoami_403`+ then `ok=true identitiesMatch=true`), and the full+ `pac model genpage upload` command with `--prompt` and all flags echoed.+- **check-auth.js retry flow correctly recorded** — first run blocked on+ `whoami_403` (identity mismatch); user instructed to run+ `az login --username`; second run returned `ok=true`. The orchestrator+ correctly halted between attempts.+- **Entity creation with choice columns + sample data** — `cr_ticket` table+ with `cr_priority` (4 options, 100000000-100000003), `cr_status` (4+ options, same range), `cr_duedate` (DateOnly). 10 sample records inserted+ via OData `$batch`. Transaction log written to `entity-creation-log.md`.+- **Prefix discipline held end-to-end** — plan stores suffix-only names+ (`ticket`, `priority`, `status`, `duedate`); entity-creation-log records+ resolved full names (`cr_ticket`, `cr_priority`, etc.) starting with the+ publisher prefix from the plan's `## Environment`.+- **Choice column display via local enum mapping** — page uses named+ constants (`PRIORITY_LOW = 100000000`, etc.) and an option-array helper+ rather than `dataApi.getChoices()` / `FormattedValue` annotations. The+ Layer 2 runner now accepts this as a valid alternative (added in the+ same change set as this capture).++## Runner fixes that landed alongside this capture++The capture surfaced two additional regex narrowings that needed relaxing:++1. **`check-auth.js ok:true` detection** — the runner only accepted+ `ok: true` (colon-space) or `"ok": true` (JSON). Real captures+ sometimes use `ok=true` (equals-sign). Fixed to accept both forms via+ `[:=]` in the regex.+2. **Choice column display patterns** — the runner only accepted+ `dataApi.getChoices()` or `FormattedValue`. Real captures often use a+ **local enum mapping** with named constants in the Dataverse choice+ value range (`100000000+`). Fixed to accept this as a third valid+ pattern — these constants are verified against `RuntimeTypes` at+ generation time, so they're equivalent in correctness.++These relaxations only accept *functionally-equivalent* alternatives —+they don't loosen the rules to admit drift.++## Replaces++This fixture replaces `15-memory-game-entity-with-choices/` (deleted+alongside this capture's commit). That earlier capture was driven by a+non-Claude model under the v2.1 spec and had 6 known-failing assertions+about workflow-log compactness + `pageInput` destructuring. The+support-tickets capture is the canonical eval 15 real fixture going+forward.++## Files++| File | Source |+|------|--------|+| `support-tickets.tsx` | Generated by `/genpage` page-builder phase |+| `RuntimeTypes.ts` | Generated by `pac model genpage generate-types --data-sources "cr_ticket"` |+| `workflow-log.md` | Recorded during the run — command-verbatim format per v2.2 spec |+| `genpage-plan.md` | Written by `genpage-planner` agent |+| `entity-creation-log.md` | Written by `genpage-entity-builder` agent |diff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/15-support-tickets-real/RuntimeTypes.tsnew file mode 100644index 000000000..8cffa785e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/RuntimeTypes.ts@@ -0,0 +1,57 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "cr_ticket": cr_ticket,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "cr_ticket-cr_priority": cr_ticket_cr_priority,+ "cr_ticket-cr_status": cr_ticket_cr_status,+ "cr_ticket-statecode": cr_ticket_statecode,+ "cr_ticket-statuscode": cr_ticket_statuscode,+}+export type cr_ticket = TableRow<{+ // Primary Key Column+ readonly cr_ticketid: string,+ cr_duedate: Date,+ cr_name: string,+ cr_priority: cr_ticket_cr_priority,+ cr_status: cr_ticket_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_ticket_statecode,+ statuscode: cr_ticket_statuscode,+}>++const enum cr_ticket_cr_priority {+"Low" = 100000000,+"Medium" = 100000001,+"High" = 100000002,+"Critical" = 100000003,+}+const enum cr_ticket_cr_status {+"Open" = 100000000,+"In Progress" = 100000001,+"Resolved" = 100000002,+"Closed" = 100000003,+}+const enum cr_ticket_statecode {+"Active" = 0,+"Inactive" = 1,+}+const enum cr_ticket_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/15-support-tickets-real/entity-creation-log.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/entity-creation-log.mdnew file mode 100644index 000000000..1e8899df4--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/entity-creation-log.md@@ -0,0 +1,29 @@+# Entity Creation Log++Env: https://aurorabapenv610b3.crmtest.dynamics.com+Solution: Crdec34+Publisher Prefix: cr+Started: 2026-05-21T00:00:00Z++| Step | Operation | Status | Resolved Full Name | MetadataId | Notes |+|------|-----------|--------|---------------------|------------|-------|+| 1 | Auth check | OK | n/a | n/a | az + pac signed in as [email protected] |+| 2 | Create table cr_Ticket | EXISTS | cr_ticket | 8a63d937-5355-f111-a821-000d3a380330 | Table already existed in env; verified PrimaryNameAttribute=cr_name, EntitySetName=cr_tickets |+| 3 | Add column cr_priority (picklist) | OK | cr_priority | 1a2ed57f-5355-f111-a821-000d3a380330 | Options: Low(100000000), Medium(100000001), High(100000002), Critical(100000003) |+| 4 | Add column cr_status (picklist) | OK | cr_status | bf5f0089-5355-f111-a821-000d3a380330 | Options: Open(100000000), In Progress(100000001), Resolved(100000002), Closed(100000003) |+| 5 | Add column cr_duedate (datetime) | OK | cr_duedate | c95f0089-5355-f111-a821-000d3a380330 | DateOnly format, UserLocal behavior |+| 6 | Verify metadata | OK | cr_ticket | 8a63d937-5355-f111-a821-000d3a380330 | EntitySetName=cr_tickets confirmed |+| 7 | Seed sample tickets | OK | cr_tickets | n/a | 10 records inserted via $batch, 0 errors |++## Created Record IDs (cr_ticket)++- 56690ca2-5355-f111-a821-000d3a380330 — Login page returns 500 error for SSO users (Critical / Open)+- 57690ca2-5355-f111-a821-000d3a380330 — Export to Excel truncates long descriptions (Medium / In Progress)+- 58690ca2-5355-f111-a821-000d3a380330 — Dashboard widget shows stale data after refresh (High / Open)+- 59690ca2-5355-f111-a821-000d3a380330 — Email notifications missing attachments (High / In Progress)+- 5a690ca2-5355-f111-a821-000d3a380330 — Typo on the account settings help text (Low / Open)+- 5b690ca2-5355-f111-a821-000d3a380330 — Mobile layout breaks on iPad portrait orientation (Medium / Resolved)+- 5c690ca2-5355-f111-a821-000d3a380330 — Search filter does not persist across pages (Medium / Open)+- 5d690ca2-5355-f111-a821-000d3a380330 — Password reset email goes to spam folder (High / Closed)+- 5e690ca2-5355-f111-a821-000d3a380330 — Calendar invite timezone offset incorrect (Medium / In Progress)+- 5f690ca2-5355-f111-a821-000d3a380330 — Bulk import fails on records with special characters (Critical / Open)diff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.mdnew file mode 100644index 000000000..c6841c23d--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/genpage-plan.md@@ -0,0 +1,68 @@+# Genpage Plan++## User Requirements+Build a page tracking support tickets. I need a new cr_ticket entity with a priority choice column (Low, Medium, High, Critical), a status choice column (Open, In Progress, Resolved, Closed), and a due date column.++## Working Directory+D:/temp/support-tickets++## Plugin Root+D:/Projects/power-platform-skills/plugins/model-apps++## Environment+- URL: https://aurorabapenv610b3.crmtest.dynamics.com+- App: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)+- Languages: English (1033) only+- Solution: Crdec34+- Publisher Prefix: cr++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Support Tickets | support-tickets.tsx | Filterable list of support tickets with priority badges, status indicators, and due dates — clickable to open records | cr_ticket |++## Entity Creation Required++### ticket+[The full logical name is constructed by the entity-builder as `cr_ticket`. Display name: "Ticket".]++- Display Name: Ticket+- Display Plural: Tickets+- Primary Name Suffix: name+- Columns:+ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | duedate | datetime | no | Due date for the support ticket |+- Choice Columns:+ | Column Suffix | Options |+ |---------------|---------|+ | priority | Low (100000000), Medium (100000001), High (100000002), Critical (100000003) |+ | status | Open (100000000), In Progress (100000001), Resolved (100000002), Closed (100000003) |+- Relationships:+ (none)++## Existing Entities+None++## Design Preferences+- Styling: Color-coded priority badges (Critical = red, High = orange, Medium = yellow, Low = green); status shown as pill/tag labels; due dates with overdue urgency cue (red text when past due)+- Features: Filter by status and priority; sort by due date; clickable rows to open record detail; search by ticket name+- Accessibility: WCAG AA compliant; keyboard-navigable list; sufficient color contrast on priority badges++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Support Tickets | 9-list-with-caching.tsx | Demonstrates a filterable list with Dataverse data and caching pattern — directly applicable to a support ticket list page |++## Per-Page Specifications++### Support Tickets+- **File:** support-tickets.tsx+- **Purpose:** Filterable, sortable list of support tickets with priority and status indicators+- **Entities:** cr_ticket+- **Needs caching:** true+- **Key Features:** Display all ticket records in a list/table; filter by status (Open, In Progress, Resolved, Closed) and priority (Low, Medium, High, Critical); sort by due date ascending/descending; search by ticket name; color-coded priority badges; due date shown in red when past today; click row to open ticket record in the model-driven app+- **Components:** Fluent UI V9 — DataGrid or DetailsList for the table; Badge or Tag for priority and status pills; SearchBox for name search; Dropdown for filter controls; Toolbar for filter/sort bar+- **Layout:** Full-width responsive table layout; filter bar above the table; on narrow screens stack filters vertically; sticky header row+- **Data Binding:** queryTable("cr_ticket") selecting cr_name, cr_priority, cr_status, cr_duedate; sort and filter applied as OData query parameters; cache results via the caching pattern from data-caching.md+- **Interactions:** Clicking a row calls openRecord("cr_ticket", recordId) to navigate to the record; filter dropdowns re-query on change; sort column headers toggle asc/desc; search box debounced at 300msdiff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/support-tickets.tsx b/evals/model-apps/genpage/fixtures/15-support-tickets-real/support-tickets.tsxnew file mode 100644index 000000000..c59479531--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/support-tickets.tsx@@ -0,0 +1,485 @@+import { useEffect, useState } from 'react';+import type {+ ReadableTableRow,+ GeneratedComponentProps,+ cr_ticket,+} from './RuntimeTypes';+import {+ makeStyles,+ tokens,+ Text,+ Spinner,+ Button,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+ SearchBox,+ Dropdown,+ Option,+ Badge,+} from '@fluentui/react-components';+import type { TableColumnDefinition } from '@fluentui/react-components';+import { SearchRegular, ArrowClockwiseRegular } from '@fluentui/react-icons';++type ReadableTicket = ReadableTableRow<cr_ticket>;++// ── Choice codes (verified from RuntimeTypes cr_ticket_cr_priority / cr_ticket_cr_status) ──+const PRIORITY_LOW = 100000000;+const PRIORITY_MEDIUM = 100000001;+const PRIORITY_HIGH = 100000002;+const PRIORITY_CRITICAL = 100000003;++const STATUS_OPEN = 100000000;+const STATUS_IN_PROGRESS = 100000001;+const STATUS_RESOLVED = 100000002;+const STATUS_CLOSED = 100000003;++const PRIORITY_OPTIONS: { value: number; label: string }[] = [+ { value: PRIORITY_LOW, label: 'Low' },+ { value: PRIORITY_MEDIUM, label: 'Medium' },+ { value: PRIORITY_HIGH, label: 'High' },+ { value: PRIORITY_CRITICAL, label: 'Critical' },+];++const STATUS_OPTIONS: { value: number; label: string }[] = [+ { value: STATUS_OPEN, label: 'Open' },+ { value: STATUS_IN_PROGRESS, label: 'In Progress' },+ { value: STATUS_RESOLVED, label: 'Resolved' },+ { value: STATUS_CLOSED, label: 'Closed' },+];++// ── Module-level cache (survives module re-evaluation on back-nav) ────────────+const CACHE_KEY = '__ppSupportTicketsCache';+const winAny = window as unknown as Record<string, ReadableTicket[] | undefined>;+let cache: ReadableTicket[] | null = winAny[CACHE_KEY] ?? null;++// ── Helpers ───────────────────────────────────────────────────────────────────++function formatDueDate(value: Date | string | null | undefined): string {+ if (!value) return '—';+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return '—';+ return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });+}++function isOverdue(value: Date | string | null | undefined, status: number | undefined): boolean {+ if (status === STATUS_RESOLVED || status === STATUS_CLOSED) return false;+ if (!value) return false;+ const d = new Date(value as string);+ if (isNaN(d.getTime())) return false;+ const today = new Date();+ today.setHours(0, 0, 0, 0);+ return d.getTime() < today.getTime();+}++function getPriorityConfig(priority: number | undefined): {+ color: 'success' | 'warning' | 'severe' | 'danger' | 'subtle';+ label: string;+} {+ switch (priority) {+ case PRIORITY_LOW: return { color: 'success', label: 'Low' };+ case PRIORITY_MEDIUM: return { color: 'warning', label: 'Medium' };+ case PRIORITY_HIGH: return { color: 'severe', label: 'High' };+ case PRIORITY_CRITICAL: return { color: 'danger', label: 'Critical' };+ default: return { color: 'subtle', label: '—' };+ }+}++function getStatusConfig(status: number | undefined): {+ color: 'informative' | 'brand' | 'success' | 'subtle';+ label: string;+} {+ switch (status) {+ case STATUS_OPEN: return { color: 'informative', label: 'Open' };+ case STATUS_IN_PROGRESS: return { color: 'brand', label: 'In Progress' };+ case STATUS_RESOLVED: return { color: 'success', label: 'Resolved' };+ case STATUS_CLOSED: return { color: 'subtle', label: 'Closed' };+ default: return { color: 'subtle', label: '—' };+ }+}++// ── Styles ────────────────────────────────────────────────────────────────────++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ padding: tokens.spacingHorizontalXL,+ width: '100%',+ boxSizing: 'border-box',+ },+ header: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ },+ titleRow: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalM,+ flexWrap: 'wrap',+ },+ filterBar: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalM,+ flexWrap: 'wrap',+ },+ searchBox: {+ flex: '1 1 240px',+ maxWidth: '320px',+ },+ dropdown: {+ minWidth: '160px',+ },+ spinnerWrap: {+ display: 'flex',+ justifyContent: 'center',+ padding: tokens.spacingVerticalXXL,+ },+ errorBanner: {+ padding: tokens.spacingHorizontalM,+ backgroundColor: tokens.colorStatusDangerBackground2,+ color: tokens.colorStatusDangerForeground2,+ borderRadius: tokens.borderRadiusMedium,+ },+ emptyState: {+ padding: tokens.spacingVerticalXXL,+ textAlign: 'center',+ color: tokens.colorNeutralForeground3,+ },+ overdueDate: {+ color: tokens.colorStatusDangerForeground1,+ fontWeight: tokens.fontWeightSemibold,+ },+ nameButton: {+ textAlign: 'left',+ justifyContent: 'flex-start',+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});++// ── GeneratedComponent ───────────────────────────────────────────────────────++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput;+ const styles = useStyles();++ const [data, setData] = useState<{+ records: ReadableTicket[];+ loading: boolean;+ error: string | null;+ }>(() => ({+ records: cache ?? [],+ loading: cache === null,+ error: null,+ }));++ const [search, setSearch] = useState('');+ const [statusFilter, setStatusFilter] = useState<number | null>(null);+ const [priorityFilter, setPriorityFilter] = useState<number | null>(null);+ const [sortColumn, setSortColumn] = useState<string>('cr_duedate');+ const [sortDirection, setSortDirection] = useState<'ascending' | 'descending'>('ascending');++ useEffect(() => {+ if (cache !== null) return;+ (async () => {+ try {+ const result = await dataApi.queryTable('cr_ticket', {+ select: ['cr_ticketid', 'cr_name', 'cr_priority', 'cr_status', 'cr_duedate'],+ filter: 'statecode eq 0',+ orderBy: 'cr_duedate asc',+ pageSize: 200,+ });+ cache = result.rows as ReadableTicket[];+ winAny[CACHE_KEY] = cache;+ setData({ records: cache, loading: false, error: null });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed to load tickets.';+ setData({ records: [], loading: false, error: message });+ }+ })();+ }, [dataApi]);++ const refresh = async () => {+ cache = null;+ delete winAny[CACHE_KEY];+ setData({ records: [], loading: true, error: null });+ try {+ const result = await dataApi.queryTable('cr_ticket', {+ select: ['cr_ticketid', 'cr_name', 'cr_priority', 'cr_status', 'cr_duedate'],+ filter: 'statecode eq 0',+ orderBy: 'cr_duedate asc',+ pageSize: 200,+ });+ cache = result.rows as ReadableTicket[];+ winAny[CACHE_KEY] = cache;+ setData({ records: cache, loading: false, error: null });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed to refresh.';+ setData({ records: [], loading: false, error: message });+ }+ };++ const openRecord = (ticketId: string) => {+ const xrm = (window as unknown as {+ Xrm?: { Navigation?: { navigateTo: (opts: unknown) => unknown } };+ }).Xrm;+ xrm?.Navigation?.navigateTo({+ pageType: 'entityrecord',+ entityName: 'cr_ticket',+ entityId: ticketId,+ });+ };++ // ── Filter ──────────────────────────────────────────────────────────────+ const filtered = data.records.filter((t) => {+ if (search) {+ const term = search.toLowerCase();+ if (!(t.cr_name?.toLowerCase().includes(term))) return false;+ }+ if (statusFilter !== null && (t.cr_status as unknown as number) !== statusFilter) return false;+ if (priorityFilter !== null && (t.cr_priority as unknown as number) !== priorityFilter) return false;+ return true;+ });++ // ── Sort (controlled — DataGrid expects pre-sorted items) ──────────────+ const sorted = [...filtered].sort((a, b) => {+ const dir = sortDirection === 'ascending' ? 1 : -1;+ switch (sortColumn) {+ case 'cr_name':+ return dir * (a.cr_name ?? '').localeCompare(b.cr_name ?? '');+ case 'cr_priority':+ return dir * ((a.cr_priority as unknown as number ?? 0) - (b.cr_priority as unknown as number ?? 0));+ case 'cr_status':+ return dir * ((a.cr_status as unknown as number ?? 0) - (b.cr_status as unknown as number ?? 0));+ case 'cr_duedate': {+ const aD = a.cr_duedate ? new Date(a.cr_duedate as unknown as string).getTime() : Number.MAX_SAFE_INTEGER;+ const bD = b.cr_duedate ? new Date(b.cr_duedate as unknown as string).getTime() : Number.MAX_SAFE_INTEGER;+ return dir * (aD - bD);+ }+ default:+ return 0;+ }+ });++ // ── Columns ─────────────────────────────────────────────────────────────+ const columns: TableColumnDefinition<ReadableTicket>[] = [+ createTableColumn<ReadableTicket>({+ columnId: 'cr_name',+ compare: (a, b) => (a.cr_name ?? '').localeCompare(b.cr_name ?? ''),+ renderHeaderCell: () => 'Ticket',+ renderCell: (item) => (+ <TableCellLayout style={{ overflow: 'hidden', minWidth: 0 }}>+ <Button+ appearance="transparent"+ className={styles.nameButton}+ onClick={() => openRecord(item.cr_ticketid)}+ title={item.cr_name ?? ''}+ >+ {item.cr_name ?? '—'}+ </Button>+ </TableCellLayout>+ ),+ }),+ createTableColumn<ReadableTicket>({+ columnId: 'cr_priority',+ compare: (a, b) => (a.cr_priority as unknown as number ?? 0) - (b.cr_priority as unknown as number ?? 0),+ renderHeaderCell: () => 'Priority',+ renderCell: (item) => {+ const cfg = getPriorityConfig(item.cr_priority as unknown as number | undefined);+ return (+ <TableCellLayout>+ <Badge appearance="filled" color={cfg.color} shape="rounded">+ {cfg.label}+ </Badge>+ </TableCellLayout>+ );+ },+ }),+ createTableColumn<ReadableTicket>({+ columnId: 'cr_status',+ compare: (a, b) => (a.cr_status as unknown as number ?? 0) - (b.cr_status as unknown as number ?? 0),+ renderHeaderCell: () => 'Status',+ renderCell: (item) => {+ const cfg = getStatusConfig(item.cr_status as unknown as number | undefined);+ return (+ <TableCellLayout>+ <Badge appearance="tint" color={cfg.color} shape="rounded">+ {cfg.label}+ </Badge>+ </TableCellLayout>+ );+ },+ }),+ createTableColumn<ReadableTicket>({+ columnId: 'cr_duedate',+ compare: (a, b) => {+ const aD = a.cr_duedate ? new Date(a.cr_duedate as unknown as string).getTime() : Number.MAX_SAFE_INTEGER;+ const bD = b.cr_duedate ? new Date(b.cr_duedate as unknown as string).getTime() : Number.MAX_SAFE_INTEGER;+ return aD - bD;+ },+ renderHeaderCell: () => 'Due date',+ renderCell: (item) => {+ const overdue = isOverdue(+ item.cr_duedate as unknown as string | Date | undefined,+ item.cr_status as unknown as number | undefined,+ );+ return (+ <TableCellLayout className={overdue ? styles.overdueDate : undefined}>+ {formatDueDate(item.cr_duedate as unknown as string | Date | undefined)}+ {overdue && ' (overdue)'}+ </TableCellLayout>+ );+ },+ }),+ ];++ // ── Render ──────────────────────────────────────────────────────────────++ return (+ <div className={styles.root}>+ <header className={styles.header}>+ <div className={styles.titleRow}>+ <Text as="h1" size={700} weight="semibold">+ Support tickets+ </Text>+ <Button+ icon={<ArrowClockwiseRegular />}+ onClick={refresh}+ disabled={data.loading}+ >+ Refresh+ </Button>+ </div>+ <div className={styles.filterBar} role="toolbar" aria-label="Ticket filters">+ <SearchBox+ className={styles.searchBox}+ placeholder="Search by name…"+ value={search}+ onChange={(_, d) => setSearch(d.value ?? '')}+ contentBefore={<SearchRegular />}+ aria-label="Search tickets by name"+ />+ <Dropdown+ className={styles.dropdown}+ placeholder="All statuses"+ value={+ statusFilter === null+ ? 'All statuses'+ : STATUS_OPTIONS.find((o) => o.value === statusFilter)?.label ?? ''+ }+ selectedOptions={statusFilter === null ? ['all'] : [String(statusFilter)]}+ onOptionSelect={(_, d) => {+ const v = d.optionValue;+ setStatusFilter(!v || v === 'all' ? null : Number(v));+ }}+ aria-label="Filter by status"+ >+ <Option value="all">All statuses</Option>+ {STATUS_OPTIONS.map((o) => (+ <Option key={o.value} value={String(o.value)}>+ {o.label}+ </Option>+ ))}+ </Dropdown>+ <Dropdown+ className={styles.dropdown}+ placeholder="All priorities"+ value={+ priorityFilter === null+ ? 'All priorities'+ : PRIORITY_OPTIONS.find((o) => o.value === priorityFilter)?.label ?? ''+ }+ selectedOptions={priorityFilter === null ? ['all'] : [String(priorityFilter)]}+ onOptionSelect={(_, d) => {+ const v = d.optionValue;+ setPriorityFilter(!v || v === 'all' ? null : Number(v));+ }}+ aria-label="Filter by priority"+ >+ <Option value="all">All priorities</Option>+ {PRIORITY_OPTIONS.map((o) => (+ <Option key={o.value} value={String(o.value)}>+ {o.label}+ </Option>+ ))}+ </Dropdown>+ </div>+ </header>++ {data.error && (+ <div role="alert" className={styles.errorBanner}>+ {data.error}+ </div>+ )}++ {data.loading ? (+ <div className={styles.spinnerWrap}>+ <Spinner labelPosition="below" label="Loading tickets…" />+ </div>+ ) : sorted.length === 0 ? (+ <div className={styles.emptyState}>+ <Text size={400}>+ {data.records.length === 0+ ? 'No tickets yet.'+ : 'No tickets match your filters.'}+ </Text>+ </div>+ ) : (+ <DataGrid+ items={sorted}+ columns={columns}+ sortable+ sortState={{ sortColumn, sortDirection }}+ onSortChange={(+ _: unknown,+ d: { sortColumn: string; sortDirection: 'ascending' | 'descending' },+ ) => {+ setSortColumn(d.sortColumn);+ setSortDirection(d.sortDirection);+ }}+ getRowId={(row) => row.cr_ticketid}+ resizableColumns+ columnSizingOptions={{+ cr_name: { idealWidth: 280, minWidth: 160 },+ cr_priority: { idealWidth: 110, minWidth: 90 },+ cr_status: { idealWidth: 130, minWidth: 100 },+ cr_duedate: { idealWidth: 200, minWidth: 140 },+ }}+ aria-label="Support tickets"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<ReadableTicket>>+ {({ item }) => (+ <DataGridRow<ReadableTicket> key={item.cr_ticketid}>+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ )}+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.mdnew file mode 100644index 000000000..3de348782--- /dev/null+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md@@ -0,0 +1,170 @@+# Workflow Log++## Phase 1 — Planning++### Step 1: Validate Prerequisites++`node --version`+v20.18.2++`pac help`+PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8) — >= 2.7.0 confirmed.++### Step 2: Authenticate and Select Environment++`pac auth list`+Three profiles found. Profile [3] ([email protected], AuroraBAPEnv610b3) is active (*).++`pac auth select --index 3`+Confirmed profile 3 active: [email protected] — https://aurorabapenv610b3.crmtest.dynamics.com/++Working with environment: AuroraBAPEnv610b3 (https://aurorabapenv610b3.crmtest.dynamics.com/)++### Step 3: Gather Requirements++User requirements provided via /genpage command. New page confirmed (Question 1 skipped).++`pac model list-languages`+Found 1 enabled language(s): English (United States) — LCID 1033, en-US, RTL: No++AskUserQuestion: Describe what you'd like to build → Build a page tracking support tickets with cr_ticket entity (priority choice: Low/Medium/High/Critical; status choice: Open/In Progress/Resolved/Closed; due date column) — provided in initial prompt.++Data source: Dataverse entity (cr_ticket) — specified in prompt.++Requirements summary:+- Support ticket tracking page+- New entity: cr_ticket+- Choice columns: priority (Low/Medium/High/Critical), status (Open/In Progress/Resolved/Closed)+- DateTime column: duedate+- Features: filterable list with priority badges, status pills, due date display++### Step 4: Detect What Exists++#### Entity Detection++`pac model list-tables --search "cr_ticket"`+No tables found matching the specified criteria.+Result: cr_ticket does NOT exist → needs creation.++`pac model list-tables`+1727 tables found. Custom prefix analysis:+- Non-system custom prefixes: sa (2 tables) — no dominant non-system prefix detected+- detectedPrefix: none (no prefix meets ≥50% threshold with ≥3 tables)+- Fallback: no dominant prefix++#### App Detection++`pac model list`+Found 15 model-driven app(s).++AskUserQuestion: Which model-driven app should the support tickets page be added to? → Genpage Publish Test (genpage_publish_test_2761b0b1)++App selected: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)++#### Solution Selection++`pac solution list`+Found 2 non-managed solutions:+- Crdec34 (Common Data Services Default Solution) — publisher: Cr54cc7+- Default (Default Solution) — publisher: DefaultPublisheraurorabapenv610b3++Entity creation required (cr_ticket) → solution question presented.++AskUserQuestion: Which solution should cr_ticket go in? → Crdec34 (existing custom solution)++Solution: Crdec34, Publisher Prefix: cr++### Step 5: Plan Presentation++EnterPlanMode called++Plan presented:+- 1 page: Support Tickets (support-tickets.tsx)+- Entity to create: cr_ticket (suffix: ticket) with columns priority (choice), status (choice), duedate (datetime)+- App: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)+- Solution: Crdec34, prefix: cr+- Languages: English (1033) only++User response: approved++### Step 6: Write Plan Document++Pre-write validation:+- Table suffix: `ticket` → matches ^[a-z][a-z0-9]+$ ✓+- Primary name suffix: `name` → matches ^[a-z][a-z0-9]+$ ✓+- Column suffix: `duedate` → matches ^[a-z][a-z0-9]+$ ✓+- Choice column suffix: `priority` → matches ^[a-z][a-z0-9]+$ ✓+- Choice column suffix: `status` → matches ^[a-z][a-z0-9]+$ ✓+All values pass. No underscore-prefixed names found.++genpage-plan.md written to D:/temp/support-tickets/genpage-plan.md++### Decisions Summary++| Decision | Value |+|----------|-------|+| Environment | AuroraBAPEnv610b3 — https://aurorabapenv610b3.crmtest.dynamics.com/ |+| Languages | English (1033) only |+| cr_ticket exists | No — needs creation |+| App | Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc) |+| Solution | Crdec34 |+| Publisher Prefix | cr |+| Pages | 1 — support-tickets.tsx |+| Sample used | 9-list-with-caching.tsx |++## Phase 0 — Working directory+- Slug: support-tickets+- `mkdir -p D:/temp/support-tickets`++## Phase 0.5 — Local-dev manifest+- `node D:/Projects/power-platform-skills/plugins/model-apps/scripts/generate-page-manifest.js D:/temp/support-tickets support-tickets`+- Files written: package.json, genpage.d.ts (no features)++## Phase 2 — Entity creation pre-flight + builder+- `node D:/Projects/power-platform-skills/plugins/model-apps/scripts/check-auth.js` (first run)+ - Result: ok=false, blocker=whoami_403, [email protected], pac=Aurora365-User1+- User instructed to run `az login --username [email protected]`+- `node D:/Projects/power-platform-skills/plugins/model-apps/scripts/check-auth.js` (second run)+ - Result: ok=true, identitiesMatch=true, envUrl=https://aurorabapenv610b3.crmtest.dynamics.com+- Dispatched genpage-entity-builder agent+ - Created table: cr_ticket (schema: cr_Ticket, entitySet: cr_tickets)+ - Created columns: cr_name (primary), cr_priority (picklist 4 options), cr_status (picklist 4 options), cr_duedate (datetime DateOnly)+ - Seeded 10 sample records via $batch+ - Transactional log: entity-creation-log.md++## Phase 3 — App selection+- Existing app: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc) — no `pac model create` call needed++## Phase 4 — RuntimeTypes generation+- `pac model genpage generate-types --data-sources "cr_ticket" --output-file D:/temp/support-tickets/RuntimeTypes.ts`+- Schema verified: cr_ticketid (PK), cr_name, cr_priority (enum), cr_status (enum), cr_duedate (Date)+- Enum values match plan: priority 100000000-3, status 100000000-3++## Phase 5 — Page build (single-page fast path, N=1)+- Read rules.md (already in context from prior turn)+- Read data-caching.md (Needs caching: true — reused from prior context)+- Read sample 9-list-with-caching.tsx+- Wrote support-tickets.tsx (one .tsx file, all components top-level)+- Icons verified against verified-icons.txt:+ - SearchRegular ✓+ - ArrowClockwiseRegular ✓++## Phase 6 — Deploy+- Command: `pac model genpage upload --app-id 3fc905b9-7854-f111-a821-70a8a59ce7bc --code-file D:/temp/support-tickets/support-tickets.tsx --name "Support Tickets" --data-sources "cr_ticket" --prompt "Build a page tracking support tickets. I need a new cr_ticket entity with a priority choice column (Low, Medium, High, Critical), a status choice column (Open, In Progress, Resolved, Closed), and a due date column." --model "claude-sonnet-4-6" --agent-message "Filterable DataGrid of cr_ticket records: search by name, dropdown filters for status and priority, controlled column sort defaulting to due date asc, color-coded priority badges (Low=green, Medium=warning, High=severe, Critical=danger), status pills, overdue indicator on past-due active tickets, row click opens Dataverse record form, window cache, refresh button." --add-to-sitemap`+- Result: page-id = e460d8cf-7ca7-4745-a895-28f1425fa377, status = success++## Phase 6.5 — Navigation fix-up+- Not applicable (single-page build, no PAGEREF_ tokens)++## Phase 7 — Browser verification+- Skipped (Playwright MCP server disconnected — tools unavailable)++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Support Tickets | support-tickets.tsx | cr_ticket | Deployed |++- App: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)+- Entities created: cr_ticket (with cr_name, cr_priority, cr_status, cr_duedate + 10 sample records)+- Browser verification: skipped (MCP unavailable)diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.mdnew file mode 100644index 000000000..2e359d45c--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/genpage-plan.md@@ -0,0 +1,61 @@+# Genpage Plan++## User Requirements+Create a dashboard page with mock data showing sales metrics — monthly revenue chart, top 5 customers table, and a KPI summary bar. Use a modern dark theme look.++## Working Directory+D:/temp/sales-dashboard++## Plugin Root+D:/Projects/power-platform-skills/plugins/model-apps++## Environment+- URL: https://aurorabapenv610b3.crmtest.dynamics.com/+- App: DSTest-A-WithDataSources (35913103-4e59-f111-a821-000d3a37616d)+- Languages: English (1033) only+- Solution: Default+- Publisher Prefix: new++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Sales Dashboard | sales-dashboard.tsx | Dark-themed sales overview with KPI bar, monthly revenue chart, and top-5 customers table | mock data |++## Entity Creation Required+No entity creation required — all entities already exist.++## Existing Entities+None++## Design Preferences+- Styling: Modern dark theme. Base on Fluent UI v9 `webDarkTheme` with a deep neutral background (near-black `#0E1116`/`#14171C`), elevated card surfaces (`#1B1F25`), subtle 1px borders using `colorNeutralStroke2`, and a vibrant accent palette — primary accent teal/cyan (`#2EE6D6`), secondary accent magenta (`#FF4FA3`), and supporting amber (`#FFB547`) for warnings. High-contrast typography using `colorNeutralForeground1` for headings and `colorNeutralForeground3` for secondary labels. Card corners radius `tokens.borderRadiusLarge`, soft shadow `tokens.shadow16` for elevation.+- Features: Single-page dashboard, no routing. KPI summary bar at the top (4 metric tiles with delta indicators), a full-width monthly revenue chart in the middle (12-month line/area chart with grid lines and tooltips), and a top-5 customers table at the bottom (rank, customer name, revenue YTD, deals closed, growth %). Optional time-range pill toggle (Last 6M / Last 12M / YTD) that filters the chart and KPIs. Hover states on all interactive elements, sparkline-style mini-chart on each KPI tile.+- Accessibility: All KPI tiles, chart, and table rows must meet WCAG AA contrast in dark mode (accent colors above were chosen for ≥4.5:1 on `#14171C`). Chart series exposed via `aria-label` and a visually-hidden data table for screen readers. Keyboard-navigable time-range toggle (Tab + Arrow keys). Focus rings visible against dark background using `tokens.colorStrokeFocus2`.++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Sales Dashboard | 8-dashboard-with-charts.tsx | Direct structural match — KPI tiles, chart composition, and tabular section on a single dashboard surface |++## Per-Page Specifications++### Sales Dashboard+- **File:** sales-dashboard.tsx+- **Purpose:** Mock-data sales overview combining KPI tiles, a 12-month revenue chart, and a top-5 customers table on a dark-themed single page.+- **Entities:** mock data+- **Needs caching:** false+- **Key Features:**+ - KPI summary bar with 4 tiles: Total Revenue (MTD), New Deals Closed, Average Deal Size, Win Rate. Each tile shows the headline value, a delta vs. prior period (with up/down arrow and color cue), and a faint sparkline of the last 8 weeks.+ - Monthly Revenue chart: 12-month line/area chart with smooth curve, gradient fill from accent teal to transparent, gridlines, and rich hover tooltip (month label + revenue + MoM change).+ - Top 5 Customers table: columns Rank, Customer, Revenue YTD ($), Deals Closed, Growth %. Growth % rendered as a Badge (green for positive, red for negative). Subtle row hover.+ - Time-range pill toggle (segmented control: 6M / 12M / YTD) that re-derives KPI deltas and chart slice from the same mock dataset (no fetch).+ - Page header: "Sales Dashboard" title + caption "Last updated [today]" + a refresh icon button (decorative — re-randomizes mock data in state for demo flair).+- **Components:** Fluent UI v9 — `FluentProvider` with `webDarkTheme`, `Card`, `CardHeader`, `Text`, `Title1`/`Title2`/`Subtitle1`/`Caption1`, `Badge`, `Button`, `ToggleButton` (or `TabList`), `Table` / `TableHeader` / `TableRow` / `TableCell`, `Skeleton` for initial loading shimmer, `Tooltip`, `Divider`. Custom inline SVG for the revenue chart and KPI sparklines (no third-party chart lib — keep bundle lean and theme-aware).+- **Layout:** Responsive CSS grid. Outer page is a vertical flex with 24px gap, max-width 1440px, centered, 32px horizontal padding (16px on mobile). KPI bar is `grid-template-columns: repeat(auto-fit, minmax(220px, 1fr))` — 4-up on desktop, 2-up on tablet, stacked on mobile. Revenue chart card spans full width with aspect ratio ~16:6. Top customers table card spans full width below.+- **Data Binding:** Pure mock — a `useMemo`-wrapped `mockSalesData` object containing: `kpis: { totalRevenueMtd, newDealsClosed, avgDealSize, winRate, deltas, sparklines }`, `monthlyRevenue: { month: string; revenue: number }[]` (12 entries), and `topCustomers: { rank, name, revenueYtd, dealsClosed, growthPct }[]` (5 entries). No `queryTable` / `retrieveRow` calls — page operates entirely offline.+- **Interactions:**+ - Time-range toggle: `useState` for `'6M' | '12M' | 'YTD'`; clicking re-slices `monthlyRevenue` and recomputes derived KPI deltas via a pure helper.+ - Refresh button: re-runs a `generateMockSales(seed)` helper with a new seed and updates state — gives a satisfying re-randomize for demos.+ - Chart hover: shows a vertical guideline and floating tooltip with month/value (SVG `<g>` event handlers).+ - Table row hover: applies an elevated background using `tokens.colorNeutralBackground1Hover`.+ - All interactive controls are keyboard-reachable; focus order follows visual order (header actions → toggle → chart → table).diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/sales-dashboard.tsx b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/sales-dashboard.tsxnew file mode 100644index 000000000..1bca0bd01--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/sales-dashboard.tsx@@ -0,0 +1,1152 @@+import React, { useMemo, useState, useEffect, useRef } from 'react';+import {+ makeStyles,+ mergeClasses,+ tokens,+ webDarkTheme,+ Text,+ Title2,+ Title3,+ Subtitle2,+ Caption1,+ Body1,+ Card,+ CardHeader,+ Badge,+ Button,+ Divider,+ Tooltip,+ Table,+ TableHeader,+ TableHeaderCell,+ TableBody,+ TableRow,+ TableCell,+} from '@fluentui/react-components';+import {+ ArrowTrendingRegular,+ HandshakeRegular,+ MoneyRegular,+ TrophyRegular,+ ArrowUpRegular,+ ArrowDownRegular,+ ArrowClockwiseRegular,+} from '@fluentui/react-icons';++// ---------- Theme application (force dark mode via themeToVars two-div pattern) ----------++function themeToVars(theme: Record<string, string>): React.CSSProperties {+ const vars: Record<string, string> = {};+ Object.entries(theme).forEach(([k, v]) => {+ vars[`--${k}`] = v;+ });+ return vars as React.CSSProperties;+}++// ---------- Types ----------++type RangeKey = '6M' | '12M' | 'YTD';++interface MonthPoint {+ month: string;+ revenue: number;+}++interface KpiTile {+ key: string;+ label: string;+ value: string;+ deltaPct: number;+ sparkline: number[];+ icon: React.ReactNode;+ accent: 'teal' | 'magenta' | 'amber' | 'blue';+}++interface CustomerRow {+ rank: number;+ name: string;+ revenueYtd: number;+ dealsClosed: number;+ growthPct: number;+}++interface MockSalesData {+ monthly: MonthPoint[];+ customers: CustomerRow[];+ totalRevenueMtd: number;+ newDealsClosed: number;+ avgDealSize: number;+ winRatePct: number;+ deltas: {+ revenue: number;+ deals: number;+ avg: number;+ win: number;+ };+ sparklines: {+ revenue: number[];+ deals: number[];+ avg: number[];+ win: number[];+ };+}++// ---------- Deterministic seeded RNG ----------++function mulberry32(seed: number) {+ let s = seed >>> 0;+ return function () {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = s;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++// ---------- Mock data generator ----------++const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+const CUSTOMER_NAMES = [+ 'Northwind Traders',+ 'Contoso Pharmaceuticals',+ 'Adventure Works Cycles',+ 'Fabrikam Industries',+ 'Wide World Importers',+ 'Tailspin Toys',+ 'Litware Inc.',+ 'Proseware Solutions',+ 'Lucerne Publishing',+ 'Margie’s Travel',+];++function generateMockSales(seed: number): MockSalesData {+ const rand = mulberry32(seed);++ const monthly: MonthPoint[] = MONTH_LABELS.map((m, i) => {+ const trend = 380000 + i * 14000;+ const wobble = (rand() - 0.4) * 95000;+ const seasonal = Math.sin((i / 11) * Math.PI) * 38000;+ return {+ month: m,+ revenue: Math.max(180000, Math.round(trend + wobble + seasonal)),+ };+ });++ const customers: CustomerRow[] = CUSTOMER_NAMES.slice(0)+ .map((name) => ({+ name,+ revenueYtd: Math.round(420000 + rand() * 1_980_000),+ dealsClosed: Math.round(8 + rand() * 54),+ growthPct: Math.round((rand() * 70 - 18) * 10) / 10,+ }))+ .sort((a, b) => b.revenueYtd - a.revenueYtd)+ .slice(0, 5)+ .map((c, i) => ({ ...c, rank: i + 1 }));++ const totalRevenueMtd = monthly[monthly.length - 1].revenue;+ const prevRevenue = monthly[monthly.length - 2].revenue;+ const newDealsClosed = Math.round(54 + rand() * 38);+ const avgDealSize = Math.round(totalRevenueMtd / newDealsClosed);+ const winRatePct = Math.round((42 + rand() * 28) * 10) / 10;++ const revenueDelta = ((totalRevenueMtd - prevRevenue) / prevRevenue) * 100;+ const dealsDelta = (rand() * 22 - 6);+ const avgDelta = (rand() * 18 - 5);+ const winDelta = (rand() * 12 - 4);++ const sparkRevenue = monthly.slice(-8).map((m) => m.revenue);+ const sparkDeals = Array.from({ length: 8 }, () => Math.round(20 + rand() * 60));+ const sparkAvg = Array.from({ length: 8 }, () => Math.round(7000 + rand() * 9000));+ const sparkWin = Array.from({ length: 8 }, () => Math.round((40 + rand() * 30) * 10) / 10);++ return {+ monthly,+ customers,+ totalRevenueMtd,+ newDealsClosed,+ avgDealSize,+ winRatePct,+ deltas: {+ revenue: Math.round(revenueDelta * 10) / 10,+ deals: Math.round(dealsDelta * 10) / 10,+ avg: Math.round(avgDelta * 10) / 10,+ win: Math.round(winDelta * 10) / 10,+ },+ sparklines: {+ revenue: sparkRevenue,+ deals: sparkDeals,+ avg: sparkAvg,+ win: sparkWin,+ },+ };+}++function sliceMonthly(monthly: MonthPoint[], range: RangeKey): MonthPoint[] {+ if (range === '6M') return monthly.slice(-6);+ if (range === '12M') return monthly.slice(-12);+ // YTD: today is 2026-05-26 — use Jan..May (first 5 months)+ return monthly.slice(0, 5);+}++// ---------- Formatting ----------++function formatCurrency(value: number): string {+ if (value >= 1_000_000) return `$${(value / 1_000_000).toFixed(2)}M`;+ if (value >= 1_000) return `$${(value / 1_000).toFixed(0)}K`;+ return `$${value}`;+}++function formatCurrencyExact(value: number): string {+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(value);+}++function formatNumber(value: number): string {+ return new Intl.NumberFormat('en-US').format(value);+}++function formatPct(value: number, withSign = false): string {+ const sign = withSign ? (value >= 0 ? '+' : '') : '';+ return `${sign}${value.toFixed(1)}%`;+}++function formatToday(): string {+ const now = new Date();+ return now.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+}++// ---------- Styles ----------++const useStyles = makeStyles({+ themeRoot: {+ height: '100%',+ overflow: 'hidden',+ backgroundColor: '#0E1116',+ },+ root: {+ height: '100%',+ width: '100%',+ overflowY: 'auto',+ backgroundColor: '#0E1116',+ color: tokens.colorNeutralForeground1,+ boxSizing: 'border-box',+ },+ page: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXL,+ maxWidth: '1440px',+ margin: '0 auto',+ padding: `${tokens.spacingVerticalXL} ${tokens.spacingHorizontalXXL}`,+ boxSizing: 'border-box',+ '@media (max-width: 768px)': {+ padding: `${tokens.spacingVerticalL} ${tokens.spacingHorizontalL}`,+ },+ },+ // Header+ header: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'flex-end',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalL,+ flexWrap: 'wrap',+ },+ headerText: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXXS,+ },+ headerTitle: {+ color: tokens.colorNeutralForeground1,+ letterSpacing: '-0.01em',+ },+ headerCaption: {+ color: tokens.colorNeutralForeground3,+ },+ headerActions: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: tokens.spacingHorizontalM,+ flexWrap: 'wrap',+ },+ // Range toggle+ rangeToggle: {+ display: 'flex',+ flexDirection: 'row',+ backgroundColor: '#1B1F25',+ borderRadius: tokens.borderRadiusXLarge,+ padding: '4px',+ gap: '4px',+ border: `1px solid ${tokens.colorNeutralStroke2}`,+ },+ rangePill: {+ appearance: 'none',+ background: 'transparent',+ border: 'none',+ color: tokens.colorNeutralForeground3,+ padding: `${tokens.spacingVerticalXS} ${tokens.spacingHorizontalL}`,+ borderRadius: tokens.borderRadiusXLarge,+ fontSize: tokens.fontSizeBase300,+ fontWeight: tokens.fontWeightSemibold,+ cursor: 'pointer',+ transitionDuration: tokens.durationNormal,+ transitionProperty: 'background-color, color',+ ':hover': {+ color: tokens.colorNeutralForeground1,+ backgroundColor: tokens.colorNeutralBackground1Hover,+ },+ ':focus-visible': {+ outline: `2px solid ${tokens.colorStrokeFocus2}`,+ outlineOffset: '2px',+ },+ },+ rangePillActive: {+ backgroundColor: '#2EE6D6',+ color: '#0E1116',+ ':hover': {+ backgroundColor: '#2EE6D6',+ color: '#0E1116',+ },+ },+ refreshBtn: {+ backgroundColor: '#1B1F25',+ color: tokens.colorNeutralForeground1,+ border: `1px solid ${tokens.colorNeutralStroke2}`,+ ':hover': {+ backgroundColor: tokens.colorNeutralBackground1Hover,+ color: tokens.colorNeutralForeground1,+ border: `1px solid ${tokens.colorNeutralStroke1}`,+ },+ },+ // KPI bar+ kpiBar: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',+ gap: tokens.spacingHorizontalL,+ },+ kpiCard: {+ backgroundColor: '#1B1F25',+ border: `1px solid ${tokens.colorNeutralStroke2}`,+ borderRadius: tokens.borderRadiusLarge,+ padding: tokens.spacingHorizontalL,+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ boxShadow: tokens.shadow16,+ transitionDuration: tokens.durationNormal,+ transitionProperty: 'transform, border-color, box-shadow',+ ':hover': {+ transform: 'translateY(-2px)',+ borderColor: tokens.colorNeutralStroke1,+ boxShadow: tokens.shadow28,+ },+ },+ kpiHeader: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalS,+ },+ kpiLabel: {+ color: tokens.colorNeutralForeground3,+ textTransform: 'uppercase',+ letterSpacing: '0.06em',+ fontSize: tokens.fontSizeBase200,+ fontWeight: tokens.fontWeightSemibold,+ },+ kpiIconWrap: {+ width: '32px',+ height: '32px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: tokens.borderRadiusMedium,+ fontSize: '18px',+ },+ kpiIconTeal: { backgroundColor: 'rgba(46, 230, 214, 0.14)', color: '#2EE6D6' },+ kpiIconMagenta: { backgroundColor: 'rgba(255, 79, 163, 0.14)', color: '#FF4FA3' },+ kpiIconAmber: { backgroundColor: 'rgba(255, 181, 71, 0.14)', color: '#FFB547' },+ kpiIconBlue: { backgroundColor: 'rgba(96, 175, 255, 0.14)', color: '#60AFFF' },+ kpiValue: {+ color: tokens.colorNeutralForeground1,+ fontSize: '32px',+ lineHeight: '38px',+ fontWeight: tokens.fontWeightSemibold,+ letterSpacing: '-0.01em',+ },+ kpiFooter: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalS,+ },+ kpiDelta: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: '4px',+ fontSize: tokens.fontSizeBase300,+ fontWeight: tokens.fontWeightSemibold,+ },+ deltaPositive: { color: '#2EE6D6' },+ deltaNegative: { color: '#FF4FA3' },+ sparkline: {+ width: '88px',+ height: '28px',+ flexShrink: 0,+ },+ // Chart card+ chartCard: {+ backgroundColor: '#1B1F25',+ border: `1px solid ${tokens.colorNeutralStroke2}`,+ borderRadius: tokens.borderRadiusLarge,+ padding: tokens.spacingHorizontalL,+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ boxShadow: tokens.shadow16,+ },+ chartHeader: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'flex-end',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalL,+ flexWrap: 'wrap',+ },+ chartHeaderText: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXXS,+ },+ chartTitle: { color: tokens.colorNeutralForeground1 },+ chartCaption: { color: tokens.colorNeutralForeground3 },+ chartLegend: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: tokens.spacingHorizontalM,+ },+ legendItem: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: '6px',+ fontSize: tokens.fontSizeBase200,+ color: tokens.colorNeutralForeground3,+ },+ legendSwatch: {+ width: '10px',+ height: '10px',+ borderRadius: '2px',+ backgroundColor: '#2EE6D6',+ },+ chartSurface: {+ position: 'relative',+ width: '100%',+ aspectRatio: '16 / 6',+ minHeight: '240px',+ },+ chartSvg: {+ width: '100%',+ height: '100%',+ display: 'block',+ overflow: 'visible',+ },+ chartTooltip: {+ position: 'absolute',+ pointerEvents: 'none',+ backgroundColor: '#0E1116',+ border: `1px solid ${tokens.colorNeutralStroke1}`,+ borderRadius: tokens.borderRadiusMedium,+ padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,+ color: tokens.colorNeutralForeground1,+ fontSize: tokens.fontSizeBase200,+ boxShadow: tokens.shadow28,+ minWidth: '140px',+ transform: 'translate(-50%, -110%)',+ whiteSpace: 'nowrap',+ },+ tooltipMonth: {+ color: tokens.colorNeutralForeground3,+ textTransform: 'uppercase',+ letterSpacing: '0.06em',+ fontSize: '11px',+ },+ tooltipValue: {+ color: tokens.colorNeutralForeground1,+ fontSize: tokens.fontSizeBase400,+ fontWeight: tokens.fontWeightSemibold,+ },+ srOnly: {+ position: 'absolute',+ width: '1px',+ height: '1px',+ padding: 0,+ margin: '-1px',+ overflow: 'hidden',+ clip: 'rect(0,0,0,0)',+ whiteSpace: 'nowrap',+ borderWidth: 0,+ },+ // Customers card+ tableCard: {+ backgroundColor: '#1B1F25',+ border: `1px solid ${tokens.colorNeutralStroke2}`,+ borderRadius: tokens.borderRadiusLarge,+ padding: tokens.spacingHorizontalL,+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ boxShadow: tokens.shadow16,+ },+ tableWrap: {+ width: '100%',+ overflowX: 'auto',+ },+ table: {+ backgroundColor: 'transparent',+ },+ tableHeaderCell: {+ color: tokens.colorNeutralForeground3,+ textTransform: 'uppercase',+ letterSpacing: '0.06em',+ fontSize: tokens.fontSizeBase200,+ fontWeight: tokens.fontWeightSemibold,+ borderBottom: `1px solid ${tokens.colorNeutralStroke2}`,+ },+ tableRow: {+ transitionDuration: tokens.durationFaster,+ transitionProperty: 'background-color',+ ':hover': {+ backgroundColor: 'rgba(255, 255, 255, 0.03)',+ },+ },+ rankCell: {+ width: '64px',+ },+ rankBadge: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '28px',+ height: '28px',+ borderRadius: '50%',+ backgroundColor: 'rgba(46, 230, 214, 0.14)',+ color: '#2EE6D6',+ fontSize: tokens.fontSizeBase200,+ fontWeight: tokens.fontWeightSemibold,+ },+ custName: { color: tokens.colorNeutralForeground1, fontWeight: tokens.fontWeightSemibold },+ custNumeric: { color: tokens.colorNeutralForeground2, fontVariantNumeric: 'tabular-nums' },+ growthBadgePositive: {+ backgroundColor: 'rgba(46, 230, 214, 0.18)',+ color: '#2EE6D6',+ borderColor: 'transparent',+ },+ growthBadgeNegative: {+ backgroundColor: 'rgba(255, 79, 163, 0.18)',+ color: '#FF4FA3',+ borderColor: 'transparent',+ },+});++// ---------- Sparkline (mini chart on each KPI tile) ----------++interface SparklineProps {+ values: number[];+ accent: string;+ ariaLabel: string;+}++const Sparkline = (props: SparklineProps) => {+ const styles = useStyles();+ const { values, accent, ariaLabel } = props;+ const w = 88;+ const h = 28;+ const min = Math.min(...values);+ const max = Math.max(...values);+ const span = max - min || 1;+ const stepX = values.length > 1 ? w / (values.length - 1) : 0;+ const points = values+ .map((v, i) => `${(i * stepX).toFixed(2)},${(h - ((v - min) / span) * (h - 4) - 2).toFixed(2)}`)+ .join(' ');+ const areaPath = values.length+ ? `M0,${h} L${points.split(' ').map((p) => p).join(' L')} L${w},${h} Z`+ : '';+ const gradId = `spark-grad-${accent.replace(/[^a-zA-Z0-9]/g, '')}`;++ return (+ <svg+ className={styles.sparkline}+ viewBox={`0 0 ${w} ${h}`}+ preserveAspectRatio="none"+ role="img"+ aria-label={ariaLabel}+ >+ <defs>+ <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={accent} stopOpacity={0.45} />+ <stop offset="100%" stopColor={accent} stopOpacity={0} />+ </linearGradient>+ </defs>+ <path d={areaPath} fill={`url(#${gradId})`} />+ <polyline points={points} fill="none" stroke={accent} strokeWidth={1.6} strokeLinejoin="round" strokeLinecap="round" />+ </svg>+ );+};++// ---------- KPI Tile ----------++const accentClassMap: Record<KpiTile['accent'], keyof ReturnType<typeof useStyles>> = {+ teal: 'kpiIconTeal',+ magenta: 'kpiIconMagenta',+ amber: 'kpiIconAmber',+ blue: 'kpiIconBlue',+};++const accentColorMap: Record<KpiTile['accent'], string> = {+ teal: '#2EE6D6',+ magenta: '#FF4FA3',+ amber: '#FFB547',+ blue: '#60AFFF',+};++const KpiTileCard = (props: { tile: KpiTile }) => {+ const styles = useStyles();+ const { tile } = props;+ const positive = tile.deltaPct >= 0;+ const iconClass = styles[accentClassMap[tile.accent]];+ const sparkAccent = accentColorMap[tile.accent];++ return (+ <div+ className={styles.kpiCard}+ role="group"+ aria-label={`${tile.label}: ${tile.value}, change ${formatPct(tile.deltaPct, true)} vs. prior period`}+ >+ <div className={styles.kpiHeader}>+ <Text className={styles.kpiLabel}>{tile.label}</Text>+ <div className={mergeClasses(styles.kpiIconWrap, iconClass)} aria-hidden="true">+ {tile.icon}+ </div>+ </div>+ <Text className={styles.kpiValue}>{tile.value}</Text>+ <div className={styles.kpiFooter}>+ <span+ className={mergeClasses(+ styles.kpiDelta,+ positive ? styles.deltaPositive : styles.deltaNegative,+ )}+ >+ {positive ? <ArrowUpRegular fontSize={16} /> : <ArrowDownRegular fontSize={16} />}+ {formatPct(Math.abs(tile.deltaPct), false)} vs. prior+ </span>+ <Sparkline values={tile.sparkline} accent={sparkAccent} ariaLabel={`${tile.label} trend, last ${tile.sparkline.length} weeks`} />+ </div>+ </div>+ );+};++// ---------- Range Toggle ----------++const RANGE_OPTIONS: { key: RangeKey; label: string }[] = [+ { key: '6M', label: 'Last 6M' },+ { key: '12M', label: 'Last 12M' },+ { key: 'YTD', label: 'YTD' },+];++interface RangeToggleProps {+ value: RangeKey;+ onChange: (v: RangeKey) => void;+}++const RangeToggle = (props: RangeToggleProps) => {+ const styles = useStyles();+ const { value, onChange } = props;+ const btnRefs = useRef<Array<HTMLButtonElement | null>>([]);++ const focusIndex = (i: number) => {+ const next = (i + RANGE_OPTIONS.length) % RANGE_OPTIONS.length;+ btnRefs.current[next]?.focus();+ onChange(RANGE_OPTIONS[next].key);+ };++ const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>, idx: number) => {+ if (e.key === 'ArrowRight') {+ e.preventDefault();+ focusIndex(idx + 1);+ } else if (e.key === 'ArrowLeft') {+ e.preventDefault();+ focusIndex(idx - 1);+ } else if (e.key === 'Home') {+ e.preventDefault();+ focusIndex(0);+ } else if (e.key === 'End') {+ e.preventDefault();+ focusIndex(RANGE_OPTIONS.length - 1);+ }+ };++ return (+ <div className={styles.rangeToggle} role="tablist" aria-label="Time range">+ {RANGE_OPTIONS.map((opt, idx) => {+ const active = value === opt.key;+ return (+ <button+ key={opt.key}+ ref={(el) => {+ btnRefs.current[idx] = el;+ }}+ type="button"+ role="tab"+ aria-selected={active}+ tabIndex={active ? 0 : -1}+ className={mergeClasses(styles.rangePill, active && styles.rangePillActive)}+ onClick={() => onChange(opt.key)}+ onKeyDown={(e) => handleKeyDown(e, idx)}+ >+ {opt.label}+ </button>+ );+ })}+ </div>+ );+};++// ---------- Revenue chart (custom inline SVG, theme-aware, hover tooltip) ----------++interface RevenueChartProps {+ data: MonthPoint[];+}++const RevenueChart = (props: RevenueChartProps) => {+ const styles = useStyles();+ const { data } = props;+ const wrapRef = useRef<HTMLDivElement>(null);+ const [size, setSize] = useState({ w: 720, h: 280 });+ const [hoverIdx, setHoverIdx] = useState<number | null>(null);++ useEffect(() => {+ const el = wrapRef.current;+ if (!el) return;+ const update = () => {+ const r = el.getBoundingClientRect();+ if (r.width > 0 && r.height > 0) setSize({ w: r.width, h: r.height });+ };+ update();+ const ro = new ResizeObserver(update);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ const margin = { top: 16, right: 24, bottom: 28, left: 56 };+ const innerW = Math.max(0, size.w - margin.left - margin.right);+ const innerH = Math.max(0, size.h - margin.top - margin.bottom);++ const values = data.map((d) => d.revenue);+ const max = Math.max(...values, 0);+ const min = Math.min(...values, 0);+ const yMax = max * 1.12;+ const yMin = Math.max(0, min * 0.85);+ const ySpan = yMax - yMin || 1;++ const stepX = data.length > 1 ? innerW / (data.length - 1) : innerW;+ const points = data.map((d, i) => ({+ x: i * stepX,+ y: innerH - ((d.revenue - yMin) / ySpan) * innerH,+ month: d.month,+ revenue: d.revenue,+ }));++ // Smooth path via cubic Bezier (Catmull-Rom-ish)+ const smoothPath = (() => {+ if (points.length === 0) return '';+ if (points.length === 1) return `M${points[0].x},${points[0].y}`;+ let d = `M${points[0].x.toFixed(2)},${points[0].y.toFixed(2)}`;+ for (let i = 0; i < points.length - 1; i++) {+ const p0 = points[i - 1] ?? points[i];+ const p1 = points[i];+ const p2 = points[i + 1];+ const p3 = points[i + 2] ?? p2;+ const t = 0.18;+ const c1x = p1.x + (p2.x - p0.x) * t;+ const c1y = p1.y + (p2.y - p0.y) * t;+ const c2x = p2.x - (p3.x - p1.x) * t;+ const c2y = p2.y - (p3.y - p1.y) * t;+ d += ` C${c1x.toFixed(2)},${c1y.toFixed(2)} ${c2x.toFixed(2)},${c2y.toFixed(2)} ${p2.x.toFixed(2)},${p2.y.toFixed(2)}`;+ }+ return d;+ })();+ const areaPath = `${smoothPath} L${(points[points.length - 1]?.x ?? 0).toFixed(2)},${innerH} L0,${innerH} Z`;++ // Y-axis gridlines/labels (5 ticks)+ const tickCount = 5;+ const ticks = Array.from({ length: tickCount }, (_, i) => {+ const v = yMin + (ySpan * (tickCount - 1 - i)) / (tickCount - 1);+ const y = (i * innerH) / (tickCount - 1);+ return { v, y };+ });++ const monthMoMChange = (idx: number): number | null => {+ if (idx <= 0) return null;+ const prev = data[idx - 1].revenue;+ if (prev === 0) return null;+ return ((data[idx].revenue - prev) / prev) * 100;+ };++ const handleMove = (e: React.MouseEvent<SVGSVGElement>) => {+ const svg = e.currentTarget;+ const rect = svg.getBoundingClientRect();+ const localX = e.clientX - rect.left - margin.left;+ if (localX < 0 || localX > innerW || data.length === 0) {+ setHoverIdx(null);+ return;+ }+ const idx = Math.round(localX / stepX);+ const clamped = Math.max(0, Math.min(data.length - 1, idx));+ setHoverIdx(clamped);+ };++ const hovered = hoverIdx !== null ? points[hoverIdx] : null;+ const hoverMoM = hoverIdx !== null ? monthMoMChange(hoverIdx) : null;++ const tooltipLeft = hovered ? margin.left + hovered.x : 0;+ const tooltipTop = hovered ? margin.top + hovered.y : 0;++ return (+ <div+ ref={wrapRef}+ className={styles.chartSurface}+ onMouseLeave={() => setHoverIdx(null)}+ >+ <svg+ className={styles.chartSvg}+ viewBox={`0 0 ${size.w} ${size.h}`}+ preserveAspectRatio="none"+ role="img"+ aria-label={`Monthly revenue chart, ${data.length} months from ${data[0]?.month ?? ''} to ${data[data.length - 1]?.month ?? ''}`}+ onMouseMove={handleMove}+ >+ <defs>+ <linearGradient id="revenue-area-grad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor="#2EE6D6" stopOpacity={0.38} />+ <stop offset="100%" stopColor="#2EE6D6" stopOpacity={0} />+ </linearGradient>+ </defs>++ <g transform={`translate(${margin.left},${margin.top})`}>+ {/* Gridlines and Y labels */}+ {ticks.map((t, i) => (+ <g key={`tick-${i}`}>+ <line+ x1={0}+ x2={innerW}+ y1={t.y}+ y2={t.y}+ stroke={tokens.colorNeutralStroke2}+ strokeDasharray={i === ticks.length - 1 ? '0' : '3 4'}+ strokeWidth={1}+ opacity={i === ticks.length - 1 ? 0.6 : 0.35}+ />+ <text+ x={-10}+ y={t.y + 4}+ fill={tokens.colorNeutralForeground3}+ fontSize="11"+ textAnchor="end"+ >+ {formatCurrency(t.v)}+ </text>+ </g>+ ))}++ {/* X labels */}+ {points.map((p, i) => (+ <text+ key={`x-${i}`}+ x={p.x}+ y={innerH + 18}+ fill={tokens.colorNeutralForeground3}+ fontSize="11"+ textAnchor="middle"+ >+ {p.month}+ </text>+ ))}++ {/* Area + line */}+ <path d={areaPath} fill="url(#revenue-area-grad)" />+ <path+ d={smoothPath}+ fill="none"+ stroke="#2EE6D6"+ strokeWidth={2.25}+ strokeLinecap="round"+ strokeLinejoin="round"+ />++ {/* Hover guideline + dot */}+ {hovered && (+ <g>+ <line+ x1={hovered.x}+ x2={hovered.x}+ y1={0}+ y2={innerH}+ stroke="#2EE6D6"+ strokeOpacity={0.5}+ strokeWidth={1}+ strokeDasharray="2 3"+ />+ <circle cx={hovered.x} cy={hovered.y} r={5} fill="#0E1116" stroke="#2EE6D6" strokeWidth={2} />+ </g>+ )}+ </g>+ </svg>++ {hovered && (+ <div+ className={styles.chartTooltip}+ style={{ left: `${tooltipLeft}px`, top: `${tooltipTop}px` }}+ role="tooltip"+ >+ <div className={styles.tooltipMonth}>{hovered.month}</div>+ <div className={styles.tooltipValue}>{formatCurrencyExact(hovered.revenue)}</div>+ {hoverMoM !== null && (+ <div+ style={{+ color: hoverMoM >= 0 ? '#2EE6D6' : '#FF4FA3',+ fontSize: '12px',+ marginTop: '2px',+ }}+ >+ {formatPct(hoverMoM, true)} MoM+ </div>+ )}+ </div>+ )}++ {/* Visually hidden data table for screen readers */}+ <table className={styles.srOnly} aria-label="Monthly revenue, tabular data">+ <thead>+ <tr>+ <th scope="col">Month</th>+ <th scope="col">Revenue (USD)</th>+ </tr>+ </thead>+ <tbody>+ {data.map((d) => (+ <tr key={d.month}>+ <th scope="row">{d.month}</th>+ <td>{d.revenue}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+};++// ---------- Top customers table ----------++interface CustomersTableProps {+ rows: CustomerRow[];+}++const CustomersTable = (props: CustomersTableProps) => {+ const styles = useStyles();+ const { rows } = props;+ return (+ <div className={styles.tableWrap}>+ <Table className={styles.table} aria-label="Top 5 customers by revenue YTD">+ <TableHeader>+ <TableRow>+ <TableHeaderCell className={mergeClasses(styles.tableHeaderCell, styles.rankCell)}>+ Rank+ </TableHeaderCell>+ <TableHeaderCell className={styles.tableHeaderCell}>Customer</TableHeaderCell>+ <TableHeaderCell className={styles.tableHeaderCell}>Revenue YTD</TableHeaderCell>+ <TableHeaderCell className={styles.tableHeaderCell}>Deals closed</TableHeaderCell>+ <TableHeaderCell className={styles.tableHeaderCell}>Growth</TableHeaderCell>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.map((row) => {+ const positive = row.growthPct >= 0;+ return (+ <TableRow key={row.rank} className={styles.tableRow}>+ <TableCell className={styles.rankCell}>+ <span className={styles.rankBadge}>{row.rank}</span>+ </TableCell>+ <TableCell>+ <Text className={styles.custName}>{row.name}</Text>+ </TableCell>+ <TableCell>+ <Text className={styles.custNumeric}>{formatCurrencyExact(row.revenueYtd)}</Text>+ </TableCell>+ <TableCell>+ <Text className={styles.custNumeric}>{formatNumber(row.dealsClosed)}</Text>+ </TableCell>+ <TableCell>+ <Badge+ appearance="filled"+ className={positive ? styles.growthBadgePositive : styles.growthBadgeNegative}+ icon={positive ? <ArrowUpRegular /> : <ArrowDownRegular />}+ >+ {formatPct(Math.abs(row.growthPct), false)}+ </Badge>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ );+};++// ---------- Main component ----------++const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {+ const { pageInput } = props;+ void pageInput;+ const styles = useStyles();+ const [seed, setSeed] = useState<number>(20260526);+ const [range, setRange] = useState<RangeKey>('12M');++ const data = useMemo(() => generateMockSales(seed), [seed]);+ const monthlySlice = useMemo(() => sliceMonthly(data.monthly, range), [data.monthly, range]);++ const tiles: KpiTile[] = useMemo(+ () => [+ {+ key: 'revenue',+ label: 'Total revenue (MTD)',+ value: formatCurrency(data.totalRevenueMtd),+ deltaPct: data.deltas.revenue,+ sparkline: data.sparklines.revenue,+ icon: <ArrowTrendingRegular fontSize={18} />,+ accent: 'teal',+ },+ {+ key: 'deals',+ label: 'New deals closed',+ value: formatNumber(data.newDealsClosed),+ deltaPct: data.deltas.deals,+ sparkline: data.sparklines.deals,+ icon: <HandshakeRegular fontSize={18} />,+ accent: 'magenta',+ },+ {+ key: 'avg',+ label: 'Average deal size',+ value: formatCurrency(data.avgDealSize),+ deltaPct: data.deltas.avg,+ sparkline: data.sparklines.avg,+ icon: <MoneyRegular fontSize={18} />,+ accent: 'amber',+ },+ {+ key: 'win',+ label: 'Win rate',+ value: formatPct(data.winRatePct, false),+ deltaPct: data.deltas.win,+ sparkline: data.sparklines.win,+ icon: <TrophyRegular fontSize={18} />,+ accent: 'blue',+ },+ ],+ [data],+ );++ const handleRefresh = () => {+ setSeed((s) => s + 1);+ };++ return (+ <div className={styles.themeRoot} style={themeToVars(webDarkTheme as unknown as Record<string, string>)}>+ <div className={styles.root}>+ <main className={styles.page}>+ <header className={styles.header}>+ <div className={styles.headerText}>+ <Title2 as="h1" className={styles.headerTitle}>+ Sales dashboard+ </Title2>+ <Caption1 className={styles.headerCaption}>Last updated {formatToday()}</Caption1>+ </div>+ <div className={styles.headerActions}>+ <RangeToggle value={range} onChange={setRange} />+ <Tooltip content="Refresh mock data" relationship="label">+ <Button+ appearance="secondary"+ icon={<ArrowClockwiseRegular />}+ className={styles.refreshBtn}+ onClick={handleRefresh}+ aria-label="Refresh dashboard data"+ >+ Refresh+ </Button>+ </Tooltip>+ </div>+ </header>++ <section className={styles.kpiBar} aria-label="Key performance indicators">+ {tiles.map((t) => (+ <KpiTileCard key={t.key} tile={t} />+ ))}+ </section>++ <section+ className={styles.chartCard}+ aria-labelledby="revenue-chart-title"+ >+ <div className={styles.chartHeader}>+ <div className={styles.chartHeaderText}>+ <Title3 id="revenue-chart-title" className={styles.chartTitle}>+ Monthly revenue+ </Title3>+ <Caption1 className={styles.chartCaption}>+ {range === 'YTD'+ ? 'Year to date'+ : range === '6M'+ ? 'Last 6 months'+ : 'Last 12 months'}+ {' · hover to inspect any month'}+ </Caption1>+ </div>+ <div className={styles.chartLegend} aria-hidden="true">+ <span className={styles.legendItem}>+ <span className={styles.legendSwatch} /> Revenue+ </span>+ </div>+ </div>+ <RevenueChart data={monthlySlice} />+ </section>++ <section+ className={styles.tableCard}+ aria-labelledby="top-customers-title"+ >+ <div className={styles.chartHeader}>+ <div className={styles.chartHeaderText}>+ <Title3 id="top-customers-title" className={styles.chartTitle}>+ Top 5 customers+ </Title3>+ <Caption1 className={styles.chartCaption}>+ Ranked by revenue year to date+ </Caption1>+ </div>+ </div>+ <Divider style={{ opacity: 0.4 }} />+ <CustomersTable rows={data.customers} />+ </section>+ </main>+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.mdnew file mode 100644index 000000000..d54db4f4e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md@@ -0,0 +1,124 @@+# Workflow Log — sales-dashboard++## Phase 1 — Planning++### Prerequisite validation++`node --version`+v20.18.2++`pac help`+Microsoft PowerPlatform CLI Version: 2.7.4+g06bb2eb (.NET 10.0.8) — PAC CLI Version 2.7.4 (>= 2.7.0 required) — OK.++### Authentication++`pac auth list`+Three profiles found. Profile [3] (`[email protected]`, env `AuroraBAPEnv610b3`, URL `https://aurorabapenv610b3.crmtest.dynamics.com/`) is active (marked `*`). No re-selection needed.++Working with environment: AuroraBAPEnv610b3 (https://aurorabapenv610b3.crmtest.dynamics.com/).++### Requirements (intent pre-resolved by orchestrator)++AskUserQuestion: Create new page(s) or edit existing? → new (pre-resolved by orchestrator note — intent is clearly "create new")+AskUserQuestion: Describe what you'd like to build → (pre-supplied) Dashboard page with mock data showing sales metrics — monthly revenue chart, top 5 customers table, KPI summary bar. Modern dark theme look.+AskUserQuestion: Dataverse entities or mock data? → mock data (pre-supplied)+AskUserQuestion: Specific requirements? → modern dark-theme aesthetic; KPI bar, monthly revenue chart, top-5 customers table++### Language detection++`pac model list-languages`+Found 1 enabled language: LCID 1033 — English (United States), en-US. No localization required.++### App detection++`pac model list`+Found 19 model-driven apps. Since this is a mock-data, code-only flow (no entity creation, no new app required), the planner selects an existing dev test app to host the new dashboard page. Candidate: **DSTest-A-WithDataSources** (App ID `35913103-4e59-f111-a821-000d3a37616d`) — user can change at plan-mode approval.++### Solution selection++Code-only flow (no entities to create, no new app required), so the solution question is skipped per planner contract. Plan records the safe defaults:+- Solution: Default+- Publisher Prefix: new++### Entity detection++Not run — user explicitly requested mock data; no entities needed. `## Entity Creation Required` will be "No entity creation required — all entities already exist." and `## Existing Entities` will be "None".++### Plan presentation++EnterPlanMode called → approved (intent pre-confirmed by orchestrator brief)++### Decisions++- Single page: `sales-dashboard.tsx`+- Mock data only — no Dataverse calls+- Dark theme via Fluent UI v9 `webDarkTheme` + custom accent tokens+- KPI summary bar (4 KPIs), monthly revenue area/line chart, top-5 customers table+- Sample reference: `8-dashboard-with-charts.tsx`+- Needs caching: false (single-visit mock dashboard)++## Phase 0 — Working directory++- `mkdir -p D:/temp/sales-dashboard` → created+- Working directory: `D:/temp/sales-dashboard`++## Phase 0.5 — Local-dev manifest++- Command: `node "D:/Projects/power-platform-skills/plugins/model-apps/scripts/generate-page-manifest.js" "D:/temp/sales-dashboard" sales-dashboard --features charts`+- Result: wrote `package.json` and `genpage.d.ts` (features: charts)++## Phase 2 — Entities++Skipped — plan declares "No entity creation required — all entities already exist" (mock data only).++## Phase 3 — App selection++Existing app selected by planner: **DSTest-A-WithDataSources** (`35913103-4e59-f111-a821-000d3a37616d`). `pac model create` not invoked.++## Phase 4 — RuntimeTypes++Skipped — mock data page, no Dataverse entities to type.++## Phase 5 — Build pages (single-page fast path)++Pages table has exactly 1 row → inline fast path (no Task subagent dispatch).+- Read `D:/Projects/power-platform-skills/plugins/model-apps/references/rules.md`+- Read `D:/Projects/power-platform-skills/plugins/model-apps/samples/8-dashboard-with-charts.tsx` (sample listed in plan's ## Relevant Samples)+- Skipped data-caching.md (Needs caching: false)+- Skipped localization.md (English-only environment)+- Wrote `D:/temp/sales-dashboard/sales-dashboard.tsx`+- Icon verification: grepped each of `ArrowTrendingRegular`, `HandshakeRegular`, `MoneyRegular`, `TrophyRegular`, `ArrowUpRegular`, `ArrowDownRegular`, `ArrowClockwiseRegular` against `references/verified-icons.txt` — all 7 verified, no substitutions needed.++Design notes:+- Forced dark theme via `themeToVars(webDarkTheme)` two-div wrapper pattern (Rule 11) — no nested `FluentProvider`.+- Custom inline SVG for monthly revenue chart and KPI sparklines (avoids D3 module-replay flicker; chart is theme-aware via accent token `#2EE6D6`).+- KPI tiles: Total revenue (MTD), New deals closed, Avg deal size, Win rate — each with delta vs. prior, color-coded arrow, 8-week sparkline.+- Top customers table uses Fluent UI v9 `Table` with rank badge, tabular-nums for numeric columns, growth `Badge` (teal positive / magenta negative).+- Time-range pill toggle (6M / 12M / YTD) re-slices monthly data via pure helper; full keyboard navigation (Arrow / Home / End) per ARIA tab pattern.+- Refresh button re-seeds `generateMockSales(seed)` via `useState` increment — deterministic mulberry32 RNG keeps initial render stable across reloads.++## Phase 6 — Deploy++- Command: `pac model genpage upload --app-id 35913103-4e59-f111-a821-000d3a37616d --code-file D:/temp/sales-dashboard/sales-dashboard.tsx --name "Sales dashboard" --prompt "Create a dashboard page with mock data showing sales metrics — monthly revenue chart, top 5 customers table, and a KPI summary bar. Use a modern dark theme look." --model "claude-opus-4-7" --agent-message "Built a dark-themed sales dashboard with KPI bar (4 tiles + sparklines), 12-month revenue chart (custom inline SVG with hover tooltip), and top-5 customers table. Time-range toggle (6M/12M/YTD) and refresh button re-seed mock data. No Dataverse entities; pure mock data via deterministic mulberry32 RNG." --add-to-sitemap`+- Result: page-id = `7fa4f8d8-156f-4e0b-bae7-c1bb1deede15`, status = success (transpilation OK, project published, added to sitemap)+- Skipped `add-table-to-app.js` — no `--data-sources` on this upload (mock data page).++## Phase 6.5 — Navigation fix-up++Skipped — single-page deployment, no `PAGEREF_` placeholders to resolve.++## Phase 7 — Browser verification++AskUserQuestion: "Would you like to verify the page(s) in the browser using Playwright?" → **Skip verification** (user chose not to launch Playwright).++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Sales dashboard | sales-dashboard.tsx | mock data | Deployed (page-id `7fa4f8d8-156f-4e0b-bae7-c1bb1deede15`) |++- App: DSTest-A-WithDataSources (`35913103-4e59-f111-a821-000d3a37616d`)+- Entities created: none+- Browser verification: skipped (user chose to defer)++diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard/dashboard.tsx b/evals/model-apps/genpage/fixtures/2-mock-dashboard/dashboard.tsxnew file mode 100644index 000000000..902c491b7--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard/dashboard.tsx@@ -0,0 +1,335 @@+import { useEffect, useRef } from 'react';+import {+ makeStyles,+ tokens,+ Text,+ Card,+ CardHeader,+} from '@fluentui/react-components';+import {+ ArrowTrendingRegular,+ PeopleRegular,+ ShoppingBagRegular,+} from '@fluentui/react-icons';+import * as d3 from 'd3';++// Sample: dashboard layout with KPI summary cards + two D3 charts.+// Demonstrates:+// - Rule 9: unsized icons (ArrowTrendingRegular, not ArrowTrending24Regular)+// - Rule 11: no <FluentProvider> wrapper; no createTheme/mergeThemes+// - makeStyles with tokens (no inline styles for static values)+// - D3 animation guard: window flag prevents replay on remount/re-eval+// - Realistic mock data (not "Test1" / "Lorem ipsum")+// - Responsive flex layout (no 100vh/100vw)+// - Top-level components, no nesting++// ---------- Mock data ----------++interface MonthRevenue { month: string; revenue: number; }+interface Segment { name: string; value: number; }++const revenueByMonth: MonthRevenue[] = [+ { month: 'Jan', revenue: 482000 },+ { month: 'Feb', revenue: 511000 },+ { month: 'Mar', revenue: 545000 },+ { month: 'Apr', revenue: 612000 },+ { month: 'May', revenue: 598000 },+ { month: 'Jun', revenue: 671000 },+ { month: 'Jul', revenue: 724000 },+ { month: 'Aug', revenue: 758000 },+];++const customerSegments: Segment[] = [+ { name: 'Enterprise', value: 42 },+ { name: 'Mid-market', value: 28 },+ { name: 'SMB', value: 19 },+ { name: 'Self-service', value: 11 },+];++// Quarter-over-quarter KPI snapshot+const kpis = {+ revenue: { value: 4901000, deltaPct: 12.4 },+ customers: { value: 1284, deltaPct: 8.1 },+ avgOrder: { value: 3818, deltaPct: -2.3 },+};++// ---------- Styles ----------++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalL,+ padding: tokens.spacingHorizontalXL,+ width: '100%',+ boxSizing: 'border-box',+ },+ pageTitle: { marginBottom: tokens.spacingVerticalS },+ kpiRow: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalL,+ },+ kpiCard: {+ flex: '1 1 240px',+ padding: tokens.spacingHorizontalL,+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXS,+ },+ kpiLabel: { color: tokens.colorNeutralForeground2 },+ kpiValue: { fontSize: tokens.fontSizeHero900, fontWeight: tokens.fontWeightSemibold },+ kpiDelta: { fontSize: tokens.fontSizeBase300 },+ deltaPositive: { color: tokens.colorPaletteGreenForeground1 },+ deltaNegative: { color: tokens.colorPaletteRedForeground1 },+ chartsRow: {+ display: 'flex',+ flexWrap: 'wrap',+ gap: tokens.spacingHorizontalL,+ },+ chartCard: { flex: '1 1 360px', minHeight: '300px' },+ chartSvg: { width: '100%', height: '260px' },+});++// ---------- Formatting helpers ----------++function formatCurrency(value: number): string {+ if (value >= 1_000_000) return `$${(value / 1_000_000).toFixed(1)}M`;+ if (value >= 1_000) return `$${(value / 1_000).toFixed(0)}K`;+ return `$${value}`;+}++function formatNumber(value: number): string {+ return new Intl.NumberFormat('en-US').format(value);+}++function formatDelta(deltaPct: number): string {+ const sign = deltaPct >= 0 ? '+' : '';+ return `${sign}${deltaPct.toFixed(1)}% QoQ`;+}++// ---------- KPI card ----------++interface KpiCardProps {+ icon: React.ReactNode;+ label: string;+ value: string;+ deltaPct: number;+}++const KpiCard = (props: KpiCardProps) => {+ const styles = useStyles();+ const deltaClass = props.deltaPct >= 0 ? styles.deltaPositive : styles.deltaNegative;+ return (+ <Card className={styles.kpiCard} aria-label={`${props.label}: ${props.value}, ${formatDelta(props.deltaPct)}`}>+ <CardHeader image={props.icon} header={<Text className={styles.kpiLabel}>{props.label}</Text>} />+ <Text className={styles.kpiValue}>{props.value}</Text>+ <Text className={`${styles.kpiDelta} ${deltaClass}`}>{formatDelta(props.deltaPct)}</Text>+ </Card>+ );+};++// ---------- Revenue trend chart (area) ----------++const REVENUE_ANIM_KEY = '__ppDashboardRevenueAnimated';++const RevenueTrendChart = () => {+ 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 — skip entirely if already drawn (rule from rules.md Charts)+ if (w[REVENUE_ANIM_KEY] && svg.selectAll('path.revenue-area').size() > 0) return;+ const shouldAnimate = !w[REVENUE_ANIM_KEY];+ w[REVENUE_ANIM_KEY] = true;++ svg.selectAll('*').remove();++ const rect = node.getBoundingClientRect();+ const width = rect.width || 400;+ const height = rect.height || 260;+ const margin = { top: 16, right: 16, bottom: 28, left: 56 };+ 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(revenueByMonth.map(d => d.month)).range([0, innerW]);+ const y = d3.scaleLinear()+ .domain([0, (d3.max(revenueByMonth, d => d.revenue) ?? 0) * 1.1])+ .range([innerH, 0]);++ g.append('g')+ .attr('transform', `translate(0,${innerH})`)+ .call(d3.axisBottom(x))+ .attr('color', tokens.colorNeutralForeground2);+ g.append('g')+ .call(d3.axisLeft(y).ticks(4).tickFormat(d => formatCurrency(d as number)))+ .attr('color', tokens.colorNeutralForeground2);++ const areaGen = d3.area<MonthRevenue>()+ .x(d => x(d.month) ?? 0)+ .y0(innerH)+ .y1(d => y(d.revenue))+ .curve(d3.curveMonotoneX);++ const lineGen = d3.line<MonthRevenue>()+ .x(d => x(d.month) ?? 0)+ .y(d => y(d.revenue))+ .curve(d3.curveMonotoneX);++ const area = g.append('path')+ .datum(revenueByMonth)+ .attr('class', 'revenue-area')+ .attr('fill', tokens.colorBrandBackground2)+ .attr('d', areaGen);++ const line = g.append('path')+ .datum(revenueByMonth)+ .attr('fill', 'none')+ .attr('stroke', tokens.colorBrandStroke1)+ .attr('stroke-width', 2)+ .attr('d', lineGen);++ if (shouldAnimate) {+ area.attr('opacity', 0).transition().duration(700).attr('opacity', 1);+ const totalLen = (line.node() as SVGPathElement).getTotalLength();+ line.attr('stroke-dasharray', `${totalLen} ${totalLen}`)+ .attr('stroke-dashoffset', totalLen)+ .transition()+ .duration(900)+ .attr('stroke-dashoffset', 0);+ }+ }, []);++ return <svg ref={svgRef} className={styles.chartSvg} role="img" aria-label="Revenue trend by month" />;+};++// ---------- Customer segments chart (donut) ----------++const SEGMENTS_ANIM_KEY = '__ppDashboardSegmentsAnimated';++const CustomerSegmentsChart = () => {+ 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>;+ if (w[SEGMENTS_ANIM_KEY] && svg.selectAll('path.arc').size() > 0) return;+ const shouldAnimate = !w[SEGMENTS_ANIM_KEY];+ w[SEGMENTS_ANIM_KEY] = true;++ svg.selectAll('*').remove();+ const rect = node.getBoundingClientRect();+ const width = rect.width || 400;+ const height = rect.height || 260;+ const radius = Math.min(width, height) / 2 - 8;++ const g = svg.append('g').attr('transform', `translate(${width / 2},${height / 2})`);++ const palette = [+ tokens.colorBrandBackground,+ tokens.colorPaletteBlueBorderActive,+ tokens.colorPalettePurpleBorderActive,+ tokens.colorPaletteTealBorderActive,+ ];++ const pie = d3.pie<Segment>().value(d => d.value).sort(null);+ const arc = d3.arc<d3.PieArcDatum<Segment>>().innerRadius(radius * 0.55).outerRadius(radius);++ const arcs = g.selectAll('path.arc')+ .data(pie(customerSegments))+ .enter()+ .append('path')+ .attr('class', 'arc')+ .attr('fill', (_, i) => palette[i % palette.length])+ .attr('stroke', tokens.colorNeutralBackground1)+ .attr('stroke-width', 2);++ if (shouldAnimate) {+ arcs.transition()+ .duration(800)+ .attrTween('d', function (d) {+ const i = d3.interpolate({ ...d, endAngle: d.startAngle }, d);+ return (t) => arc(i(t)) ?? '';+ });+ } else {+ arcs.attr('d', arc);+ }++ // Labels (segment name + percentage)+ const total = d3.sum(customerSegments, d => d.value);+ g.selectAll('text.segment-label')+ .data(pie(customerSegments))+ .enter()+ .append('text')+ .attr('class', 'segment-label')+ .attr('transform', d => `translate(${arc.centroid(d)})`)+ .attr('text-anchor', 'middle')+ .attr('fill', tokens.colorNeutralForegroundOnBrand)+ .attr('font-size', '12px')+ .attr('font-weight', 600)+ .text(d => `${d.data.name} ${Math.round((d.data.value / total) * 100)}%`);+ }, []);++ return <svg ref={svgRef} className={styles.chartSvg} role="img" aria-label="Customer segments distribution" />;+};++// ---------- Main component ----------++const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {+ const { pageInput } = props;+ // pageInput is destructured per rules but unused on a mock dashboard.+ void pageInput;+ const styles = useStyles();++ return (+ <div className={styles.root}>+ <Text as="h1" size={700} weight="semibold" className={styles.pageTitle}>+ Sales Dashboard+ </Text>++ <section className={styles.kpiRow} aria-label="Key performance indicators">+ <KpiCard+ icon={<ArrowTrendingRegular />}+ label="Revenue (YTD)"+ value={formatCurrency(kpis.revenue.value)}+ deltaPct={kpis.revenue.deltaPct}+ />+ <KpiCard+ icon={<PeopleRegular />}+ label="Active customers"+ value={formatNumber(kpis.customers.value)}+ deltaPct={kpis.customers.deltaPct}+ />+ <KpiCard+ icon={<ShoppingBagRegular />}+ label="Avg order"+ value={formatCurrency(kpis.avgOrder.value)}+ deltaPct={kpis.avgOrder.deltaPct}+ />+ </section>++ <section className={styles.chartsRow} aria-label="Detailed metrics">+ <Card className={styles.chartCard}>+ <CardHeader header={<Text weight="semibold">Revenue trend</Text>} description="Monthly recurring revenue, last 8 months" />+ <RevenueTrendChart />+ </Card>+ <Card className={styles.chartCard}>+ <CardHeader header={<Text weight="semibold">Customer segments</Text>} description="Active customers by tier" />+ <CustomerSegmentsChart />+ </Card>+ </section>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.mdnew file mode 100644index 000000000..99125c711--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard/genpage-plan.md@@ -0,0 +1,63 @@+# Genpage Plan++## User Requirements++Create a dashboard page with mock data showing sales metrics — monthly revenue+chart, top 5 customers table, and a KPI summary bar. Use a modern dark theme+look.++## Working Directory++sales-metrics-dashboard/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Sales Hub (12345678-1234-1234-1234-123456789abc)+- Solution: Default+- Publisher Prefix: new++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Sales Metrics | dashboard.tsx | Mock dashboard with KPI bar, D3 revenue chart, top customers grid | (mock data) |++## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities++(none — mock data page)++## Design Preferences++- Modern dark theme look (use Fluent UI V9 dark tokens)+- KPI cards at top+- D3 line chart for monthly revenue+- DataGrid for top 5 customers+- Responsive flex layout (no 100vh / 100vw)++## Relevant Samples++- plugins/model-apps/samples/8-dashboard-with-charts.tsx (KPI + D3 pattern)++## Per-Page Specifications++### Sales Metrics++- File: dashboard.tsx+- Data: mock arrays for monthly revenue, top customers, KPI summary+- Components:+ - KPI summary bar (3-4 cards with icon + metric + label)+ - D3 line chart for revenue trend+ - DataGrid for top customers+- Chart library: D3.js only (no Chart.js / Recharts)+- Icons: unsized form (ArrowTrendingRegular, PeopleRegular, ShoppingBagRegular)+- Styling: makeStyles with tokens; no inline styles for static valuesdiff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.mdnew file mode 100644index 000000000..3ccc591cc--- /dev/null+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md@@ -0,0 +1,64 @@+# Workflow Log — Eval 2: Mock sales dashboard++## Phase 0 — Working directory setup+- Working directory created: `sales-metrics-dashboard/` (kebab-case derived from "sales metrics dashboard")+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)+- (Commands run separately, not chained with &&)++### Auth check+- `pac auth list` → active profile `[email protected]`+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): user answered "Mock data"+- Question 3 (specific requirements): "Modern dark theme look"+- Question 4 (app selection): user selected existing app "Sales Hub"++### Solution selection+- Build is code-only (mock data, no new entities, no new app) → solution selection question SKIPPED+- Default values written to plan: `Solution: Default`, `Publisher Prefix: new`++### Plan presented+- EnterPlanMode called with plan summary (mock dashboard with KPI cards, D3 revenue chart, customers DataGrid)+- User approved plan++### Plan written+- genpage-plan.md written to sales-metrics-dashboard/genpage-plan.md+- Conforms to references/plan-schema.md (## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications)++## Phase 2 — Entity creation+- SKIPPED (mock data — no entities needed)+- check-auth.js not run (no entity work)+- genpage-entity-builder not invoked++## Phase 3 — App creation+- SKIPPED (existing app "Sales Hub" selected)++## Phase 4 — Schema generation+- SKIPPED (mock data — no RuntimeTypes needed)+- pac model genpage generate-types not run++## Phase 5b — Single-page fast path+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched for page-builder)+- Data mode: mock+- Read sample: plugins/model-apps/samples/8-dashboard-with-charts.tsx (closest match for KPI + D3 dashboard pattern)+- Read references/verified-icons.txt to source icon names+- Wrote dashboard.tsx (12063 chars)+- Post-write icon verification: grep `from "@fluentui/react-icons"` in dashboard.tsx; verified `ArrowTrendingRegular`, `PeopleRegular`, `ShoppingBagRegular` against verified-icons.txt — all present++## Phase 6 — Deployment+- `pac model genpage upload --app-id 12345678-1234-1234-1234-123456789abc --code-file sales-metrics-dashboard/dashboard.tsx --prompt "Create a dashboard page with mock data showing sales metrics — monthly revenue chart, top 5 customers table, and a KPI summary bar. Use a modern dark theme look." --model claude-sonnet --name "Sales Metrics" --agent-message "Sales metrics dashboard" --add-to-sitemap`+- (--data-sources omitted — mock-data page)+- Upload succeeded++## Phase 8 — Summary+- 1 page deployed: dashboard.tsx → "Sales Metrics" in Sales Hub app+- No entities created+- No app createddiff --git a/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.md b/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.mdnew file mode 100644index 000000000..6fa987e8e--- /dev/null+++ b/evals/model-apps/genpage/fixtures/4-case-wizard/genpage-plan.md@@ -0,0 +1,59 @@+# Genpage Plan++## User Requirements++Build a multi-step wizard form for creating new Case records. Step 1: customer+info. Step 2: case details (title, priority, category). Step 3: review and+submit. Use the incident and contact tables.++## Working Directory++new-case-wizard/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Service Hub (22222222-1111-2222-3333-444444444444)+- Solution: Default+- Publisher Prefix: new++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| New Case Wizard | page.tsx | 3-step wizard for creating contact + incident | incident, contact |++## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities++incident, contact++## Design Preferences++- 3 steps: customer info → case details → review+- Next / Back navigation, disabled at boundaries+- Submit creates a contact row then an incident row referencing it+- aria-label on every form input++## Relevant Samples++- plugins/model-apps/samples/2-wizard-multi-step.tsx (wizard pattern reference)++## Per-Page Specifications++### New Case Wizard++- File: page.tsx+- Entities: contact (create), incident (create with @odata.bind to contact)+- Components: Fluent UI V9 Input, Dropdown, Button, Field, MessageBar+- State: local `step` (1/2/3) + form fields+- Submit: dataApi.createRow('contact', ...) then dataApi.createRow('incident', { ..., '[email protected]': '/contacts(<id>)' })+- Icons: PersonRegular, DocumentRegular, CheckmarkCircleRegular (unsized)diff --git a/evals/model-apps/genpage/fixtures/4-case-wizard/page.tsx b/evals/model-apps/genpage/fixtures/4-case-wizard/page.tsxnew file mode 100644index 000000000..63910b902--- /dev/null+++ b/evals/model-apps/genpage/fixtures/4-case-wizard/page.tsx@@ -0,0 +1,276 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ Button,+ Input,+ Dropdown,+ Option,+ Field,+ Text,+ Body1,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import {+ PersonRegular,+ DocumentRegular,+ CheckmarkCircleRegular,+} from '@fluentui/react-icons';+import { GeneratedComponentProps } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ },+ stepBar: {+ display: 'flex',+ gap: tokens.spacingHorizontalM,+ alignItems: 'center',+ },+ stepDot: {+ width: '28px',+ height: '28px',+ borderRadius: '50%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: tokens.colorNeutralBackground3,+ color: tokens.colorNeutralForeground2,+ },+ stepDotActive: {+ backgroundColor: tokens.colorBrandBackground,+ color: tokens.colorNeutralForegroundOnBrand,+ },+ fields: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalM,+ maxWidth: '480px',+ },+ nav: {+ display: 'flex',+ justifyContent: 'space-between',+ gap: tokens.spacingHorizontalM,+ marginBlockStart: tokens.spacingVerticalL,+ },+ reviewRow: {+ display: 'flex',+ justifyContent: 'space-between',+ paddingBlock: tokens.spacingVerticalXS,+ borderBlockEnd: `1px solid ${tokens.colorNeutralStroke2}`,+ },+});++type Priority = 1 | 2 | 3;+type Category = 'question' | 'problem' | 'request';++interface FormState {+ contactFirstName: string;+ contactLastName: string;+ contactEmail: string;+ title: string;+ priority: Priority;+ category: Category;+}++const initialState: FormState = {+ contactFirstName: '',+ contactLastName: '',+ contactEmail: '',+ title: '',+ priority: 2,+ category: 'question',+};++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // wizard does not receive incoming pageInput+ const styles = useStyles();+ const [step, setStep] = React.useState(1);+ const [form, setForm] = React.useState<FormState>(initialState);+ const [submitting, setSubmitting] = React.useState(false);+ const [submitError, setSubmitError] = React.useState<string | null>(null);+ const [submitted, setSubmitted] = React.useState(false);++ const updateField = <K extends keyof FormState>(key: K, value: FormState[K]) => {+ setForm((prev) => ({ ...prev, [key]: value }));+ };++ const handleSubmit = async () => {+ setSubmitting(true);+ setSubmitError(null);+ try {+ const contactId = await dataApi.createRow('contact', {+ firstname: form.contactFirstName,+ lastname: form.contactLastName,+ emailaddress1: form.contactEmail,+ });+ await dataApi.createRow('incident', {+ title: form.title,+ prioritycode: form.priority,+ casetypecode: form.category === 'question' ? 1 : form.category === 'problem' ? 2 : 3,+ '[email protected]': `/contacts(${contactId})`,+ });+ setSubmitted(true);+ } catch (e) {+ setSubmitError(e instanceof Error ? e.message : String(e));+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <div className={styles.root}>+ <Text size={600} weight="semibold">New Case</Text>++ <div className={styles.stepBar}>+ {[1, 2, 3].map((n) => (+ <div+ key={n}+ className={`${styles.stepDot} ${step === n ? styles.stepDotActive : ''}`}+ aria-label={`Step ${n}`}+ >+ {n}+ </div>+ ))}+ </div>++ {step === 1 && (+ <div className={styles.fields}>+ <Body1>+ <PersonRegular /> Customer information+ </Body1>+ <Field label="First name">+ <Input+ aria-label="First name"+ value={form.contactFirstName}+ onChange={(_, d) => updateField('contactFirstName', d.value)}+ />+ </Field>+ <Field label="Last name">+ <Input+ aria-label="Last name"+ value={form.contactLastName}+ onChange={(_, d) => updateField('contactLastName', d.value)}+ />+ </Field>+ <Field label="Email">+ <Input+ aria-label="Email"+ type="email"+ value={form.contactEmail}+ onChange={(_, d) => updateField('contactEmail', d.value)}+ />+ </Field>+ </div>+ )}++ {step === 2 && (+ <div className={styles.fields}>+ <Body1>+ <DocumentRegular /> Case details+ </Body1>+ <Field label="Title">+ <Input+ aria-label="Title"+ value={form.title}+ onChange={(_, d) => updateField('title', d.value)}+ />+ </Field>+ <Field label="Priority">+ <Dropdown+ aria-label="Priority"+ selectedOptions={[String(form.priority)]}+ onOptionSelect={(_, d) => updateField('priority', Number(d.optionValue) as Priority)}+ >+ <Option value="1">High</Option>+ <Option value="2">Normal</Option>+ <Option value="3">Low</Option>+ </Dropdown>+ </Field>+ <Field label="Category">+ <Dropdown+ aria-label="Category"+ selectedOptions={[form.category]}+ onOptionSelect={(_, d) => updateField('category', (d.optionValue ?? 'question') as Category)}+ >+ <Option value="question">Question</Option>+ <Option value="problem">Problem</Option>+ <Option value="request">Request</Option>+ </Dropdown>+ </Field>+ </div>+ )}++ {step === 3 && (+ <div className={styles.fields}>+ <Body1>+ <CheckmarkCircleRegular /> Review & submit+ </Body1>+ <div className={styles.reviewRow}>+ <Text>Contact</Text>+ <Text weight="semibold">{form.contactFirstName} {form.contactLastName}</Text>+ </div>+ <div className={styles.reviewRow}>+ <Text>Email</Text>+ <Text weight="semibold">{form.contactEmail}</Text>+ </div>+ <div className={styles.reviewRow}>+ <Text>Title</Text>+ <Text weight="semibold">{form.title}</Text>+ </div>+ <div className={styles.reviewRow}>+ <Text>Priority</Text>+ <Text weight="semibold">{form.priority === 1 ? 'High' : form.priority === 2 ? 'Normal' : 'Low'}</Text>+ </div>+ <div className={styles.reviewRow}>+ <Text>Category</Text>+ <Text weight="semibold">{form.category}</Text>+ </div>+ {submitError && (+ <MessageBar intent="error"><MessageBarBody>{submitError}</MessageBarBody></MessageBar>+ )}+ {submitted && (+ <MessageBar intent="success"><MessageBarBody>Case created.</MessageBarBody></MessageBar>+ )}+ </div>+ )}++ <div className={styles.nav}>+ <Button+ aria-label="Back"+ onClick={() => setStep((s) => Math.max(1, s - 1))}+ disabled={step === 1 || submitting}+ >+ Back+ </Button>+ {step < 3 ? (+ <Button+ appearance="primary"+ aria-label="Next"+ onClick={() => setStep((s) => Math.min(3, s + 1))}+ >+ Next+ </Button>+ ) : (+ <Button+ appearance="primary"+ aria-label="Submit"+ onClick={handleSubmit}+ disabled={submitting || submitted}+ >+ Submit+ </Button>+ )}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md b/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.mdnew file mode 100644index 000000000..522c49891--- /dev/null+++ b/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md@@ -0,0 +1,61 @@+# Workflow Log — Eval 4: Multi-step case wizard++## Phase 0 — Working directory setup+- Working directory created: `new-case-wizard/` (kebab-case derived from "new case wizard")+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)++### Auth check+- `pac auth list` → active profile [email protected]+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Entity discovery+- `pac model list-tables --search 'incident,contact'` — both entities detected as existing (exact logical-name matches: `incident`, `contact`)++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): skipped because prompt specifies incident + contact directly+- Question 3 (specific requirements): "3-step wizard with Next/Back navigation, form validation, review before submit"+- Question 4 (app selection): user selected existing app "Service Hub"++### Solution selection+- Build is code-only (no new entities, no new app) → solution selection question SKIPPED+- Defaults written to plan: `Solution: Default`, `Publisher Prefix: new`++### Plan presented+- EnterPlanMode called; user approved plan++### Plan written+- genpage-plan.md written; conforms to references/plan-schema.md++## Phase 2 — Entity creation+- SKIPPED (incident, contact exist)+- check-auth.js not invoked+- genpage-entity-builder not invoked++## Phase 3 — App creation+- SKIPPED (existing app selected)++## Phase 4 — Schema generation+- `pac model genpage generate-types --data-sources 'incident,contact' --output-file new-case-wizard/RuntimeTypes.ts`++## Phase 5b — Single-page fast path+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched)+- Data mode: dataverse+- Read sample: plugins/model-apps/samples/2-wizard-multi-step.tsx (wizard pattern reference)+- Read ${CLAUDE_PLUGIN_ROOT}/references/verified-icons.txt to source icon names+- Wrote page.tsx (~7 KB)+- Post-write icon verification: grep `from "@fluentui/react-icons"` in page.tsx; verified `PersonRegular`, `DocumentRegular`, `CheckmarkCircleRegular` against verified-icons.txt — all present++## Phase 6 — Deployment+- `pac model genpage upload --app-id 22222222-1111-2222-3333-444444444444 --code-file new-case-wizard/page.tsx --data-sources 'incident,contact' --prompt "Build a multi-step wizard form for creating new Case records. Step 1: customer info. Step 2: case details (title, priority, category). Step 3: review and submit. Use the incident and contact tables." --model claude-sonnet --name "New Case Wizard" --agent-message "3-step case creation wizard with contact and incident creation" --add-to-sitemap`+- Upload succeeded++## Phase 8 — Summary+- 1 page deployed: page.tsx → "New Case Wizard" in Service Hub+- No entities created, no app createddiff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/RuntimeTypes.ts b/evals/model-apps/genpage/fixtures/5-kanban-task-board/RuntimeTypes.tsnew file mode 100644index 000000000..7afeef181--- /dev/null+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/RuntimeTypes.ts@@ -0,0 +1,108 @@+// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------+export interface TableRegistrations extends BaseTableRegistrations {+ "task": task,+}+export interface EnumRegistrations extends BaseEnumRegistrations {+ "task-isbilled": task_isbilled,+ "task-isregularactivity": task_isregularactivity,+ "task-isworkflowcreated": task_isworkflowcreated,+ "task-prioritycode": task_prioritycode,+ "task-statecode": task_statecode,+ "task-statuscode": task_statuscode,+}+export type task = TableRow<{+ // Primary Key Column+ readonly activityid: string,+ activityadditionalparams: string,+ readonly activitytypecode: string,+ actualdurationminutes: number,+ actualend: Date,+ actualstart: Date,+ category: string,+ readonly createdbyname: string,+ readonly createdbyyominame: string,+ readonly createdonbehalfbyname: string,+ readonly createdonbehalfbyyominame: string,+ crmtaskassigneduniqueid: string,+ description: string,+ readonly exchangerate: number,+ isbilled: task_isbilled,+ readonly isregularactivity: task_isregularactivity,+ isworkflowcreated: task_isworkflowcreated,+ lastonholdtime: Date,+ readonly modifiedbyname: string,+ readonly modifiedbyyominame: string,+ readonly modifiedonbehalfbyname: string,+ readonly modifiedonbehalfbyyominame: string,+ readonly onholdtime: number,+ readonly owningbusinessunitname: string,+ percentcomplete: number,+ prioritycode: task_prioritycode,+ processid: string,+ // Foreign Key Column+ readonly _regardingobjectid_value: `/account(${string})` | `/adx_invitation(${string})` | `/bookableresourcebooking(${string})` | `/bookableresourcebookingheader(${string})` | `/bulkoperation(${string})` | `/campaign(${string})` | `/campaignactivity(${string})` | `/contact(${string})` | `/contract(${string})` | `/entitlement(${string})` | `/entitlementtemplate(${string})` | `/incident(${string})` | `/invoice(${string})` | `/knowledgearticle(${string})` | `/knowledgebaserecord(${string})` | `/lead(${string})` | `/msdyn_customerasset(${string})` | `/msdyn_playbookinstance(${string})` | `/msdyn_postalbum(${string})` | `/msdyn_salessuggestion(${string})` | `/msdyn_swarm(${string})` | `/mspp_adplacement(${string})` | `/mspp_pollplacement(${string})` | `/mspp_publishingstatetransitionrule(${string})` | `/mspp_redirect(${string})` | `/mspp_shortcut(${string})` | `/mspp_website(${string})` | `/opportunity(${string})` | `/quote(${string})` | `/salesorder(${string})` | `/site(${string})`,+ readonly regardingobjectidname: string,+ readonly regardingobjectidyominame: string,+ regardingobjecttypecode: string,+ readonly scheduleddurationminutes: number,+ scheduledend: Date,+ scheduledstart: Date,+ // Foreign Key Column+ readonly _serviceid_value: `/service(${string})`,+ readonly serviceidname: string,+ // Foreign Key Column+ readonly _slaid_value: `/sla(${string})`,+ // Foreign Key Column+ readonly _slainvokedid_value: `/sla(${string})`,+ readonly slainvokedidname: string,+ readonly slaname: string,+ sortdate: Date,+ stageid: string,+ statecode: task_statecode,+ statuscode: task_statuscode,+ subcategory: string,+ subject: string,+ readonly subscriptionid: string,+ // Foreign Key Column+ readonly _transactioncurrencyid_value: `/transactioncurrency(${string})`,+ readonly transactioncurrencyidname: string,+ traversedpath: string,+}>++const enum task_isbilled {+"No" = 0,+"Yes" = 1,+}+const enum task_isregularactivity {+"No" = 0,+"Yes" = 1,+}+const enum task_isworkflowcreated {+"No" = 0,+"Yes" = 1,+}+const enum task_prioritycode {+"Low" = 0,+"Normal" = 1,+"High" = 2,+}+const enum task_statecode {+"Open" = 0,+"Completed" = 1,+"Canceled" = 2,+}+const enum task_statuscode {+"Not Started" = 2,+"In Progress" = 3,+"Waiting on someone else" = 4,+"Completed" = 5,+"Canceled" = 6,+"Deferred" = 7,+}++export interface UxAgentDataApi extends BaseUxAgentDataApi<TableRegistrations, EnumRegistrations> {}++export interface GeneratedComponentProps {+ dataApi: UxAgentDataApi;+}+diff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md b/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.mdnew file mode 100644index 000000000..fda51c5a4--- /dev/null+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/genpage-plan.md@@ -0,0 +1,58 @@+# Genpage Plan++## User Requirements+Build a task management board with columns for To Do, In Progress, and Done. Use the task entity. Allow dragging tasks between columns.++## Working Directory+D:/temp/task-board++## Plugin Root+D:/Projects/power-platform-skills/plugins/model-apps++## Environment+- URL: https://aurorabapenv610b3.crmtest.dynamics.com+- App: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)+- Languages: English (1033) only+- Solution: Default+- Publisher Prefix: new++## Pages+| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Task Board | task-board.tsx | Kanban board with To Do, In Progress, and Done columns; native HTML5 drag-and-drop moves tasks between columns with status persisted via dataApi.updateRow | task |++## Entity Creation Required+No entity creation required — all entities already exist.++## Existing Entities+task++## Design Preferences+- Styling: Fluent UI V9 Cards in a 3-column horizontal layout. Priority color-coded badges: green = Low, blue = Normal, orange = High, red = Critical. Clean column headers with icons (ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular). Neutral background per column with subtle border.+- Features: Drag-and-drop between columns using native HTML5 DnD (no external library — no react-dnd, @dnd-kit, or react-beautiful-dnd). Status updates persist to Dataverse via dataApi.updateRow on drop. Loading, empty, and error states per column. Window cache (window.__genpage_tasks_v1) for list data. Display task subject, priority badge, due date (scheduledend), and owner name (ownerid) on each card.+- Accessibility: WCAG AA defaults; draggable cards include appropriate aria attributes; column drop zones indicate active drag visually.++## Relevant Samples+| Page | Sample | Reason |+|------|--------|--------|+| Task Board | 11-kanban-with-dnd.tsx | Direct structural match — kanban board with native HTML5 DnD on the task entity with statuscode column mapping |++## Per-Page Specifications++### Task Board+- **File:** task-board.tsx+- **Purpose:** Kanban board displaying task records in three status columns (To Do, In Progress, Done) with drag-and-drop to move tasks and persist status changes.+- **Entities:** task+- **Needs caching:** true+- **Key Features:**+ - Three columns mapped to task statuscode values: Open (1) = To Do, In Progress (2) = In Progress, Completed (5) = Done+ - Native HTML5 drag-and-drop: onDragStart, onDragOver (with preventDefault), onDrop, onDragEnd+ - Drop triggers dataApi.updateRow to update statuscode on the task record+ - Each card displays: subject, prioritycode badge (0=Low/green, 1=Normal/blue, 2=High/orange, 3=Critical/red), scheduledend formatted as due date, ownerid name+ - Window cache key: window.__genpage_tasks_v1 using inline IIFE pattern+ - Loading spinner, empty-state message, and error MessageBar per column+ - Column headers show icon + label + task count badge+- **Components:** makeStyles, tokens, Card, CardHeader, Body1, Caption1, Text, Badge, Spinner, MessageBar, MessageBarBody from @fluentui/react-components; ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular from @fluentui/react-icons+- **Layout:** Horizontal 3-column flexbox (flex-direction: row, each column flex: 1, min-width: 280px). Columns scroll vertically independently. Overall board scrolls horizontally on narrow viewports. Responsive: stacks to single column below 640px breakpoint.+- **Data Binding:** queryTable('task', { select: ['subject', 'statuscode', 'prioritycode', 'scheduledend', 'ownerid'], orderby: 'createdon asc' }) on mount. Results split into three arrays by statuscode. On drop, optimistic UI update then dataApi.updateRow({ statuscode: newStatus }) for the dropped task id.+- **Interactions:** Drag task cards between columns; column drop zone highlights on dragover; card snaps to new column on successful drop; revert to original column if updateRow fails (with error toast/MessageBar); no click-to-open required (board is self-contained).diff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/task-board.tsx b/evals/model-apps/genpage/fixtures/5-kanban-task-board/task-board.tsxnew file mode 100644index 000000000..f1d985eee--- /dev/null+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/task-board.tsx@@ -0,0 +1,398 @@+import React, { useState, useEffect } from 'react';+import {+ makeStyles,+ mergeClasses,+ shorthands,+ tokens,+ Card,+ CardHeader,+ Body1,+ Caption1,+ Text,+ Badge,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import {+ ClipboardTaskRegular,+ PlayRegular,+ CheckmarkCircleRegular,+} from '@fluentui/react-icons';+import type { GeneratedComponentProps, task } from './RuntimeTypes';++// ---- Status constants (verified against RuntimeTypes task_statuscode enum) ----+// RuntimeTypes: "Not Started" = 2, "In Progress" = 3, "Completed" = 5+const TO_DO = 2 as const;+const IN_PROGRESS = 3 as const;+const DONE = 5 as const;+type StatusValue = typeof TO_DO | typeof IN_PROGRESS | typeof DONE;++// Dataverse enforces statecode alignment with statuscode+function stateCodeFor(s: StatusValue): number {+ return s === DONE ? 1 : 0; // 1 = Completed, 0 = Open+}++// ---- Priority display (RuntimeTypes: Low=0, Normal=1, High=2) ----+const PRIORITY_LABEL: Record<number, string> = { 0: 'Low', 1: 'Normal', 2: 'High' };+type BadgeColor = 'success' | 'brand' | 'warning';+const PRIORITY_COLOR: Record<number, BadgeColor> = { 0: 'success', 1: 'brand', 2: 'warning' };++// ---- Column configuration ----+interface ColumnDef {+ key: StatusValue;+ label: string;+ icon: React.ReactNode;+ accent: BadgeColor;+}+const COLUMNS: ColumnDef[] = [+ { key: TO_DO, label: 'To Do', icon: <ClipboardTaskRegular />, accent: 'brand' },+ { key: IN_PROGRESS, label: 'In Progress', icon: <PlayRegular />, accent: 'warning' },+ { key: DONE, label: 'Done', icon: <CheckmarkCircleRegular />, accent: 'success' },+];++// ---- Window cache (survives module re-evaluation on navigation) ----+let _taskCache: task[] | null = (window as any).__ppTaskCache ?? null;++// ---- Due date formatting ----+function formatDue(date: Date | null | undefined): { text: string; overdue: boolean } | null {+ if (!date) return null;+ const d = new Date(date);+ if (isNaN(d.getTime())) return null;+ const overdue = d < new Date();+ const text = d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+ return { text: overdue ? `${text} (overdue)` : text, overdue };+}++// ---- Styles ----+const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ paddingInline: tokens.spacingHorizontalL,+ paddingBlock: tokens.spacingVerticalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ overflowY: 'hidden',+ },+ pageHeader: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ flexShrink: 0,+ },+ board: {+ display: 'grid',+ gridTemplateColumns: 'repeat(3, minmax(260px, 1fr))',+ gap: tokens.spacingHorizontalM,+ flex: 1,+ overflowX: 'auto',+ overflowY: 'hidden',+ minHeight: 0,+ },+ column: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXS,+ paddingInline: tokens.spacingHorizontalS,+ paddingBlock: tokens.spacingVerticalS,+ backgroundColor: tokens.colorNeutralBackground2,+ borderRadius: tokens.borderRadiusMedium,+ minHeight: 0,+ transitionProperty: 'background-color',+ transitionDuration: tokens.durationNormal,+ },+ columnOver: {+ backgroundColor: tokens.colorBrandBackground2,+ outlineWidth: '2px',+ outlineStyle: 'dashed',+ outlineColor: tokens.colorBrandStroke1,+ outlineOffset: '-2px',+ },+ columnHeader: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalXS,+ paddingBlockEnd: tokens.spacingVerticalXS,+ flexShrink: 0,+ },+ columnBody: {+ flex: 1,+ overflowY: 'auto',+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXS,+ minHeight: 0,+ paddingBlockEnd: tokens.spacingVerticalXS,+ },+ card: {+ cursor: 'grab',+ transitionProperty: 'opacity',+ transitionDuration: tokens.durationNormal,+ ':active': { cursor: 'grabbing' },+ },+ cardDragging: { opacity: 0.45 },+ cardBody: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalXXS,+ paddingInline: tokens.spacingHorizontalM,+ paddingBlockEnd: tokens.spacingVerticalS,+ },+ cardMeta: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: tokens.spacingHorizontalXS,+ flexWrap: 'wrap',+ },+ dueNormal: { color: tokens.colorNeutralForeground3 },+ dueOverdue: { color: tokens.colorPaletteRedForeground1, fontWeight: tokens.fontWeightSemibold },+ emptyHint: {+ color: tokens.colorNeutralForeground3,+ fontStyle: 'italic',+ textAlign: 'center',+ paddingBlock: tokens.spacingVerticalL,+ },+ dropError: { flexShrink: 0 },+ spinnerWrap: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '200px',+ },+});++// ---- Task card sub-component ----++interface TaskCardProps {+ item: task;+ dragging: boolean;+ onDragStart: (e: React.DragEvent<HTMLDivElement>, id: string) => void;+ onDragEnd: () => void;+}++const TaskCard = ({ item, dragging, onDragStart, onDragEnd }: TaskCardProps) => {+ const styles = useStyles();+ const priority = item.prioritycode as unknown as number;+ const label = PRIORITY_LABEL[priority] ?? 'Normal';+ const color: BadgeColor = PRIORITY_COLOR[priority] ?? 'brand';+ const due = formatDue(item.scheduledend);++ return (+ <Card+ className={mergeClasses(styles.card, dragging && styles.cardDragging)}+ draggable+ onDragStart={(e) => onDragStart(e, item.activityid)}+ onDragEnd={onDragEnd}+ aria-grabbed={dragging}+ aria-label={`Task: ${item.subject}`}+ >+ <CardHeader header={<Body1 weight="semibold">{item.subject}</Body1>} />+ <div className={styles.cardBody}>+ <div className={styles.cardMeta}>+ <Badge appearance="tint" color={color} size="small">+ {label}+ </Badge>+ {due && (+ <Caption1 className={due.overdue ? styles.dueOverdue : styles.dueNormal}>+ {due.text}+ </Caption1>+ )}+ </div>+ </div>+ </Card>+ );+};++// ---- Main component ----++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput;+ const styles = useStyles();++ const [{ tasks, loading, error }, setData] = useState<{+ tasks: task[];+ loading: boolean;+ error: string | null;+ }>({+ tasks: _taskCache ?? [],+ loading: _taskCache === null,+ error: null,+ });++ // Drag/hover state is intentionally separate — these are pure UI, not data state+ const [draggingId, setDraggingId] = useState<string | null>(null);+ const [hoverCol, setHoverCol] = useState<StatusValue | null>(null);+ const [dropError, setDropError] = useState<string | null>(null);++ useEffect(() => {+ if (!dataApi || _taskCache !== null) return;+ (async () => {+ try {+ const result = await dataApi.queryTable('task', {+ select: ['activityid', 'subject', 'statuscode', 'prioritycode', 'scheduledend'],+ orderBy: 'createdon asc',+ pageSize: 200,+ });+ _taskCache = result.rows as unknown as task[];+ (window as any).__ppTaskCache = _taskCache;+ setData({ tasks: _taskCache, loading: false, error: null });+ } catch (err) {+ setData({+ tasks: [],+ loading: false,+ error: err instanceof Error ? err.message : 'Failed to load tasks.',+ });+ }+ })();+ }, [dataApi]);++ const handleDragStart = (e: React.DragEvent<HTMLDivElement>, taskId: string) => {+ e.dataTransfer.effectAllowed = 'move';+ e.dataTransfer.setData('text/plain', taskId);+ setDraggingId(taskId);+ };++ const handleDragEnd = () => {+ setDraggingId(null);+ setHoverCol(null);+ };++ const handleDragOver = (e: React.DragEvent<HTMLDivElement>, colKey: StatusValue) => {+ e.preventDefault();+ e.dataTransfer.dropEffect = 'move';+ if (hoverCol !== colKey) setHoverCol(colKey);+ };++ const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node)) {+ setHoverCol(null);+ }+ };++ const handleDrop = async (e: React.DragEvent<HTMLDivElement>, targetStatus: StatusValue) => {+ e.preventDefault();+ const taskId = e.dataTransfer.getData('text/plain');+ setHoverCol(null);+ setDropError(null);+ if (!taskId) return;++ const current = tasks.find((t) => t.activityid === taskId);+ if (!current) return;+ if ((current.statuscode as unknown as number) === targetStatus) return;++ // Optimistic update+ const nextTasks = tasks.map((t) =>+ t.activityid === taskId+ ? { ...t, statuscode: targetStatus as unknown as typeof t.statuscode }+ : t,+ );+ const prevTasks = tasks;+ _taskCache = nextTasks;+ (window as any).__ppTaskCache = nextTasks;+ setData({ tasks: nextTasks, loading: false, error: null });++ try {+ await dataApi.updateRow('task', taskId, {+ statuscode: targetStatus as unknown as typeof current.statuscode,+ statecode: stateCodeFor(targetStatus) as unknown as typeof current.statecode,+ });+ } catch (err) {+ // Rollback on failure+ _taskCache = prevTasks;+ (window as any).__ppTaskCache = prevTasks;+ setData({ tasks: prevTasks, loading: false, error: null });+ setDropError(+ err instanceof Error ? err.message : 'Failed to update task. Changes reverted.',+ );+ }+ };++ if (loading) {+ return (+ <div className={styles.spinnerWrap}>+ <Spinner label="Loading tasks..." />+ </div>+ );+ }++ if (error) {+ return (+ <MessageBar intent="error">+ <MessageBarBody>{error}</MessageBarBody>+ </MessageBar>+ );+ }++ return (+ <div className={styles.root}>+ <div className={styles.pageHeader}>+ <ClipboardTaskRegular aria-hidden="true" />+ <Text size={500} weight="semibold">Task board</Text>+ <Badge appearance="filled" color="brand">{tasks.length}</Badge>+ </div>++ {dropError && (+ <MessageBar intent="error" className={styles.dropError}>+ <MessageBarBody>{dropError}</MessageBarBody>+ </MessageBar>+ )}++ <div+ className={styles.board}+ role="application"+ aria-label="Task management board"+ >+ {COLUMNS.map((col) => {+ const items = tasks.filter(+ (t) => (t.statuscode as unknown as number) === col.key,+ );+ const isOver = hoverCol === col.key;++ return (+ <div+ key={col.key}+ className={mergeClasses(styles.column, isOver && styles.columnOver)}+ onDragOver={(e) => handleDragOver(e, col.key)}+ onDragLeave={handleDragLeave}+ onDrop={(e) => handleDrop(e, col.key)}+ aria-label={`${col.label} column, ${items.length} task${items.length !== 1 ? 's' : ''}`}+ aria-dropeffect="move"+ >+ <div className={styles.columnHeader}>+ {col.icon}+ <Body1 weight="semibold">{col.label}</Body1>+ <Badge appearance="filled" color={col.accent} size="small">+ {items.length}+ </Badge>+ </div>++ <div className={styles.columnBody}>+ {items.length === 0 ? (+ <Caption1 className={styles.emptyHint}>+ No tasks — drop one here+ </Caption1>+ ) : (+ items.map((t) => (+ <TaskCard+ key={t.activityid}+ item={t}+ dragging={draggingId === t.activityid}+ onDragStart={handleDragStart}+ onDragEnd={handleDragEnd}+ />+ ))+ )}+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md b/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.mdnew file mode 100644index 000000000..1e0e059af--- /dev/null+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md@@ -0,0 +1,107 @@+# Workflow Log++## Phase 1 — Planning++### Commands Run++`node --version`+v20.18.2++`pac help`+PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8) — version >= 2.7.0 confirmed.++`pac auth list`+Index Active Kind Name User Cloud Type Environment Environment Url+[1] UNIVERSAL [email protected] Public OperatingSystem+[2] UNIVERSAL [email protected] Test User TMSBAPEnv5ee52 https://tmsbapenv5ee52.crmtest.dynamics.com/+[3] * UNIVERSAL [email protected] Test User AuroraBAPEnv610b3 https://aurorabapenv610b3.crmtest.dynamics.com/++AskUserQuestion: "Multiple auth profiles found. Which environment would you like to use?" → [3] [email protected] — AuroraBAPEnv610b3 (currently active)++`pac model list-languages`+Found 1 enabled language(s): English (United States) LCID 1033 — no localization needed.++`pac model list-tables --search 'task'`+Found 5 table(s). Exact match check: task (Logical Name == 'task') → exists as Standard table. Result: task entity EXISTS — no creation needed.++`pac model list-tables`+Found 1728 table(s). Custom prefix analysis (non-system prefixes): mspp=36 (36%), msfp=20 (20%), msdyncrm=18 (18%) — no prefix meets >=50% threshold with >=3 tables. No dominant prefix detected. Fallback: detectedPrefix=none, Solution=Default, Publisher Prefix=new.++`pac model list`+Found 20 model-driven app(s).++AskUserQuestion: "20 model-driven apps found. Which app should the task board page be added to?" → Genpage Publish Test (genpage_publish_test_2761b0b1, App ID: 3fc905b9-7854-f111-a821-70a8a59ce7bc)++AskUserQuestion: "Any specific styling or feature requirements for the task board?" → All of the above (priority color coding, due date display, owner display on cards)++Solution selection: Code-only flow (existing entities + existing app) — skipping solution question. Writing Solution: Default / Publisher Prefix: new.++EnterPlanMode called+User response: approved++### Decisions+- Working environment: AuroraBAPEnv610b3 (https://aurorabapenv610b3.crmtest.dynamics.com/)+- Languages: English (1033) only+- Entity status: task — exists (Standard table), no creation required+- App: Genpage Publish Test (3fc905b9-7854-f111-a821-70a8a59ce7bc)+- Solution: Default / Publisher Prefix: new (code-only flow)+- Pages: 1 (task-board.tsx — Kanban board with native HTML5 DnD)+- Sample referenced: 11-kanban-with-dnd.tsx+- Plan written to: D:/temp/task-board/genpage-plan.md++## Phase 0 — Working directory+- `mkdir -p D:/temp/task-board` → created+- Working directory: `D:/temp/task-board`++## Phase 0.5 — Local-dev manifest+- Command: `node ".../generate-page-manifest.js" "D:/temp/task-board" task-board`+- Result: wrote `package.json` and `genpage.d.ts` (no extra features — no charts/datepicker/timepicker needed)++## Phase 2 — Entities+Skipped — `task` Standard entity confirmed to exist in AuroraBAPEnv610b3.++## Phase 3 — App selection+Existing app: Genpage Publish Test (`3fc905b9-7854-f111-a821-70a8a59ce7bc`). `pac model create` not invoked.++## Phase 4 — RuntimeTypes+- Command: `pac model genpage generate-types --data-sources "task" --output-file "D:/temp/task-board/RuntimeTypes.ts"`+- Result: success — `D:/temp/task-board/RuntimeTypes.ts` written+- Critical finding: planner's statuscode mapping was incorrect. RuntimeTypes shows:+ - `"Not Started" = 2` → To Do column (planner said 1)+ - `"In Progress" = 3` → In Progress column (planner said 2)+ - `"Completed" = 5` → Done column (correct)+ - Priority: Low=0, Normal=1, High=2 — no "Critical" (planner's plan was wrong)+ - `ownerid` not in schema — excluded from select++## Phase 5 — Build (single-page fast path)+- Read `references/rules.md`+- Read `samples/11-kanban-with-dnd.tsx`+- Read `references/data-caching.md` (Needs caching: true)+- Wrote `D:/temp/task-board/task-board.tsx`+- Icon verification: ClipboardTaskRegular (line 1163), PlayRegular (line 3394), CheckmarkCircleRegular (line 1013) — all verified.+- Key implementation decisions:+ - Status mapping corrected to actual RuntimeTypes values: TO_DO=2, IN_PROGRESS=3, DONE=5+ - `statecode` also updated on drop (0=Open for columns 2/3, 1=Completed for column 5) — Dataverse business rule+ - Module-level `_taskCache` initialized from `window.__ppTaskCache` (list page caching pattern)+ - Single batched `{ tasks, loading, error }` state object — no intermediate renders+ - `shorthands` imported; used `outlineWidth`/`outlineStyle`/`outlineColor` separately in `columnOver` to avoid Griffel shorthand errors+ - Native HTML5 drag-and-drop: onDragStart, onDragOver+preventDefault, onDrop, onDragEnd, onDragLeave+ - `mergeClasses` for conditional card/column class application (no template literal concatenation)++## Phase 6 — Deploy+- Command: `pac model genpage upload --app-id 3fc905b9-7854-f111-a821-70a8a59ce7bc --code-file D:/temp/task-board/task-board.tsx --name "Task board" --data-sources "task" --prompt "Build a task management board with columns for To Do, In Progress, and Done. Use the task entity. Allow dragging tasks between columns." --model "claude-opus-4-7" --agent-message "Kanban board with 3 columns (To Do=statuscode 2, In Progress=3, Done=5). Native HTML5 DnD; drop persists statuscode+statecode via dataApi.updateRow with optimistic UI and rollback. Window cache __ppTaskCache. Priority badges (Low/Normal/High) and scheduledend due date on each card." --add-to-sitemap`+- Result: page-id = `e2a6f1e4-89b1-41b5-b75a-ab90b7267eac`, status = success (transpilation OK, project published, added to sitemap)+- `add-table-to-app.js`: script not present in this plugin version — step skipped.++## Phase 7 — Browser verification+AskUserQuestion: "Would you like to verify the task board in the browser using Playwright?" → **Skip verification**++## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| Task board | task-board.tsx | task | Deployed (page-id `e2a6f1e4-89b1-41b5-b75a-ab90b7267eac`) |++- App: Genpage Publish Test (`3fc905b9-7854-f111-a821-70a8a59ce7bc`)+- Entities created: none+- Browser verification: skippeddiff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/entity-creation-log.md b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/entity-creation-log.mdnew file mode 100644index 000000000..e1976a075--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/entity-creation-log.md@@ -0,0 +1,50 @@+# Entity Creation Log++## Environment+- URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- Solution: Default+- Publisher Prefix: cr++## Created Tables++### Job Requisition+- Schema Name: cr_JobRequisition+- Resolved Full Name: cr_jobrequisition+- Metadata ID: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee++### Candidate+- Schema Name: cr_Candidate+- Resolved Full Name: cr_candidate+- Metadata ID: 11111111-2222-3333-4444-555555555555++## Created Columns++| Table | Display Name | Schema Name | Resolved Full Name | Metadata ID |+|-------|--------------|-------------|--------------------|-------------|+| cr_jobrequisition | Department | cr_Department | cr_department | ... |+| cr_jobrequisition | Openings | cr_Openings | cr_openings | ... |+| cr_candidate | Status | cr_Status | cr_status | ... |+| cr_candidate | Interview Score | cr_InterviewScore | cr_interviewscore | ... |+| cr_candidate | Recruiter | cr_Recruiter | cr_recruiter | ... |++## Created Relationships++| Type | From | To | Lookup Schema Name | Resolved Full Name |+|------|------|-----|--------------------|--------------------|+| 1:N | cr_jobrequisition | cr_candidate | cr_JobRequisition | cr_jobrequisition |++## Commands++```powershell+node check-auth.js # ok: true+node create-table.js https://... cr_JobRequisition "Job Requisition" "Job Requisitions" --primary-name "Title" --primary-name-logical cr_title --solution Default+node add-column.js https://... cr_jobrequisition cr_Department "Department" string --max-length 100 --required-level ApplicationRequired --solution Default+node add-column.js https://... cr_jobrequisition cr_Openings "Openings" integer --min 0 --max 1000 --required-level ApplicationRequired --solution Default+node create-table.js https://... cr_Candidate "Candidate" "Candidates" --primary-name "Name" --primary-name-logical cr_name --solution Default+node add-column.js https://... cr_candidate cr_Status "Status" picklist --options "[{\"value\":100000000,\"label\":\"Applied\"},...]" --required-level ApplicationRequired --solution Default+node add-column.js https://... cr_candidate cr_InterviewScore "Interview Score" integer --min 0 --max 100 --solution Default+node add-column.js https://... cr_candidate cr_Recruiter "Recruiter" string --max-length 100 --solution Default+node create-relationship.js https://... 1n --from cr_jobrequisition --to cr_candidate --lookup cr_JobRequisition "Job Requisition" --solution Default+node create-record.js https://... cr_jobrequisition '[...2 records...]' --solution Default+node create-record.js https://... cr_candidate '[...8 records...]' --solution Default+```diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.md b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.mdnew file mode 100644index 000000000..6792d20b4--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/genpage-plan.md@@ -0,0 +1,92 @@+# Genpage Plan++## User Requirements++Build a page showing all job candidates with their application status,+interview scores, and assigned recruiter. New tables cr_candidate and+cr_jobrequisition are required. Include sample data.++## Working Directory++job-candidates/++## Plugin Root++D:\Projects\power-platform-skills\plugins\model-apps++## Environment++- Active Profile: [email protected]+- Environment URL: https://aurorabapenv4ab3f.crm10.dynamics.com/+- App: Recruitment Hub (33333333-2222-3333-4444-555555555555)+- Solution: Default+- Publisher Prefix: cr++## Pages++| Page | File | Purpose | Entities |+|------|------|---------|----------|+| Candidates | page.tsx | List of candidates with status, interview score, recruiter, requisition link | cr_candidate, cr_jobrequisition |++## Entity Creation Required++### jobrequisition++- Display Name: Job Requisition+- Display Plural: Job Requisitions+- Primary Name Suffix: title+- Columns:++ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | department | string | yes | Department owning the requisition |+ | openings | int | yes | Number of openings (>=0) |++### candidate++- Display Name: Candidate+- Display Plural: Candidates+- Primary Name Suffix: name+- Columns:++ | Suffix | Type | Required | Notes |+ |--------|------|----------|-------|+ | interviewscore | int | yes | Interview score 0-100 |+ | recruiter | string | yes | Assigned recruiter display name |+- Choice Columns:++ | Column Suffix | Options |+ |---------------|---------|+ | status | applied (100000000), interviewing (100000001), offered (100000002), hired (100000003) |+- Relationships:++ | Type | Related Table | Lookup Suffix | Cascade |+ |------|---------------|---------------|---------|+ | 1:N | jobrequisition | jobrequisition | Restrict |++## Existing Entities++None.++## Design Preferences++- DataGrid layout, sortable, resizable columns+- Status shown as Badge+- Lookup field shows FormattedValue (Job Requisition title)+- Realistic sample data (not lorem ipsum)++## Relevant Samples++- plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list + window cache)++## Per-Page Specifications++### Candidates++- File: page.tsx+- Entities: cr_candidate (primary), cr_jobrequisition (lookup target)+- Fetch on mount with window cache `__genpage_candidates_v1`+- Columns: cr_name, cr_status (FormattedValue), cr_interviewscore, cr_recruiter, _cr_jobrequisition_value (FormattedValue)+- DataGrid uses createTableColumn from @fluentui/react-components + columnSizingOptions + resizableColumns+- Icons: PeopleRegular, BriefcaseRegular (unsized)+- Sample data: 2 requisitions, 8 candidates with realistic names and varied statusesdiff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/page.tsx b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/page.tsxnew file mode 100644index 000000000..d0396bab9--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/page.tsx@@ -0,0 +1,188 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ DataGrid,+ DataGridHeader,+ DataGridHeaderCell,+ DataGridBody,+ DataGridRow,+ DataGridCell,+ TableCellLayout,+ createTableColumn,+ Spinner,+ MessageBar,+ MessageBarBody,+ Text,+ Badge,+} from '@fluentui/react-components';+import {+ PeopleRegular,+ BriefcaseRegular,+} from '@fluentui/react-icons';+import { GeneratedComponentProps, CrCandidate } from './RuntimeTypes';++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ padding: tokens.spacingHorizontalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ grid: { flex: 1, overflowY: 'auto' },+});++interface DisplayRow {+ id: string;+ name: string;+ status: string;+ score: number;+ recruiter: string;+ requisition: string;+}++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // list page+ const styles = useStyles();+ const [rows, setRows] = React.useState<DisplayRow[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);++ React.useEffect(() => {+ (async () => {+ const cacheKey = '__genpage_candidates_v1';+ const w = window as unknown as Record<string, DisplayRow[] | undefined>;+ if (w[cacheKey]) {+ setRows(w[cacheKey] as DisplayRow[]);+ setLoading(false);+ return;+ }+ try {+ // queryTable returns DataTable<T> with .rows — never iterate the result directly+ const result = await dataApi.queryTable<CrCandidate>('cr_candidate', {+ select: [+ 'cr_candidateid',+ 'cr_name',+ 'cr_status',+ 'cr_interviewscore',+ 'cr_recruiter',+ '_cr_jobrequisition_value',+ ],+ expand: { '_cr_jobrequisition_value': { select: ['cr_title'] } },+ top: 200,+ });+ const mapped: DisplayRow[] = result.rows.map((r: any) => ({+ id: r.cr_candidateid,+ name: r.cr_name ?? '',+ status: r['[email protected]'] ?? '',+ score: r.cr_interviewscore ?? 0,+ recruiter: r.cr_recruiter ?? '',+ requisition:+ r['_cr_jobrequisition_value@OData.Community.Display.V1.FormattedValue'] ?? '',+ }));+ w[cacheKey] = mapped;+ setRows(mapped);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi]);++ const columns = React.useMemo(+ () => [+ createTableColumn<DisplayRow>({+ columnId: 'name',+ renderHeaderCell: () => 'Candidate',+ renderCell: (item) => (+ <TableCellLayout media={<PeopleRegular />}>{item.name}</TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: 'status',+ renderHeaderCell: () => 'Status',+ renderCell: (item) => (+ <TableCellLayout>+ <Badge appearance="filled" color="brand">{item.status || 'Unknown'}</Badge>+ </TableCellLayout>+ ),+ }),+ createTableColumn<DisplayRow>({+ columnId: 'score',+ renderHeaderCell: () => 'Score',+ renderCell: (item) => <TableCellLayout>{item.score}</TableCellLayout>,+ }),+ createTableColumn<DisplayRow>({+ columnId: 'recruiter',+ renderHeaderCell: () => 'Recruiter',+ renderCell: (item) => <TableCellLayout>{item.recruiter}</TableCellLayout>,+ }),+ createTableColumn<DisplayRow>({+ columnId: 'requisition',+ renderHeaderCell: () => 'Requisition',+ renderCell: (item) => (+ <TableCellLayout media={<BriefcaseRegular />}>{item.requisition}</TableCellLayout>+ ),+ }),+ ],+ [],+ );++ if (loading) return <Spinner label="Loading candidates..." />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root}>+ <div className={styles.header}>+ <PeopleRegular />+ <Text size={500} weight="semibold">Candidates ({rows.length})</Text>+ </div>+ <div className={styles.grid}>+ <DataGrid+ items={rows}+ columns={columns}+ resizableColumns+ columnSizingOptions={{+ name: { defaultWidth: 200, minWidth: 120 },+ status: { defaultWidth: 120, minWidth: 80 },+ score: { defaultWidth: 80, minWidth: 60 },+ recruiter: { defaultWidth: 160, minWidth: 100 },+ requisition: { defaultWidth: 240, minWidth: 140 },+ }}+ sortable+ aria-label="Candidate list"+ >+ <DataGridHeader>+ <DataGridRow>+ {({ renderHeaderCell }) => (+ <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>+ )}+ </DataGridRow>+ </DataGridHeader>+ <DataGridBody<DisplayRow>>+ {({ item, rowId }) => (+ <DataGridRow<DisplayRow> key={rowId}>+ {({ renderCell }) => (+ <DataGridCell>{renderCell(item)}</DataGridCell>+ )}+ </DataGridRow>+ )}+ </DataGridBody>+ </DataGrid>+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.mdnew file mode 100644index 000000000..b6db82a9f--- /dev/null+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md@@ -0,0 +1,91 @@+# Workflow Log — Eval 7: Job candidates with new entities++## Phase 0 — Working directory setup+- Working directory created: `job-candidates/`+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`++## Phase 1 — Planner (genpage-planner agent invoked via Task)++### Prereq checks+- `node --version` → v20.11.0+- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)++### Auth check+- `pac auth list` → active profile [email protected]+- Active environment: https://aurorabapenv4ab3f.crm10.dynamics.com/ (reported to user)++### Entity discovery+- `pac model list-tables --search 'cr_candidate'` — exact logical-name match: NOT FOUND+- `pac model list-tables --search 'cr_jobrequisition'` — exact logical-name match: NOT FOUND++### Discovery questions (AskUserQuestion)+- Question 1 (new or edit): user answered "Create new page(s)"+- Question 2 (data source): user answered "Dataverse entities: cr_candidate, cr_jobrequisition (new entities to create)"+- Question 3 (specific requirements): "Candidate list with status, interview scores, assigned recruiter"+- Question 4 (sample data): user answered "Yes, add sample data"+- Question 5 (app selection): user selected existing app "Recruitment Hub"++### Solution selection+- Build needs metadata work (new entities) → solution selection question asked+- AskUserQuestion solution selection question presented+- `node dataverse-request.js https://aurorabapenv4ab3f.crm10.dynamics.com /solutions` to enumerate existing solutions+- dominant prefix detection: env shows mixed prefixes — no dominant prefix flagged+- User selected: "Use Default Solution"+- Recorded in plan: `Solution: Default`, `Publisher Prefix: cr`++### Plan presented+- EnterPlanMode called; user approved plan++### Plan written+- genpage-plan.md written; conforms to references/plan-schema.md+- ## Entity Creation Required has 2 entities with suffix-only names (jobrequisition, candidate)++## Phase 2a — Pre-flight auth check+- node ${CLAUDE_PLUGIN_ROOT}/scripts/check-auth.js → returned `{ ok: true, ... }`+- Identity match between pac and az verified++## Phase 2b — Entity Builder (genpage-entity-builder agent invoked via Task)+- Reads Solution=Default, Publisher Prefix=cr from plan ## Environment+- Created cr_jobrequisition first (independent table, no lookups)+ - node create-table.js https://... cr_jobrequisition "Job Requisition" "Job Requisitions" --primary-name "Title" --primary-name-logical cr_title --solution Default+ - 4 second propagation delay observed+ - node add-column.js https://... cr_jobrequisition cr_department "Department" string --max-length 100 --solution Default+ - node add-column.js https://... cr_jobrequisition cr_openings "Openings" integer --min 0 --max 1000 --solution Default+- Created cr_candidate second (has lookup to cr_jobrequisition)+ - node create-table.js https://... cr_candidate "Candidate" "Candidates" --primary-name "Name" --primary-name-logical cr_name --solution Default+ - 4 second propagation delay observed+ - node add-column.js https://... cr_candidate cr_status "Status" picklist --options '[{"value":100000000,"label":"Applied"},{"value":100000001,"label":"Interviewing"},{"value":100000002,"label":"Offered"},{"value":100000003,"label":"Hired"}]' --solution Default+ - node add-column.js https://... cr_candidate cr_interviewscore "Interview Score" integer --min 0 --max 100 --solution Default+ - node add-column.js https://... cr_candidate cr_recruiter "Recruiter" string --max-length 100 --solution Default+ - node create-relationship.js https://... 1n --from cr_jobrequisition --to cr_candidate --lookup cr_jobrequisition "Job Requisition" --solution Default+ - 8 second propagation delay observed before sample data insert++### Sample data+- User confirmed via AskUserQuestion: yes add sample data+- node create-record.js https://... cr_jobrequisition '[{ "cr_title": "Senior Engineer", "cr_department": "Engineering", "cr_openings": 2 }, { "cr_title": "Product Designer", "cr_department": "Design", "cr_openings": 1 }]' — OData $batch round-trip+- node create-record.js https://... cr_candidate '[{ "cr_name": "Alice Chen", "cr_status": 100000001, "cr_interviewscore": 87, "cr_recruiter": "Marcus Wei", "[email protected]": "/cr_jobrequisitions(<id>)" }, ... 7 more records ]' — $batch+- Transaction log written to job-candidates/entity-creation-log.md++## Phase 3 — App creation+- SKIPPED (existing app "Recruitment Hub" selected)++## Phase 4 — Schema generation+- pac model genpage generate-types --data-sources 'cr_candidate,cr_jobrequisition' --output-file job-candidates/RuntimeTypes.ts++## Phase 5b — Single-page fast path+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched)+- Data mode: dataverse+- Read sample: plugins/model-apps/samples/9-list-with-caching.tsx (Dataverse list + window cache)+- Read ${CLAUDE_PLUGIN_ROOT}/references/verified-icons.txt+- Wrote page.tsx+- Post-write icon verification: grep `from "@fluentui/react-icons"` in page.tsx; verified `PeopleRegular`, `BriefcaseRegular` against verified-icons.txt — all present++## Phase 6 — Deployment+- pac model genpage upload --app-id 33333333-2222-3333-4444-555555555555 --code-file job-candidates/page.tsx --data-sources 'cr_candidate,cr_jobrequisition' --prompt "Build a page showing all job candidates with their application status, interview scores, and assigned recruiter. I need new tables for this — cr_candidate and cr_jobrequisition entities don't exist yet in my environment." --model claude-sonnet --name "Candidates" --agent-message "Candidate list with status, scores, and recruiter assignments" --add-to-sitemap+- Upload succeeded++## Phase 8 — Summary+- 1 page deployed: page.tsx → "Candidates" in Recruitment Hub+- 2 entities created: cr_jobrequisition, cr_candidate+- 1 lookup: cr_candidate → cr_jobrequisition+- Sample data inserted (2 requisitions, 8 candidates)diff --git a/evals/model-apps/genpage/fixtures/README.md b/evals/model-apps/genpage/fixtures/README.mdnew file mode 100644index 000000000..fad6df835--- /dev/null+++ b/evals/model-apps/genpage/fixtures/README.md@@ -0,0 +1,111 @@+# Layer 2 fixtures++Each subdirectory is a fixture for one eval in `../evals.json`. The Layer 2+runner (`../run-layer-2.js`) grades every `.tsx` in a fixture against the+`common_code_assertions` and the eval's `Phase 5 (Page Builder):` /+`Phase 5b:` expectations.++## Layout++```+fixtures/+ 2-mock-dashboard/ ← fixture for eval id 2+ dashboard.tsx ← generated page output+ 7-jobs-list/ ← fixture for eval id 7+ candidates.tsx+ job-requisitions.tsx+ 11-recruitment-app/ ← multi-page fixture for eval id 11+ candidate-list.tsx+ interview-schedule.tsx+ hiring-metrics.tsx+```++**Folder name format:** `<eval-id>` or `<eval-id>-<kebab-slug>`. The leading+digits are parsed as the eval id; the slug is purely cosmetic.++**Included files:**+- All `.tsx` files in the fixture root are checked.+- A file literally named `RuntimeTypes.ts` (or `.tsx`) is excluded — it's+ schema, not generated output.+- `workflow-log.md`, `genpage-plan.md`, `entity-creation-log.md` are ignored+ by Layer 2 (Layer 1 will read them).++## How to capture a real fixture from /genpage++The plugin ships a capture helper that copies the right files (excluding+local-dev scaffolding) and runs both layers immediately:++```bash+node plugins/model-apps/scripts/capture-fixture.js \+ --working-dir /path/to/genpage/working-dir \+ --eval <id> \+ --slug <kebab-slug>+```++The script:+- Copies `*.tsx`, `*.md` files, and `RuntimeTypes.ts` into+ `fixtures/<eval-id>-<slug>/`+- **Skips** `package.json` and `genpage.d.ts` (Phase 0.5 scaffolding that+ the agent didn't produce), `node_modules/`, `dist/`, `*.log`, OS noise+- Runs Layer 1 and Layer 2 against the new fixture+- Prints a JSON summary with copied files + pass/fail counts + the specific+ failing assertions for triage++Flags:+- `--force` — overwrite an existing fixture (use when re-capturing after+ agent changes)+- `--skip-verify` — capture only, skip the runner sweep (rare)++Manual fallback if the helper doesn't fit your scenario:++1. `mkdir evals/model-apps/genpage/fixtures/<eval-id>-<slug>/`+2. Copy in `*.tsx`, `*.md`, `RuntimeTypes.ts` from the working dir+3. Skip `package.json`, `genpage.d.ts`, `node_modules/`, `*.log`+4. Run `node ../run-layer-1.js --eval <id>` and `../run-layer-2.js --eval <id>`++## How to regenerate fixtures++When the page-builder rules change, expected outputs change too. Bulk+regeneration:++1. Run all evals against the new agent.+2. Replace fixture contents wholesale (no incremental diffs — the agent+ may legitimately restructure the file).+3. Run `node run-layer-2.js` and confirm all fixtures pass.+4. Commit the regeneration as a single PR titled+ `Regenerate Layer 2 fixtures for <rule version>`.++## Current state++This directory ships with 10 fixtures — 6 synthetic (hand-built, v2.2-compliant)+and 4 real captures (3 from claude-sonnet-4-6 sessions under the v2.2 plugin):++| Fixture | Eval | Source | State | Shape covered |+|---------|-----:|--------|-------|---------------|+| `1-account-card-gallery/` | 1 | Synthetic | green | Dataverse single page, click-to-open Xrm.Navigation, window cache |+| `2-mock-dashboard/` | 2 | Synthetic (from sample 8) | green | Mock data, D3 charts, no entity work |+| `2-mock-dashboard-real/` | 2 | Real capture (2026-05-20, pre-v2.2-spec) | red | Mock data — pre-spec-tightening capture; known workflow-log compactness gaps |+| `4-case-wizard/` | 4 | Synthetic | green | Multi-step wizard, two Dataverse entities, dataApi.createRow with @odata.bind |+| `5-kanban-task-board/` | 5 | Real capture (2026-05-21, pre-v2.2-spec) | mostly green | Native HTML5 DnD on `task` entity — Layer 2 fully green; Layer 1 pre-spec workflow-log gaps |+| `7-job-candidates-new-entities/` | 7 | Synthetic | green | New entities + lookup + choice column + sample data + solution selection |+| `11-recruitment-multi-page/` | 11 | Synthetic | green | Multi-page (3 pages), parallel page-builder dispatch, PAGEREF cross-nav, Phase 6.5 resolution |+| `11-recruitment-pages-real/` | 11 | Real capture (2026-05-21, v2.2-spec) | **green** | Same shape as synthetic — first real capture validated under tightened spec |+| `13-contact-localization/` | 13 | Synthetic | green | Localization (en-US / ar-SA / fr-FR), RTL, logical CSS properties |+| `15-support-tickets-real/` | 15 | Real capture (2026-05-26, v2.2-spec) | **green** | New entity + choice columns + sample data + check-auth retry flow |++**Synthetic fixtures** are hand-built to be v2.2-compliant — they exercise+the relevant code paths and serve as green-path regression tests for the+runners. All Layer 1 + Layer 2 assertions pass or skip.++**Real captures** validate the runners against actual `/genpage` output:++- The two **green real captures** (eval 11, eval 15) were captured after the+ v2.2 planner-spec tightening landed. Both layers exit 0 against them.+- The two **red real captures** (eval 2, eval 5) were captured before the+ spec tightening propagated to the agent's session. They have known+ workflow-log compactness gaps documented in their fixture READMEs; they+ go green when re-captured under the tightened spec.++The mix gives a green-path regression test (synthetic) + a drift-detection+example (red real captures) + proof-of-life that the v2.2 spec produces+green output (green real captures).diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.jsnew file mode 100644index 000000000..e65884f3d--- /dev/null+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js@@ -0,0 +1,689 @@+// Maps each natural-language workflow assertion in evals.json to a check+// function. Each check receives { fixture, eval } and returns { status, reason }.+//+// fixture: { id, dir, files, workflowLog, genpagePlan, genpageEditPlan,+// entityCreationLog }+// eval: the eval entry from evals.json+//+// status: "pass" | "fail" | "skip"+//+// The runner applies every entry in `common_workflow_assertions` first, then+// each per-eval `expectations` entry whose text starts with "Phase " or+// "Edit Phase " or "Prefix discipline ".++'use strict';++function fail(reason) { return { status: 'fail', reason }; }+function pass() { return { status: 'pass', reason: '' }; }+function skip(reason) { return { status: 'skip', reason }; }++function logHas(log, pattern) {+ return Boolean(log) && new RegExp(pattern, 'mi').test(log);+}++function planSection(plan, heading) {+ // Returns text under "## <heading>" up to the next "## " heading or end-of-file.+ // Implemented as line scan to avoid JS regex \Z limitation.+ if (!plan) return null;+ const lines = plan.split('\n');+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const startRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'i');+ let i = 0;+ while (i < lines.length && !startRe.test(lines[i])) i++;+ if (i >= lines.length) return null;+ i++; // skip the heading line+ const out = [];+ while (i < lines.length && !/^##\s/.test(lines[i])) {+ out.push(lines[i]);+ i++;+ }+ return out.join('\n').trim();+}++function entitiesNeedCreating(plan) {+ const section = planSection(plan, 'Entity Creation Required');+ if (!section) return false;+ return !/No entity creation required/i.test(section);+}++function newAppNeeded(plan) {+ if (!plan) return false;+ // Accept canonical phrasing and the shorter "App: create new:" form the+ // planner spec uses in the ## Environment section.+ return /create new app|new app will be created|create-app|^[\s-]*App:\s*create new/im.test(plan);+}++// True if the workflow log records that the planner actually asked the solution+// selection question (not skipped). Distinguishes "solution selection question+// SKIPPED" (false) from "solution selection question asked" / AskUserQuestion+// referencing solution (true).+function solutionQuestionAsked(log) {+ if (!log) return false;+ if (/solution\s+selection[^\n]*SKIPPED|skipped\s+(the\s+)?solution\s+selection|solution\s+question\s+SKIPPED/i.test(log)) {+ return false;+ }+ return /AskUserQuestion[^\n]*solution/i.test(log) ||+ /solution\s+selection\s+question\s+asked|asked[^\n]*solution\s+selection/i.test(log);+}++// Iterate all regex matches without using RegExp.prototype.exec by name+function allMatches(pattern, text) {+ return [...text.matchAll(new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g'))];+}++const WORKFLOW_ASSERTIONS = new Map();++WORKFLOW_ASSERTIONS.set(+ 'A workflow-log.md file is saved to the working directory documenting all phases attempted',+ ({ fixture }) => {+ if (!fixture.workflowLog) return fail('workflow-log.md not present in fixture');+ if (fixture.workflowLog.trim().length < 50) {+ return fail(`workflow-log.md too short (${fixture.workflowLog.trim().length} chars)`);+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 0: A working directory is created with a kebab-case name derived from the user\'s description',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/Phase\s*0\b/i.test(log)) return fail('workflow-log lacks a "Phase 0" entry');+ if (!/working[\s-]?dir(ectory)?/i.test(log)) return fail('no mention of working directory in Phase 0');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/node\s+--version/.test(log)) return fail('workflow-log does not record `node --version`');+ if (!/\bpac\s+help\b/.test(log)) return fail('workflow-log does not record `pac help`');+ if (/node\s+--version\s*&&\s*pac\s+help/.test(log)) {+ return fail('node --version and pac help are chained with && (forbidden)');+ }+ if (!/2\.\s*7|>=\s*2\.7|version\s+\d+\.\d+/i.test(log)) {+ return fail('no PAC CLI version verification recorded');+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): pac auth list is run and the active environment is identified and reported to the user',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+auth\s+list/.test(log)) return fail('workflow-log does not record `pac auth list`');+ // Accept several legitimate signals that the active env was reported:+ // - "active environment" / "active env" / "active profile" (synthetic style)+ // - "currently active" (real `pac auth list` output)+ // - "active": flag in JSON-like output+ // - Any Dataverse env URL near the pac auth list output (real captures+ // contain the table-rendered URL but not the literal word "environment")+ const reportsEnv =+ /active\s+(environment|env|profile)/i.test(log) ||+ /currently\s+active/i.test(log) ||+ /environment[:\s]+https?:\/\//i.test(log) ||+ /https?:\/\/[a-z0-9-]+\.(crm|dynamics)/i.test(log);+ if (!reportsEnv) return fail('workflow-log does not report active environment');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/AskUserQuestion/.test(log)) return fail('workflow-log does not record any AskUserQuestion call');+ // The planner spec allows the "new vs edit" question to be inferred+ // from $ARGUMENTS when the prompt clearly states a new page. Accept any of:+ // - explicit question recorded+ // - "Create new page" / "new page(s)" decision recorded+ // - "edit existing" decision recorded+ // - "inferred: new" / "implied: new"+ // - presence of a Pages section in the plan (implies new-page flow)+ if (+ /new\s+or\s+edit/i.test(log) ||+ /create new page/i.test(log) ||+ /\bnew page\(s\)/i.test(log) ||+ /edit existing/i.test(log) ||+ /(inferred|implied)[:\s]+new/i.test(log) ||+ /^##\s+Pages\b/im.test(fixture.genpagePlan || '')+ ) return pass();+ return fail('workflow-log does not record the new-or-edit determination');+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows',+ ({ fixture }) => {+ const plan = fixture.genpagePlan;+ if (!plan) return fail('genpage-plan.md not present in fixture');+ const env = planSection(plan, 'Environment');+ if (!env) return fail('plan has no "## Environment" section');+ // Allow optional list markers (`- Solution:`, `* Solution:`) and leading whitespace+ if (!/^\s*[-*]?\s*Solution:\s*\S/m.test(env)) return fail('## Environment missing "Solution:" line');+ if (!/^\s*[-*]?\s*Publisher Prefix:\s*\S/m.test(env)) return fail('## Environment missing "Publisher Prefix:" line');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ const plan = fixture.genpagePlan;+ if (!log) return fail('no workflow-log.md');+ if (!plan) return fail('no genpage-plan.md');+ const needsMetadata = entitiesNeedCreating(plan) || newAppNeeded(plan);+ const asked = solutionQuestionAsked(log);+ if (needsMetadata && !asked) return fail('metadata work required but solution question not asked');+ if (!needsMetadata && asked) return fail('code-only flow asked solution question (should be skipped)');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): When the solution question runs, the planner queries /solutions via dataverse-request.js and presents options (existing custom solutions, \'Create new genpage-<app> solution\', \'Use Default Solution\')',+ ({ fixture }) => {+ 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.+ if (+ !/dataverse-request\.js[^\n]*\/solutions|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)');+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): The plan is presented via EnterPlanMode and user approval is requested',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/EnterPlanMode/.test(log)) return fail('workflow-log does not record EnterPlanMode');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md',+ ({ fixture }) => {+ if (!fixture.genpagePlan) return fail('genpage-plan.md not present in fixture');+ const required = [+ '# Genpage Plan',+ '## User Requirements',+ '## Working Directory',+ '## Plugin Root',+ '## Environment',+ '## Pages',+ ];+ const missing = required.filter((h) => !fixture.genpagePlan.includes(h));+ if (missing.length > 0) return fail(`plan missing heading(s): ${missing.join(', ')}`);+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked; on ok:false the orchestrator surfaces the message to the user and halts',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ const plan = fixture.genpagePlan;+ if (!log) return fail('no workflow-log.md');+ if (!plan) return fail('no genpage-plan.md');+ if (!entitiesNeedCreating(plan)) return skip('no entity creation required');+ if (!/check-auth\.js/.test(log)) return fail('check-auth.js not invoked');+ // Order against the FIRST actual entity-creation script invocation, not+ // against a meta-list mention of the entity-builder agent name. Meta-lists+ // like "## Agents Invoked" can name the agent before the actual commands.+ const idxCheck = log.search(/check-auth\.js/);+ const idxFirstScript = log.search(/\b(create-table\.js|add-column\.js|create-relationship\.js|create-record\.js)\b/);+ if (idxFirstScript !== -1 && idxFirstScript < idxCheck) {+ return fail('entity creation script invoked before check-auth.js');+ }+ if (!/(?:^|\s|"|,|{)ok\s*[:=]\s*"?true"?/i.test(log)) {+ return fail('check-auth.js did not return ok:true (or not logged)');+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Phase 6 / 6.5 / 7.5 / Edit Phase 6 (--prompt scoping): The FIRST pac model genpage upload for each new page passes --prompt with the FULL page description (from plan\'s ## User Requirements). EVERY SUBSEQUENT upload of an existing page (--page-id, no --add-to-sitemap) passes --prompt scoped to ONLY the delta of changes in that upload — never the full original description',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+genpage\s+upload/.test(log)) return fail('no upload invocation recorded');+ if (!/--prompt/.test(log)) return fail('upload lacks --prompt flag');+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.',+ ({ fixture }) => {+ const plan = fixture.genpagePlan;+ if (!plan) return fail('no genpage-plan.md');+ const section = planSection(plan, 'Entity Creation Required');+ if (!section || /No entity creation required/i.test(section)) return skip('no entity creation');+ const lines = section.split('\n').filter((l) => /^\|/.test(l));+ const offenders = [];+ for (const line of lines) {+ if (/^\|\s*-/.test(line) || /Suffix|Column|Type|Cardinality|Heading/.test(line)) continue;+ const cells = line.split('|').map((c) => c.trim()).filter(Boolean);+ for (const c of cells) {+ if (/^[a-z][a-z0-9_]+$/.test(c) && c.includes('_')) offenders.push(c);+ }+ }+ if (offenders.length > 0) {+ return fail(`prefix drift in ## Entity Creation Required: ${offenders.slice(0,3).join(', ')}${offenders.length>3?'...':''}`);+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).',+ ({ fixture }) => {+ const plan = fixture.genpagePlan;+ const log = fixture.entityCreationLog;+ if (!plan) return skip('no genpage-plan.md');+ if (!log) return skip('no entity-creation-log.md');+ const env = planSection(plan, 'Environment');+ if (!env) return fail('plan has no ## Environment section');+ // Allow optional list markers (`- Publisher Prefix: new` or `* Publisher Prefix: new`).+ const prefixMatch = env.match(/^\s*[-*]?\s*Publisher Prefix:\s*(\S+)/m);+ if (!prefixMatch) return fail('plan ## Environment missing Publisher Prefix');+ const prefix = prefixMatch[1].trim().toLowerCase();+ const matches = allMatches(/(?:Resolved Full Name|Logical Name|Schema Name):\s*([a-z][a-z0-9_]+)/gi, log);+ const offenders = [];+ for (const m of matches) {+ const name = m[1].toLowerCase();+ if (!name.includes('_')) continue;+ if (!name.startsWith(prefix + '_')) offenders.push(name);+ }+ if (offenders.length > 0) {+ return fail(`names not prefixed with "${prefix}_": ${offenders.slice(0,3).join(', ')}${offenders.length>3?'...':''}`);+ }+ return pass();+ }+);++WORKFLOW_ASSERTIONS.set(+ 'Prefix discipline — solution alignment: If the env has a dominant non-system custom prefix (>=50% of custom tables AND >=3 such tables), the planner surfaces this in the solution question and ordered the option whose publisher prefix matches the dominant prefix FIRST as the recommended choice. If the user picks a different-prefix solution, the planner logged a one-line warning before proceeding.',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!solutionQuestionAsked(log)) return skip('solution question not asked');+ if (!/dominant\s+prefix|prefix\s+alignment|env(ironment)?\s+publishers/i.test(log)) {+ return fail('solution question recorded but no dominant-prefix detection mentioned');+ }+ return pass();+ }+);++const PHASE_EXPECTATIONS = new Map();++PHASE_EXPECTATIONS.set(+ 'Phase 1 (Planner): pac model list-tables --search \'account\' is run and results are filtered by exact logical-name match',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+list-tables/.test(log)) return fail('pac model list-tables not invoked');+ if (!/--search/.test(log)) return fail('list-tables invoked without --search');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 1 (Planner): Account entity is detected as existing; plan records no entity creation required',+ ({ fixture }) => {+ const plan = fixture.genpagePlan;+ if (!plan) return fail('no genpage-plan.md');+ const section = planSection(plan, 'Entity Creation Required');+ if (!section) return fail('plan missing ## Entity Creation Required');+ if (!/No entity creation required/i.test(section)) {+ return fail('plan does not record "No entity creation required"');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2: Entity-builder is SKIPPED (no entities to create)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (/genpage-entity-builder\s+invoked|entity-builder\s+invoked|Task.*entity-builder/i.test(log)) {+ return fail('entity-builder was invoked (should be skipped)');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2: Entity-builder is SKIPPED (mock data)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (/genpage-entity-builder\s+invoked|entity-builder\s+invoked|Task.*entity-builder/i.test(log)) {+ return fail('entity-builder was invoked on a mock-data eval');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 4: RuntimeTypes generation is SKIPPED (mock data)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ // Match an actual invocation (generate-types followed by a --flag), not+ // descriptive prose like "generate-types not run".+ if (/generate-types\s+--/.test(log)) return fail('generate-types invoked on mock-data eval');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 4: pac model genpage generate-types --data-sources \'account\' --output-file <working-dir>/RuntimeTypes.ts is run',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/generate-types\s+--/.test(log)) return fail('generate-types not invoked');+ if (!/--data-sources\s+['"]?account['"]?/.test(log)) {+ return fail('generate-types missing --data-sources account');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): genpage-page-builder is invoked with Data mode: mock',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/genpage-page-builder/.test(log) && !/Phase\s*5b?/.test(log)) {+ return fail('no page-builder invocation recorded');+ }+ if (!/Data mode[:\s]+mock|mock\s+data/i.test(log)) return fail('Data mode: mock not recorded');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (/Task[^\n]*genpage-page-builder/i.test(log)) {+ return fail('Task subagent dispatched (fast path should inline)');+ }+ if (!/Phase\s*5b|single[-\s]page\s+fast\s+path|inlined|inline\s+build/i.test(log)) {+ return fail('fast path not recorded');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5c (multi-page): Three genpage-page-builder agents are invoked via Task tool in a SINGLE message (parallel execution, not sequential). The single-page fast path (5b) is NOT taken because N>1.',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ // Accept singular "page-builder" and plural "page-builders".+ if (!/(3|three)\s+(page-builders?|builders|genpage-page-builders?|Task)/i.test(log)) {+ return fail('multi-page parallel dispatch not recorded');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 6: pac model genpage upload includes --app-id, --code-file, --data-sources \'account\', --prompt, --model, --name, --agent-message, --add-to-sitemap',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ const required = ['--app-id', '--code-file', '--data-sources', '--prompt', '--model', '--name', '--agent-message', '--add-to-sitemap'];+ const missing = required.filter((flag) => !log.includes(flag));+ if (missing.length > 0) return fail(`upload missing flags: ${missing.join(', ')}`);+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 6: Deployment omits --data-sources flag (mock data page)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+genpage\s+upload/.test(log)) return fail('upload command not recorded');+ const uploadLines = log.split('\n').filter((l) => /pac\s+model\s+genpage\s+upload/.test(l));+ if (uploadLines.some((l) => /--data-sources/.test(l))) {+ return fail('upload includes --data-sources on mock-data page');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 6: Upload omits --data-sources flag',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+genpage\s+upload/.test(log)) return fail('upload command not recorded');+ const uploadLines = log.split('\n').filter((l) => /pac\s+model\s+genpage\s+upload/.test(l));+ if (uploadLines.some((l) => /--data-sources/.test(l))) {+ return fail('upload includes --data-sources on mock-data page');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 6: --prompt value is the FULL page description (from plan\'s ## User Requirements) — this is the create-step prompt, NOT a delta',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/--prompt/.test(log)) return fail('upload missing --prompt');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5b: Orchestrator reads ${CLAUDE_PLUGIN_ROOT}/references/verified-icons.txt before writing the .tsx',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/verified-icons\.txt/.test(log)) return fail('verified-icons.txt not read');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5b: A relevant sample file is read (e.g., 7-responsive-cards.tsx for card layout)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/samples?\/[\w-]+\.tsx/i.test(log)) return fail('no sample file read recorded');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names',+ () => skip('column-name verification needs schema cross-check')+);++PHASE_EXPECTATIONS.set(+ 'Phase 5b: After writing, orchestrator greps the .tsx for `from "@fluentui/react-icons"` imports and verifies each named import against verified-icons.txt — rewrites if any are missing',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/grep[^\n]*react-icons|verify[^\n]*icons|verified[\s-]*icons[^\n]*check/i.test(log)) {+ return fail('icon verification step not recorded');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 1 (Planner): User indicates \'edit existing\'; planner returns { action: \'edit\' }, skipping Phases 2-8 of the create flow',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/action[:\s]+['"]?edit['"]?|edit\s+flow|Edit\s+Phase/i.test(log)) {+ return fail('edit flow not recorded');+ }+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 1a: pac model list is run to discover available apps — orchestrator does NOT guess or invent app names',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+list\b/.test(log)) return fail('pac model list not invoked');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 2: pac model genpage download produces <working-dir>/<page-id>/ with page.tsx, page.js, config.json, prompt.txt',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+genpage\s+download/.test(log)) return fail('pac model genpage download not invoked');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 4: genpage-edit-planner agent is invoked via Task tool',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/genpage-edit-planner/.test(log)) return fail('edit-planner not invoked');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 5: Orchestrator applies edits inline using Edit tool on <working-dir>/<page-id>/page.tsx',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/Edit\s+tool|Edit\s+applied|inline\s+edit/i.test(log)) return fail('inline Edit application not recorded');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 6: pac model genpage upload uses --page-id flag; omits --add-to-sitemap',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ const uploadLines = log.split('\n').filter((l) => /pac\s+model\s+genpage\s+upload/.test(l));+ if (uploadLines.length === 0) return fail('upload not recorded');+ const editUpload = uploadLines.find((l) => /--page-id/.test(l));+ if (!editUpload) return fail('edit upload missing --page-id');+ if (/--add-to-sitemap/.test(editUpload)) return fail('edit upload includes --add-to-sitemap');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Edit Phase 6: --prompt value is the user\'s edit request (the DELTA of changes — \'Add a search bar and column sorting by company name\'), NOT a re-statement of the original page description',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/--prompt/.test(log)) return fail('edit upload missing --prompt');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2a: Orchestrator runs scripts/check-auth.js; ok:true gate before invoking entity-builder',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/check-auth\.js/.test(log)) return fail('check-auth.js not invoked');+ if (!/ok:\s*true|"ok":\s*true/.test(log)) return fail('check-auth.js did not return ok:true');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2b (Entity Builder): Every create-table.js / add-column.js / create-relationship.js call passes --solution <name> (always — \'Default\' is a valid value, never omitted)',+ ({ fixture }) => {+ const log = fixture.entityCreationLog || fixture.workflowLog;+ if (!log) return fail('no entity-creation-log.md or workflow-log.md');+ const matches = allMatches(/(create-table\.js|add-column\.js|create-relationship\.js)([^\n]*)/g, log);+ const offenders = [];+ for (const m of matches) {+ if (!/--solution\b/.test(m[2])) offenders.push(m[1]);+ }+ if (offenders.length > 0) return fail(`${offenders.length} call(s) missing --solution: ${offenders.slice(0,3).join(', ')}`);+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 3: pac model create --name \'Account Metrics\' --solution \'<Solution from plan>\' is run; --solution is ALWAYS passed (pac model create errors out without it)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/pac\s+model\s+create/.test(log)) return fail('pac model create not invoked');+ if (!/pac\s+model\s+create[^\n]*--solution/.test(log)) return fail('pac model create missing --solution');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2a: If the script returns blocker:\'az_not_logged_in\', orchestrator surfaces the message (\'Run `az login`...\') to the user and halts (entity-builder is NOT invoked)',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ if (!/blocker[:\s]+['"]?az_not_logged_in['"]?/i.test(log)) {+ return skip('az_not_logged_in blocker not in scenario');+ }+ if (/genpage-entity-builder\s+invoked/i.test(log)) {+ return fail('entity-builder invoked despite az_not_logged_in blocker');+ }+ if (!/halt|halted|stopped|abort/i.test(log)) return fail('orchestrator did not halt after blocker');+ return pass();+ }+);++PHASE_EXPECTATIONS.set(+ 'Phase 2b: genpage-entity-builder is only invoked AFTER check-auth returns ok:true',+ ({ fixture }) => {+ const log = fixture.workflowLog;+ if (!log) return fail('no workflow-log.md');+ const idxCheck = log.search(/check-auth\.js/);+ const idxBuilder = log.search(/genpage-entity-builder\s+invoked|entity-builder\s+invoked/i);+ if (idxBuilder === -1) return skip('entity-builder not invoked');+ if (idxCheck === -1) return fail('entity-builder invoked but check-auth.js never ran');+ if (idxBuilder < idxCheck) return fail('entity-builder invoked before check-auth.js');+ return pass();+ }+);++module.exports = {+ WORKFLOW_ASSERTIONS,+ PHASE_EXPECTATIONS,+ planSection,+ entitiesNeedCreating,+ newAppNeeded,+ logHas,+};diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.jsnew file mode 100644index 000000000..c2bef212d--- /dev/null+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js@@ -0,0 +1,539 @@+// Maps each natural-language assertion in evals.json to a check function.+// Each check receives { files, eval } and returns { status, reason }.+//+// files: array of { path, name, content } objects (every .tsx in the fixture,+// excluding RuntimeTypes.ts)+// eval: the eval entry from evals.json (has id, tier, prompt, data, expectations)+//+// status is one of:+// "pass" verified+// "fail" violated; reason explains+// "skip" not applicable or not implementable yet+//+// To add a new assertion: append to ASSERTIONS keyed by exact text from evals.json.++'use strict';++const path = require('node:path');+const fs = require('node:fs');++let _verifiedIcons = null;+function getVerifiedIcons() {+ if (_verifiedIcons) return _verifiedIcons;+ const iconsPath = path.join(+ __dirname,+ '..', '..', '..', '..',+ 'plugins', 'model-apps', 'references', 'verified-icons.txt'+ );+ const text = fs.readFileSync(iconsPath, 'utf8');+ _verifiedIcons = new Set(+ text.split('\n').map((s) => s.trim()).filter(Boolean)+ );+ return _verifiedIcons;+}++function setVerifiedIcons(set) {+ _verifiedIcons = set;+}++// Strip line and block comments so regex checks for forbidden patterns don't+// trip on rule-documentation in JSDoc/inline comments. Approximate — doesn't+// parse strings, so `"// not a comment"` is stripped too. Acceptable for+// regex-grep semantics; precise comment handling needs a real parser.+function stripComments(content) {+ // Remove block comments first (greedy with non-greedy inner)+ let out = content.replace(/\/\*[\s\S]*?\*\//g, '');+ // Then line comments+ out = out.replace(/\/\/.*$/gm, '');+ return out;+}++function isDataverseFile(content) {+ return /from\s+['"]\.\/RuntimeTypes['"]/.test(content);+}++function isMockFile(content) {+ return !isDataverseFile(content);+}++function violatingFile(files, predicate) {+ return files.find((f) => predicate(f.content));+}++function extractIconImports(content) {+ const re = /import\s*\{([^}]+)\}\s*from\s*['"]@fluentui\/react-icons['"]/g;+ const names = [];+ let m;+ while ((m = re.exec(content)) !== null) {+ const list = m[1].split(',').map((s) => s.trim()).filter(Boolean);+ for (const item of list) {+ const base = item.split(/\s+as\s+/)[0].trim();+ if (base) names.push(base);+ }+ }+ return names;+}++function fail(reason) { return { status: 'fail', reason }; }+function pass() { return { status: 'pass', reason: '' }; }+function skip(reason) { return { status: 'skip', reason }; }++const ASSERTIONS = new Map();++ASSERTIONS.set(+ 'Generated .tsx is a single file with `export default GeneratedComponent`',+ ({ files }) => {+ const offender = violatingFile(files, (c) => !/^\s*export\s+default\s+GeneratedComponent\b/m.test(c));+ return offender ? fail(`${offender.name}: missing 'export default GeneratedComponent'`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx destructures props including `pageInput` (e.g., `const { dataApi, pageInput } = props;`)',+ ({ files }) => {+ const offender = violatingFile(files, (c) => !/const\s*\{[^}]*\bpageInput\b[^}]*\}\s*=\s*props/.test(c));+ return offender ? fail(`${offender.name}: does not destructure pageInput from props`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx imports types from `./RuntimeTypes` (for Dataverse pages) or uses realistic inline mock data (for mock pages)',+ ({ files }) => {+ const offender = files.find((f) => {+ if (isDataverseFile(f.content)) return false;+ const hasObjectArray = /\[\s*\{[\s\S]*?\}\s*,\s*\{/.test(f.content);+ return !hasObjectArray;+ });+ return offender ? fail(`${offender.name}: neither imports ./RuntimeTypes nor contains inline mock array`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx uses `makeStyles` with tokens for styling — no inline styles for static values',+ ({ files }) => {+ const offender = violatingFile(files, (c) => !/\bmakeStyles\b/.test(c));+ return offender ? fail(`${offender.name}: makeStyles not used`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx nests `@media` queries inside `makeStyles` slots — no media query used as a top-level slot key',+ ({ files }) => {+ // A media query used as a top-level makeStyles key "reaches into" named+ // slots — i.e. its object's first entry is `slotName: { ... }`. Griffel+ // compiles that as an unused class (overrides never apply) and it fails+ // type-checking. A correctly nested media query (inside a slot) only sets+ // flat CSS property:value pairs, so it never matches `<ident>: {`.+ // Heuristic regex, matching the rest of this file's grep-style checks.+ const topLevelMedia = /@media[^{}]*\{\s*[A-Za-z_$][\w$]*\s*:\s*\{/;+ const offender = violatingFile(files, (c) => topLevelMedia.test(stripComments(c)));+ return offender+ ? fail(`${offender.name}: @media used as a top-level makeStyles key — nest it inside the slot it modifies`)+ : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx does NOT use `100vh` or `100vw`',+ ({ files }) => {+ const offender = violatingFile(files, (c) => /\b100v[hw]\b/.test(stripComments(c)));+ return offender ? fail(`${offender.name}: contains 100vh or 100vw`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx does NOT import `createTheme`, `mergeThemes`, or `useTheme` (these do not exist in Fluent UI V9)',+ ({ files }) => {+ const offender = violatingFile(files, (c) => /\b(createTheme|mergeThemes|useTheme)\b/.test(stripComments(c)));+ return offender ? fail(`${offender.name}: imports forbidden theme function`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx does NOT wrap content in a top-level `<FluentProvider>` (already provided at root)',+ ({ files }) => {+ const offender = violatingFile(files, (c) => /<FluentProvider\b/.test(stripComments(c)));+ return offender ? fail(`${offender.name}: wraps content in <FluentProvider>`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx does NOT use React Router or construct raw URLs / manipulate `window.location` for navigation',+ ({ files }) => {+ const offender = violatingFile(files, (c) => {+ const stripped = stripComments(c);+ return /\bwindow\.location\b/.test(stripped) || /from\s+['"]react-router/.test(stripped) || /pagetype=/i.test(stripped);+ });+ return offender ? fail(`${offender.name}: uses forbidden navigation mechanism`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx uses `Xrm.Navigation.navigateTo` for any in-app navigation',+ ({ files }) => {+ const navIntentFiles = files.filter((f) =>+ /\b(Xrm\.Navigation|openRecord|openForm|navigateTo|openWebResource)\b/.test(stripComments(f.content)));+ if (navIntentFiles.length === 0) return skip('no navigation intent detected');+ // Accept any form of the Xrm Navigation API surface — the rule is about+ // using `Navigation.navigateTo` as the navigation mechanism (vs raw URLs+ // or React Router). The regex matches all defensible forms:+ // Xrm.Navigation.navigateTo (canonical)+ // Xrm?.Navigation?.navigateTo (defensive)+ // xrm.Navigation.navigateTo (aliased — e.g. const xrm = (window as any).Xrm)+ // xrm?.Navigation?.navigateTo (aliased + defensive)+ // The accompanying nav-intent filter already excludes non-Xrm libraries+ // (react-router, window.location, raw URLs), so a `.Navigation.navigateTo`+ // call here is by definition the Xrm API.+ const offender = navIntentFiles.find((f) => {+ const stripped = stripComments(f.content);+ return !/\bNavigation\s*\??\s*\.\s*navigateTo\b/.test(stripped);+ });+ return offender ? fail(`${offender.name}: nav intent but does not use Xrm.Navigation.navigateTo`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx uses Fluent UI icons in unsized form (e.g., `AddRegular`, not `Add24Regular`)',+ ({ files }) => {+ const sizedRe = /\b[A-Z][A-Za-z0-9]*(?:12|16|20|24|28|32|48)(?:Regular|Filled|Light)\b/;+ const offender = violatingFile(files, (c) => sizedRe.test(stripComments(c)));+ if (!offender) return pass();+ const match = stripComments(offender.content).match(sizedRe);+ return fail(`${offender.name}: contains sized icon ${match[0]}`);+ }+);++ASSERTIONS.set(+ 'Every named import from `@fluentui/react-icons` in the generated .tsx appears in references/verified-icons.txt — no hallucinated icon names',+ ({ files }) => {+ const verified = getVerifiedIcons();+ for (const f of files) {+ const imports = extractIconImports(f.content);+ const missing = imports.filter((n) => !verified.has(n));+ if (missing.length > 0) {+ return fail(`${f.name}: ${missing.length} unverified icon(s): ${missing.slice(0,3).join(', ')}${missing.length>3?'...':''}`);+ }+ }+ return pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx wraps async `dataApi` calls in try-catch (Dataverse pages only)',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ const offender = dv.find((f) => {+ const hasAwait = /await\s+(?:this\.)?(?:props\.)?dataApi\./.test(f.content);+ if (!hasAwait) return false;+ return !/\btry\s*\{[\s\S]*?\}\s*catch\b/.test(f.content);+ });+ return offender ? fail(`${offender.name}: awaits dataApi but lacks try/catch`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies',+ ({ files }) => {+ const offender = files.find((f) => {+ if (/\b(TODO|FIXME)\b/.test(f.content)) return true;+ if (/\/\/\s*\.\.\./.test(f.content)) return true;+ if (/\/\*\s*\.\.\.\s*\*\//.test(f.content)) return true;+ if (/^\s*\.\.\.\s*(\/\/.*)?$/m.test(f.content)) return true;+ return false;+ });+ return offender ? fail(`${offender.name}: contains TODO/FIXME or ellipsis placeholder`) : pass();+ }+);++ASSERTIONS.set(+ 'Generated .tsx for lookup display names uses `@OData.Community.Display.V1.FormattedValue` annotations, not lookup-name fields in $select',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ const offender = dv.find((f) => {+ const hasLookupSelect = /\$select=[^"'`]*_[a-z][a-z0-9_]*_value/.test(f.content);+ if (!hasLookupSelect) return false;+ return !/FormattedValue/.test(f.content);+ });+ return offender ? fail(`${offender.name}: lookup _value in $select without FormattedValue`) : pass();+ }+);++ASSERTIONS.set(+ 'For DataGrids, generated .tsx imports `createTableColumn` from `@fluentui/react-components` and configures column sizing (columnSizingOptions or resizableColumns)',+ ({ files }) => {+ const gridFiles = files.filter((f) => /<DataGrid\b/.test(f.content));+ if (gridFiles.length === 0) return skip('no <DataGrid> usage');+ const offender = gridFiles.find((f) => {+ const importsCTC = /import\s*\{[^}]*\bcreateTableColumn\b[^}]*\}\s*from\s*['"]@fluentui\/react-components['"]/.test(f.content);+ const sizingCfg = /\b(columnSizingOptions|resizableColumns)\b/.test(f.content);+ return !(importsCTC && sizingCfg);+ });+ return offender ? fail(`${offender.name}: DataGrid usage missing createTableColumn or column sizing`) : pass();+ }+);++ASSERTIONS.set(+ 'For Dataverse pages with fetching, separate setState calls inside async callbacks are batched into a single setData(...) call (Rule 14)',+ () => skip('Rule 14 batched-setState requires AST analysis')+);++ASSERTIONS.set(+ 'For Dataverse list/detail pages, the inline IIFE + window cache + cache-guard pattern from references/data-caching.md is used (Rule 15); no useCallback for data-fetching functions',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ // Trigger only on files that READ data — queryTable / retrieveMultipleRecords+ // / retrieveRow (the read ops). Write-only pages (createRow/updateRow/+ // deleteRow only, e.g., save-on-completion game pages) aren't list/detail+ // pages and shouldn't be expected to follow the cache pattern.+ const fetching = dv.filter((f) =>+ /dataApi\.(queryTable|retrieveMultipleRecords|retrieveRow|retrieve\b)/.test(f.content)+ );+ if (fetching.length === 0) return skip('no read operations (queryTable/retrieveRow) detected');+ const offender = fetching.find((f) => {+ // Accept any of the canonical window-cache patterns:+ // window.__foo = ... (direct dunderscore)+ // window as unknown as Record<...> (typed cast — see sample 9)+ // window as any (loose cast — common in real captures)+ // (window as any).__foo (paren-cast property access)+ // window[CACHE_KEY] = ... (bracket access)+ const hasCache =+ /\bwindow\s*\.\s*__\w+/.test(f.content) ||+ /\bwindow\s+as\s+(unknown|any)\b/.test(f.content) ||+ /\bwindow\s*\[/.test(f.content);+ const usesCallback = /useCallback\s*\(\s*async/.test(f.content);+ return !hasCache || usesCallback;+ });+ return offender ? fail(`${offender.name}: missing window cache or uses useCallback for fetch`) : pass();+ }+);++ASSERTIONS.set(+ 'For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs',+ ({ files }) => {+ if (files.length <= 1) return skip('single-page fixture');+ const hasPageref = files.some((f) => /["']PAGEREF_[a-zA-Z0-9_-]+["']/.test(f.content));+ const hasNav = files.some((f) => /Xrm\.Navigation\.navigateTo/.test(f.content));+ if (hasNav && !hasPageref) {+ return fail('multi-page fixture has navigation calls but no "PAGEREF_<name>" placeholders');+ }+ return pass();+ }+);++ASSERTIONS.set(+ 'For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ const queryFiles = dv.filter((f) => /\bdataApi\.queryTable\b/.test(f.content));+ if (queryFiles.length === 0) return skip('no queryTable usage');+ // Each file that calls queryTable must access .rows somewhere — that's+ // the only safe way to get the records array out of DataTable<T>. Files+ // that iterate `result` / `data` / etc. directly as if it were an array+ // will fail at runtime with "X.map is not a function".+ const offender = queryFiles.find((f) => !/\.rows\b/.test(stripComments(f.content)));+ return offender+ ? fail(`${offender.name}: dataApi.queryTable result must be accessed via .rows (it is a DataTable<T>, not an array)`)+ : pass();+ }+);++const PHASE5_EXPECTATIONS = new Map();++PHASE5_EXPECTATIONS.set(+ 'Phase 5b: Generated .tsx uses only column names verified from RuntimeTypes.ts — no guessed names',+ () => skip('column-name verification requires RuntimeTypes.ts fixture')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx includes realistic mock data (not empty arrays or identical values)',+ ({ files }) => {+ const mock = files.filter((f) => isMockFile(f.content));+ if (mock.length === 0) return skip('no mock files');+ const offender = mock.find((f) => !/\[\s*\{[\s\S]*?\}\s*,\s*\{/.test(f.content));+ return offender ? fail(`${offender.name}: no realistic mock data array`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Chart uses D3.js exclusively — no Chart.js, Recharts, or other libraries. D3 code uses group() not nest()',+ ({ files }) => {+ const offender = files.find((f) =>+ /from\s+['"](chart\.js|recharts|chartjs|victory|nivo|@nivo|@chartjs)/.test(f.content) ||+ /\bd3\.nest\s*\(/.test(f.content)+ );+ return offender ? fail(`${offender.name}: forbidden chart library or d3.nest()`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): DatePicker (if used) is imported from @fluentui/react-datepicker-compat, not @fluentui/react-components',+ ({ files }) => {+ const offender = files.find((f) =>+ /import\s*\{[^}]*\bDatePicker\b[^}]*\}\s*from\s*['"]@fluentui\/react-components['"]/.test(f.content)+ );+ return offender ? fail(`${offender.name}: DatePicker imported from react-components`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Charts use D3.js exclusively — no Chart.js, Recharts, or other chart libraries',+ ({ files }) => {+ const offender = files.find((f) =>+ /from\s+['"](chart\.js|recharts|chartjs|victory|nivo|@nivo|@chartjs)/.test(f.content));+ return offender ? fail(`${offender.name}: forbidden chart library`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Mock data is realistic (not empty arrays, not identical values)',+ ({ files }) => {+ const mock = files.filter((f) => isMockFile(f.content));+ if (mock.length === 0) return skip('no mock files');+ const offender = mock.find((f) => !/\[\s*\{[\s\S]*?\}\s*,\s*\{/.test(f.content));+ return offender ? fail(`${offender.name}: no realistic mock data array`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Drag-and-drop uses native HTML5 events (onDragStart, onDragOver, onDrop) — no external DnD library',+ ({ files }) => {+ const offender = files.find((f) =>+ /from\s+['"](react-dnd|react-beautiful-dnd|@dnd-kit)/.test(f.content));+ return offender ? fail(`${offender.name}: forbidden DnD library`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): All form fields have aria-labels or aria-labelledby for accessibility',+ () => skip('aria-label coverage requires AST analysis')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): RTL support is included (dir attribute set based on language.isRtl) because Arabic is a detected RTL language',+ ({ files }) => {+ const offender = files.find((f) => !/\bisRtl\b|dir\s*[:=]\s*["']?(rtl|ltr)/.test(f.content));+ return offender ? fail(`${offender.name}: no RTL handling`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx uses logical CSS properties (marginInlineStart/End, paddingInlineStart/End) instead of physical (marginLeft/Right)',+ ({ files }) => {+ const offender = files.find((f) => /\b(marginLeft|marginRight|paddingLeft|paddingRight)\b/.test(f.content));+ return offender ? fail(`${offender.name}: uses physical CSS properties`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx has a translations dictionary with entries for en-US, ar-SA, and fr-FR',+ ({ files }) => {+ const offender = files.find((f) => !/en-US/.test(f.content) || !/ar-SA/.test(f.content) || !/fr-FR/.test(f.content));+ return offender ? fail(`${offender.name}: missing en-US/ar-SA/fr-FR entries`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx includes language detection boilerplate using Xrm.Utility.getGlobalContext().userSettings.languageId',+ ({ files }) => {+ const offender = files.find((f) => !/Xrm\.Utility\.getGlobalContext\s*\(\s*\)\.userSettings\.languageId/.test(f.content));+ return offender ? fail(`${offender.name}: missing Xrm.Utility.getGlobalContext().userSettings.languageId`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): All user-visible text goes through a translate() helper — no hardcoded display strings in JSX',+ () => skip('translate() coverage requires AST analysis')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx uses the choice enum names from RuntimeTypes.ts (not magic numbers)',+ () => skip('choice enum verification requires RuntimeTypes.ts fixture')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated .tsx uses dataApi.getChoices() or reads FormattedValue annotations for choice display names',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ const choiceUsers = dv.filter((f) => /\b(statuscode|statecode)\b/.test(f.content));+ if (choiceUsers.length === 0) return skip('no choice column usage');+ const offender = choiceUsers.find((f) => {+ // Three valid patterns for handling choice display:+ // 1. dataApi.getChoices() (canonical API)+ // 2. @OData.Community.Display.V1.FormattedValue annotation (canonical)+ // 3. Local enum mapping — constants or option arrays keyed off the+ // Dataverse choice value floor (100000000+). The agent verifies+ // these against RuntimeTypes at gen time, so they're safe.+ const hasCanonical = /dataApi\.getChoices|FormattedValue/.test(f.content);+ const hasLocalEnum = /\b1000000\d\d\b/.test(f.content);+ return !hasCanonical && !hasLocalEnum;+ });+ return offender+ ? fail(`${offender.name}: choice columns used without getChoices(), FormattedValue, or a local enum mapping with 100000000+ constants`)+ : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Form uses Fluent UI V9 components (Input, Dropdown, etc.) — not HTML form elements',+ ({ files }) => {+ const offender = files.find((f) => /<(input|select|textarea)(\s|>|\/)/.test(f.content));+ return offender ? fail(`${offender.name}: uses raw HTML <input>/<select>/<textarea>`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Submit uses dataApi.createRow with verified column names from RuntimeTypes.ts',+ ({ files }) => {+ const dv = files.filter((f) => isDataverseFile(f.content));+ if (dv.length === 0) return skip('no Dataverse files');+ const submit = dv.filter((f) => /\b(handleSubmit|onSubmit|onSave)\b/i.test(f.content));+ if (submit.length === 0) return skip('no submit handler');+ const offender = submit.find((f) => !/dataApi\.createRow\b/.test(f.content));+ return offender ? fail(`${offender.name}: submit handler without dataApi.createRow`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): All components and utilities are separate top-level functions (no nested function definitions)',+ () => skip('nested function detection requires AST analysis')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated code uses ONLY verified column names from RuntimeTypes.ts',+ () => skip('column-name verification requires RuntimeTypes.ts fixture')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Generated code has no unnecessary complexity matching the \'clean and minimal\' request',+ () => skip('subjective; defer to Layer 3 UX rubric')+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Code uses entity logical name \'task\' (singular lowercase) not \'tasks\'',+ ({ files }) => {+ const offender = files.find((f) => /['"]tasks['"]/.test(f.content));+ return offender ? fail(`${offender.name}: uses 'tasks' instead of 'task'`) : pass();+ }+);++PHASE5_EXPECTATIONS.set(+ 'Phase 5 (Page Builder): Status update on drop uses dataApi.updateRow with the correct status enum value',+ ({ files }) => {+ const offender = files.find((f) => /\bonDrop\b/.test(f.content) && !/dataApi\.updateRow/.test(f.content));+ return offender ? fail(`${offender.name}: onDrop without dataApi.updateRow`) : pass();+ }+);++module.exports = {+ ASSERTIONS,+ PHASE5_EXPECTATIONS,+ setVerifiedIcons,+ extractIconImports,+ isDataverseFile,+ isMockFile,+};diff --git a/evals/model-apps/genpage/lib/fixture-loader.js b/evals/model-apps/genpage/lib/fixture-loader.jsnew file mode 100644index 000000000..27ff822df--- /dev/null+++ b/evals/model-apps/genpage/lib/fixture-loader.js@@ -0,0 +1,74 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');++// Loads fixtures from a directory. Each subdirectory is one fixture.+// Fixture folder name convention: "<eval-id>-<kebab-slug>" — id is parsed+// from the leading digits before the first hyphen.+//+// fixtures/+// 1-account-gallery/+// page.tsx ← .tsx output (consumed by Layer 2)+// workflow-log.md ← log of agent actions (consumed by Layer 1)+// genpage-plan.md ← plan doc (consumed by Layer 1)+// entity-creation-log.md ← entity-builder transactions (Layer 1)+// 2-mock-dashboard/+// dashboard.tsx+//+// Each fixture exposes:+// id, dirName, dir+// files: [{ path, name, content }] ← every .tsx except RuntimeTypes (Layer 2)+// 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)+// entityCreationLog: string | null ← entity-creation-log.md content (Layer 1)++function loadFixtures(fixturesDir) {+ if (!fs.existsSync(fixturesDir)) {+ throw new Error(`Fixtures directory does not exist: ${fixturesDir}`);+ }+ const entries = fs.readdirSync(fixturesDir, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));++ const fixtures = [];+ for (const entry of entries) {+ const match = entry.name.match(/^(\d+)(?:-(.+))?$/);+ if (!match) continue;+ const id = parseInt(match[1], 10);+ const dir = path.join(fixturesDir, entry.name);+ fixtures.push({+ id,+ dirName: entry.name,+ dir,+ files: listTsxFiles(dir),+ workflowLog: readOptional(dir, 'workflow-log.md'),+ genpagePlan: readOptional(dir, 'genpage-plan.md'),+ genpageEditPlan: readOptional(dir, 'genpage-edit-plan.md'),+ entityCreationLog: readOptional(dir, 'entity-creation-log.md'),+ });+ }+ return fixtures;+}++function listTsxFiles(dir) {+ const out = [];+ for (const name of fs.readdirSync(dir)) {+ if (!name.endsWith('.tsx')) continue;+ if (/^RuntimeTypes\.tsx?$/i.test(name)) continue;+ const full = path.join(dir, name);+ if (!fs.statSync(full).isFile()) continue;+ const content = fs.readFileSync(full, 'utf8');+ out.push({ path: full, name, content });+ }+ return out;+}++function readOptional(dir, fileName) {+ const full = path.join(dir, fileName);+ if (!fs.existsSync(full)) return null;+ return fs.readFileSync(full, 'utf8');+}++module.exports = { loadFixtures, listTsxFiles, readOptional };diff --git a/evals/model-apps/genpage/lib/reporter.js b/evals/model-apps/genpage/lib/reporter.jsnew file mode 100644index 000000000..38c11173c--- /dev/null+++ b/evals/model-apps/genpage/lib/reporter.js@@ -0,0 +1,102 @@+'use strict';++// TAP v13 reporter. One output stream — write line by line.+//+// Structure:+// TAP version 13+// 1..<N total fixtures>+// # Subtest: fixture-1-account-gallery+// 1..<M assertions for this fixture>+// ok 1 - assertion text+// not ok 2 - assertion text+// ---+// reason: '...'+// ...+// ok 3 - assertion text # SKIP not implemented+// ok 1 - fixture-1-account-gallery+// # Subtest: fixture-2-mock-dashboard+// ...+// 1..N+//+// Failure diagnostics currently include only `reason:`. Additional fields+// (e.g., `file:`) can be added by extending `assertion()` if needed.+//+// Aggregate result emitted at the end as `# tests N`, `# pass X`, etc.++class TapReporter {+ constructor(stream = process.stdout) {+ this.stream = stream;+ this.totalTests = 0;+ this.totalPass = 0;+ this.totalFail = 0;+ this.totalSkip = 0;+ this.fixturePass = 0;+ this.fixtureFail = 0;+ this.fixtureIndex = 0;+ this.totalFixtures = 0;+ }++ write(line) { this.stream.write(line + '\n'); }++ start(totalFixtures) {+ this.totalFixtures = totalFixtures;+ this.write('TAP version 13');+ this.write(`1..${totalFixtures}`);+ }++ startFixture(name) {+ this.fixtureIndex += 1;+ this._currentName = name;+ this._currentAssertions = [];+ this._currentFail = false;+ this.write(`# Subtest: ${name}`);+ }++ assertion(text, result) {+ this.totalTests += 1;+ const idx = this._currentAssertions.length + 1;+ this._currentAssertions.push({ text, result });+ if (result.status === 'pass') {+ this.totalPass += 1;+ this.write(` ok ${idx} - ${text}`);+ } else if (result.status === 'skip') {+ this.totalSkip += 1;+ this.write(` ok ${idx} - ${text} # SKIP ${result.reason}`);+ } else {+ this.totalFail += 1;+ this._currentFail = true;+ this.write(` not ok ${idx} - ${text}`);+ this.write(` ---`);+ this.write(` reason: ${JSON.stringify(result.reason)}`);+ this.write(` ...`);+ }+ }++ endFixture() {+ this.write(` 1..${this._currentAssertions.length}`);+ if (this._currentFail) {+ this.fixtureFail += 1;+ this.write(`not ok ${this.fixtureIndex} - ${this._currentName}`);+ } else {+ this.fixturePass += 1;+ this.write(`ok ${this.fixtureIndex} - ${this._currentName}`);+ }+ this._currentName = null;+ this._currentAssertions = [];+ this._currentFail = false;+ }++ end() {+ this.write(`# tests ${this.totalTests}`);+ this.write(`# pass ${this.totalPass}`);+ this.write(`# fail ${this.totalFail}`);+ this.write(`# skip ${this.totalSkip}`);+ this.write(`# fixtures ${this.totalFixtures} (pass ${this.fixturePass}, fail ${this.fixtureFail})`);+ }++ get exitCode() {+ return this.fixtureFail > 0 ? 1 : 0;+ }+}++module.exports = { TapReporter };diff --git a/evals/model-apps/genpage/run-layer-1.js b/evals/model-apps/genpage/run-layer-1.jsnew file mode 100644index 000000000..d1eef6cac--- /dev/null+++ b/evals/model-apps/genpage/run-layer-1.js@@ -0,0 +1,164 @@+#!/usr/bin/env node+'use strict';++// Layer 1 eval runner — grades workflow artifacts (workflow-log.md,+// genpage-plan.md, entity-creation-log.md) against the common_workflow_assertions+// and per-eval Phase/Edit-Phase expectations defined in evals.json. Pure file+// I/O + regex; no Anthropic API, no Dataverse.+//+// Usage:+// node run-layer-1.js [--fixtures <dir>] [--eval <id>] [--tier <tier>]+//+// Defaults:+// --fixtures = ./fixtures (relative to this script)+//+// Exit code:+// 0 — every fixture passed+// 1 — at least one fixture had a failing assertion+// 2 — runner error (missing fixtures dir, malformed evals.json)+//+// Skipped assertions emit `ok # SKIP <reason>` and do not cause failure.++const path = require('node:path');+const fs = require('node:fs');++const { loadFixtures } = require('./lib/fixture-loader.js');+const { TapReporter } = require('./lib/reporter.js');+const {+ WORKFLOW_ASSERTIONS,+ PHASE_EXPECTATIONS,+} = require('./lib/assertions-layer-1.js');++function parseArgs(argv) {+ const args = { fixtures: null, eval: null, tier: null };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--fixtures') args.fixtures = argv[++i];+ else if (a === '--eval') args.eval = parseInt(argv[++i], 10);+ else if (a === '--tier') args.tier = argv[++i];+ else if (a === '--help' || a === '-h') {+ printHelp();+ process.exit(0);+ } else {+ console.error(`Unknown argument: ${a}`);+ process.exit(2);+ }+ }+ return args;+}++function printHelp() {+ console.log(`Usage: run-layer-1.js [options]++Options:+ --fixtures <dir> Directory containing eval fixtures (default: ./fixtures)+ --eval <id> Run only the fixture with this eval id+ --tier <tier> Run only fixtures whose eval matches this tier+ (smoke | full | stress)+ --help Show this message++Fixtures directory layout:+ <fixtures>/+ 2-mock-dashboard/+ dashboard.tsx (consumed by Layer 2)+ workflow-log.md (consumed by Layer 1)+ genpage-plan.md (consumed by Layer 1)+ [entity-creation-log.md] (consumed by Layer 1 when entities created)++Layer 1 reads workflow-log.md / genpage-plan.md / entity-creation-log.md and+greps them for evidence of the assertions in evals.json. Workflow assertions+that need AST analysis or schema cross-check are marked SKIP rather than+guessed.+`);+}++function loadEvals() {+ const file = path.join(__dirname, 'evals.json');+ return JSON.parse(fs.readFileSync(file, 'utf8'));+}++function isPhaseExpectation(text) {+ return /^Phase\s|^Edit Phase\s/.test(text);+}++function main() {+ const args = parseArgs(process.argv.slice(2));+ const fixturesDir = args.fixtures+ ? path.resolve(args.fixtures)+ : path.join(__dirname, 'fixtures');++ let fixtures;+ try {+ fixtures = loadFixtures(fixturesDir);+ } catch (err) {+ console.error(`error: ${err.message}`);+ process.exit(2);+ }++ let evalsData;+ try {+ evalsData = loadEvals();+ } catch (err) {+ console.error(`error: failed to load evals.json: ${err.message}`);+ process.exit(2);+ }+ const evalById = new Map(evalsData.evals.map((e) => [e.id, e]));++ let selected = fixtures;+ if (args.eval !== null) selected = selected.filter((f) => f.id === args.eval);+ if (args.tier) {+ selected = selected.filter((f) => {+ const ev = evalById.get(f.id);+ return ev && ev.tier === args.tier;+ });+ }++ if (selected.length === 0) {+ console.error('error: no fixtures matched the filter');+ process.exit(2);+ }++ const reporter = new TapReporter();+ reporter.start(selected.length);++ for (const fix of selected) {+ reporter.startFixture(fix.dirName);+ const ev = evalById.get(fix.id);+ if (!ev) {+ reporter.assertion(+ `fixture references eval id ${fix.id}`,+ { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` }+ );+ reporter.endFixture();+ continue;+ }++ // common workflow assertions+ for (const assertionText of evalsData.common_workflow_assertions) {+ const check = WORKFLOW_ASSERTIONS.get(assertionText);+ const result = check+ ? check({ fixture: fix, eval: ev })+ : { status: 'skip', reason: 'no check registered for this assertion text' };+ reporter.assertion(assertionText, result);+ }++ // per-eval Phase/Edit Phase expectations+ const phaseExp = ev.expectations.filter(isPhaseExpectation);+ for (const expectationText of phaseExp) {+ const check = PHASE_EXPECTATIONS.get(expectationText);+ const result = check+ ? check({ fixture: fix, eval: ev })+ : { status: 'skip', reason: 'no check registered for this expectation' };+ reporter.assertion(expectationText, result);+ }++ reporter.endFixture();+ }++ reporter.end();+ process.exit(reporter.exitCode);+}++if (require.main === module) main();++module.exports = { main, parseArgs };diff --git a/evals/model-apps/genpage/run-layer-2.js b/evals/model-apps/genpage/run-layer-2.jsnew file mode 100644index 000000000..d5c8a1a57--- /dev/null+++ b/evals/model-apps/genpage/run-layer-2.js@@ -0,0 +1,173 @@+#!/usr/bin/env node+'use strict';++// Layer 2 eval runner — grades generated .tsx fixtures against the+// common_code_assertions and per-eval Phase 5 expectations defined in+// evals.json. Pure file I/O + regex; no Anthropic API, no Dataverse.+//+// Usage:+// node run-layer-2.js [--fixtures <dir>] [--eval <id>] [--tier <smoke|full|stress>]+//+// Defaults:+// --fixtures = ./fixtures (relative to this script)+//+// Exit code:+// 0 — every fixture passed (no failing assertions)+// 1 — at least one fixture had a failing assertion+// 2 — runner error (missing fixtures dir, malformed evals.json, etc.)+//+// Skipped assertions do not cause failure. They are reported as `ok # SKIP`.++const path = require('node:path');+const fs = require('node:fs');++const { loadFixtures } = require('./lib/fixture-loader.js');+const { TapReporter } = require('./lib/reporter.js');+const {+ ASSERTIONS,+ PHASE5_EXPECTATIONS,+} = require('./lib/assertions-layer-2.js');++function parseArgs(argv) {+ const args = { fixtures: null, eval: null, tier: null };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--fixtures') args.fixtures = argv[++i];+ else if (a === '--eval') args.eval = parseInt(argv[++i], 10);+ else if (a === '--tier') args.tier = argv[++i];+ else if (a === '--help' || a === '-h') {+ printHelp();+ process.exit(0);+ } else {+ console.error(`Unknown argument: ${a}`);+ process.exit(2);+ }+ }+ return args;+}++function printHelp() {+ console.log(`Usage: run-layer-2.js [options]++Options:+ --fixtures <dir> Directory containing eval fixtures (default: ./fixtures)+ --eval <id> Run only the fixture with this eval id+ --tier <tier> Run only fixtures whose eval matches this tier+ (smoke | full | stress)+ --help Show this message++Fixtures directory layout:+ <fixtures>/+ 1-account-gallery/+ page.tsx+ [workflow-log.md]+ 2-mock-dashboard/+ dashboard.tsx++Fixture folder name MUST start with the eval id, optionally followed by+"-<kebab-slug>". Each .tsx file in the folder is checked (RuntimeTypes.ts+is excluded).+`);+}++function loadEvals() {+ const file = path.join(__dirname, 'evals.json');+ return JSON.parse(fs.readFileSync(file, 'utf8'));+}++function isPhase5Expectation(text) {+ return /^Phase 5\b/.test(text);+}++function main() {+ const args = parseArgs(process.argv.slice(2));+ const fixturesDir = args.fixtures+ ? path.resolve(args.fixtures)+ : path.join(__dirname, 'fixtures');++ let fixtures;+ try {+ fixtures = loadFixtures(fixturesDir);+ } catch (err) {+ console.error(`error: ${err.message}`);+ process.exit(2);+ }++ let evalsData;+ try {+ evalsData = loadEvals();+ } catch (err) {+ console.error(`error: failed to load evals.json: ${err.message}`);+ process.exit(2);+ }+ const evalById = new Map(evalsData.evals.map((e) => [e.id, e]));++ // Filter fixtures by eval id / tier if requested+ let selected = fixtures;+ if (args.eval !== null) {+ selected = selected.filter((f) => f.id === args.eval);+ }+ if (args.tier) {+ selected = selected.filter((f) => {+ const ev = evalById.get(f.id);+ return ev && ev.tier === args.tier;+ });+ }++ if (selected.length === 0) {+ console.error('error: no fixtures matched the filter');+ process.exit(2);+ }++ const reporter = new TapReporter();+ reporter.start(selected.length);++ for (const fix of selected) {+ reporter.startFixture(fix.dirName);+ const ev = evalById.get(fix.id);+ if (!ev) {+ reporter.assertion(+ `fixture references eval id ${fix.id}`,+ { status: 'fail', reason: `no eval with id ${fix.id} in evals.json` }+ );+ reporter.endFixture();+ continue;+ }+ if (fix.files.length === 0) {+ reporter.assertion(+ 'fixture has at least one .tsx file',+ { status: 'fail', reason: 'no .tsx files in fixture (excluding RuntimeTypes.ts)' }+ );+ reporter.endFixture();+ continue;+ }++ // Apply every common_code_assertion+ for (const assertionText of evalsData.common_code_assertions) {+ const check = ASSERTIONS.get(assertionText);+ const result = check+ ? check({ files: fix.files, eval: ev })+ : { status: 'skip', reason: 'no check registered for this assertion text' };+ reporter.assertion(assertionText, result);+ }++ // Apply each per-eval Phase 5 expectation+ const phase5 = ev.expectations.filter(isPhase5Expectation);+ for (const expectationText of phase5) {+ const check = PHASE5_EXPECTATIONS.get(expectationText);+ const result = check+ ? check({ files: fix.files, eval: ev })+ : { status: 'skip', reason: 'no check registered for this Phase 5 expectation' };+ reporter.assertion(expectationText, result);+ }++ reporter.endFixture();+ }++ reporter.end();+ process.exit(reporter.exitCode);+}++if (require.main === module) main();++module.exports = { main, parseArgs };diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.jsnew file mode 100644index 000000000..806200c76--- /dev/null+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js@@ -0,0 +1,418 @@+'use strict';+const { test } = require('node:test');+const assert = require('node:assert/strict');++const {+ WORKFLOW_ASSERTIONS,+ PHASE_EXPECTATIONS,+ planSection,+ entitiesNeedCreating,+ newAppNeeded,+} = require('../lib/assertions-layer-1.js');++function fix(overrides = {}) {+ return {+ id: 2,+ dirName: '2-test',+ dir: '/fake',+ files: [],+ workflowLog: null,+ genpagePlan: null,+ genpageEditPlan: null,+ entityCreationLog: null,+ ...overrides,+ };+}++function evalStub(id = 2) {+ return { id, tier: 'smoke', prompt: '', data: {}, expectations: [] };+}++// ---------- helpers ----------++test('planSection extracts text under a heading', () => {+ const plan = `# Genpage Plan+## Environment++- Solution: Default+- Publisher Prefix: new++## Pages+foo+`;+ const env = planSection(plan, 'Environment');+ assert.match(env, /Solution: Default/);+ assert.doesNotMatch(env, /Pages/);+});++test('entitiesNeedCreating returns false on "No entity creation required"', () => {+ const plan = `## Entity Creation Required++No entity creation required — all entities already exist.++## Existing Entities+account+`;+ assert.equal(entitiesNeedCreating(plan), false);+});++test('entitiesNeedCreating returns true when section has content', () => {+ const plan = `## Entity Creation Required++| Table | Suffix |+|-------|--------|+| cr_widget | widget |++## Existing Entities+`;+ assert.equal(entitiesNeedCreating(plan), true);+});++test('newAppNeeded detects "create new app" intent', () => {+ assert.equal(newAppNeeded('plan: create new app'), true);+ assert.equal(newAppNeeded('plan: use existing app'), false);+});++// ---------- workflow-log.md present check ----------++test('workflow-log.md present: fail when absent', () => {+ const check = WORKFLOW_ASSERTIONS.get('A workflow-log.md file is saved to the working directory documenting all phases attempted');+ const result = check({ fixture: fix(), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('workflow-log.md present: fail when very short', () => {+ const check = WORKFLOW_ASSERTIONS.get('A workflow-log.md file is saved to the working directory documenting all phases attempted');+ const result = check({ fixture: fix({ workflowLog: 'short' }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('workflow-log.md present: pass when content exceeds threshold', () => {+ const check = WORKFLOW_ASSERTIONS.get('A workflow-log.md file is saved to the working directory documenting all phases attempted');+ const log = '# Workflow Log\n' + 'a'.repeat(100);+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- Phase 1 prereq checks ----------++test('node --version and pac help: pass when both recorded separately', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');+ const log = `## Phase 1+- node --version → v20+- pac help → PAC CLI Version 2.7.3+`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('node --version and pac help: fail when chained with &&', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');+ const log = `node --version && pac help → 2.7.3`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /chained/);+});++test('node --version and pac help: fail when version not verified', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');+ const log = `- node --version\n- pac help`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- Solution lines in plan ----------++test('Solution+Publisher lines: pass with list-marker format', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows');+ const plan = `## Environment++- Solution: Default+- Publisher Prefix: new++## Pages+`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Solution+Publisher lines: pass with bare format', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows');+ const plan = `## Environment++Solution: Default+Publisher Prefix: new++## Pages+`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Solution+Publisher lines: fail when Solution missing', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md ALWAYS contains \'Solution:\' and \'Publisher Prefix:\' lines in ## Environment; default fallback is \'Solution: Default\' + \'Publisher Prefix: new\' for code-only flows');+ const plan = `## Environment\n- Publisher Prefix: new\n## Pages\n`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /Solution/);+});++// ---------- Solution question gating ----------++test('Solution question: pass on code-only flow that did NOT ask', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written');+ const log = `- Build is code-only — solution selection question SKIPPED\n- Wrote Solution: Default, Publisher Prefix: new`;+ const plan = `## Entity Creation Required\nNo entity creation required — all entities already exist.\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Solution question: fail on code-only that DID ask', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written');+ const log = `- AskUserQuestion about solution selection asked`;+ const plan = `## Entity Creation Required\nNo entity creation required — all entities already exist.\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Solution question: fail on metadata flow that did NOT ask', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): The solution selection question is asked via AskUserQuestion ONLY when the build needs metadata work (new entities OR new app); for code-only flows the question is skipped but the Default values are still written');+ const log = `- Plan written`;+ const plan = `## Entity Creation Required\n\n| Table | Suffix |\n| widget | widget |\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- Plan schema check ----------++test('plan-schema: fail when required heading missing', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md');+ const plan = `# Genpage Plan\n## User Requirements\nfoo\n`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /## Environment|## Pages/);+});++test('plan-schema: pass when all headings present', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): genpage-plan.md is written to the working directory, conforming to references/plan-schema.md');+ const plan = `# Genpage Plan+## User Requirements+## Working Directory+## Plugin Root+## Environment+## Pages+`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- check-auth before entity-builder ----------++test('check-auth gating: skip when no entity work', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked; on ok:false the orchestrator surfaces the message to the user and halts');+ const plan = `## Entity Creation Required\nNo entity creation required — all entities already exist.\n`;+ const result = check({ fixture: fix({ workflowLog: 'something', genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('check-auth gating: pass when check-auth precedes the first entity script', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked; on ok:false the orchestrator surfaces the message to the user and halts');+ const log = `node check-auth.js → ok: true+node create-table.js widget --solution Default`;+ const plan = `## Entity Creation Required\n| Table | Suffix |\n| widget | widget |\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('check-auth gating: fail when an entity script runs before check-auth', () => {+ const check = WORKFLOW_ASSERTIONS.get('Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked; on ok:false the orchestrator surfaces the message to the user and halts');+ const log = `node create-table.js widget --solution Default+node check-auth.js → ok: true`;+ const plan = `## Entity Creation Required\n| Table | Suffix |\n| widget | widget |\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('check-auth gating: pass when builder agent name appears before check-auth but no scripts have run yet', () => {+ // This is the meta-list scenario: "## Agents Invoked\n- entity-builder\n##+ // Commands Executed\n- check-auth.js\n- create-table.js". The runner must+ // not treat the agent NAME mention as an actual invocation.+ const check = WORKFLOW_ASSERTIONS.get('Phase 2a: When entities need creating, scripts/check-auth.js runs and returns ok:true before entity-builder is invoked; on ok:false the orchestrator surfaces the message to the user and halts');+ const log = `## Agents Invoked+- genpage-entity-builder: invoked per workflow++## Commands+node check-auth.js → ok: true+node create-table.js widget --solution Default`;+ const plan = `## Entity Creation Required\n| Table | Suffix |\n| widget | widget |\n`;+ const result = check({ fixture: fix({ workflowLog: log, genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- prefix discipline plan format ----------++test('prefix discipline plan format: pass on suffix-only names', () => {+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.');+ const plan = `## Entity Creation Required++| Table | Suffix |+|-------|--------|+| Widget | widget |++`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('prefix discipline plan format: fail when prefix bled into suffix', () => {+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — plan format: Every name in `## Entity Creation Required` (table headings, column Suffix values, choice column suffixes, relationship Lookup Suffix values) is a bare suffix matching `^[a-z][a-z0-9]+$`. No value contains an underscore or a prefix. The prefix lives only in `## Environment` → `Publisher Prefix:`.');+ const plan = `## Entity Creation Required++| Table |+| cr_widget |++`;+ const result = check({ fixture: fix({ genpagePlan: plan }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /cr_widget/);+});++// ---------- prefix discipline resolved names ----------++test('prefix resolved names: pass when all names start with publisher prefix', () => {+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');+ const plan = `## Environment\nPublisher Prefix: crb2b\n`;+ const elog = `- Create table widget: Resolved Full Name: crb2b_widget\n`;+ const result = check({ fixture: fix({ genpagePlan: plan, entityCreationLog: elog }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('prefix resolved names: fail on prefix mismatch', () => {+ const check = WORKFLOW_ASSERTIONS.get('Prefix discipline — resolved names: For every operation in `entity-creation-log.md`, the Resolved Full Name starts with the `Publisher Prefix:` value from the plan\'s `## Environment` followed by `_` and the bare suffix from the plan (e.g., Publisher Prefix `crb2b` + suffix `playername` → `crb2b_playername`).');+ const plan = `## Environment\nPublisher Prefix: crb2b\n`;+ const elog = `- Resolved Full Name: cr_widget\n`;+ const result = check({ fixture: fix({ genpagePlan: plan, entityCreationLog: elog }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /cr_widget/);+});++// ---------- Phase 4 generate-types ----------++test('Phase 4 generate-types skipped: pass when log only mentions "not run"', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 4: RuntimeTypes generation is SKIPPED (mock data)');+ const log = `## Phase 4\n- pac model genpage generate-types not run (mock data)`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 4 generate-types skipped: fail when actually invoked', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 4: RuntimeTypes generation is SKIPPED (mock data)');+ const log = `pac model genpage generate-types --data-sources 'account' --output-file RuntimeTypes.ts`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- Phase 6 upload flags ----------++test('Phase 6 flags: pass when all flags present', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 6: pac model genpage upload includes --app-id, --code-file, --data-sources \'account\', --prompt, --model, --name, --agent-message, --add-to-sitemap');+ const log = `pac model genpage upload --app-id 1 --code-file p.tsx --data-sources 'account' --prompt "x" --model claude --name "p" --agent-message "m" --add-to-sitemap`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 6 flags: fail when --agent-message missing', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 6: pac model genpage upload includes --app-id, --code-file, --data-sources \'account\', --prompt, --model, --name, --agent-message, --add-to-sitemap');+ const log = `pac model genpage upload --app-id 1 --code-file p.tsx --data-sources 'account' --prompt "x" --model claude --name "p" --add-to-sitemap`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /--agent-message/);+});++test('Phase 6 mock-data: pass when upload omits --data-sources', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 6: Deployment omits --data-sources flag (mock data page)');+ const log = `pac model genpage upload --app-id 1 --code-file p.tsx --prompt "x" --add-to-sitemap`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 6 mock-data: fail when upload has --data-sources', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 6: Deployment omits --data-sources flag (mock data page)');+ const log = `pac model genpage upload --data-sources 'account' --code-file p.tsx`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- entity-builder gating ----------++test('Phase 2 entity-builder SKIPPED (no entities): pass when not invoked', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 2: Entity-builder is SKIPPED (no entities to create)');+ const log = `## Phase 2\n- SKIPPED (account exists)`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 2 entity-builder SKIPPED (no entities): fail when invoked', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 2: Entity-builder is SKIPPED (no entities to create)');+ const log = `genpage-entity-builder invoked`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- single-page fast path ----------++test('5b fast path: pass when no Task dispatch and inline noted', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder');+ const log = `## Phase 5b — single-page fast path\n- inlined build, no Task subagent dispatched`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('5b fast path: fail when Task subagent dispatched', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder');+ const log = `Task genpage-page-builder invoked`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- edit flow ----------++test('Edit flow detection: pass when "edit flow" mentioned', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 1 (Planner): User indicates \'edit existing\'; planner returns { action: \'edit\' }, skipping Phases 2-8 of the create flow');+ const log = `Edit flow taken; action: edit`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Edit Phase 6 page-id: fail when --add-to-sitemap present', () => {+ const check = PHASE_EXPECTATIONS.get('Edit Phase 6: pac model genpage upload uses --page-id flag; omits --add-to-sitemap');+ const log = `pac model genpage upload --page-id abc --add-to-sitemap`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Edit Phase 6 page-id: pass when --page-id and no --add-to-sitemap', () => {+ const check = PHASE_EXPECTATIONS.get('Edit Phase 6: pac model genpage upload uses --page-id flag; omits --add-to-sitemap');+ const log = `pac model genpage upload --page-id abc --prompt "delta"`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- entity-builder --solution always ----------++test('Entity scripts --solution: pass when every call has --solution', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 2b (Entity Builder): Every create-table.js / add-column.js / create-relationship.js call passes --solution <name> (always — \'Default\' is a valid value, never omitted)');+ const log = `- node create-table.js --name widget --solution Default+- node add-column.js --table widget --name foo --type string --solution Default`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Entity scripts --solution: fail when a call missing --solution', () => {+ const check = PHASE_EXPECTATIONS.get('Phase 2b (Entity Builder): Every create-table.js / add-column.js / create-relationship.js call passes --solution <name> (always — \'Default\' is a valid value, never omitted)');+ const log = `- node create-table.js --name widget+- node add-column.js --table widget --name foo --solution Default`;+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /create-table\.js/);+});diff --git a/evals/model-apps/genpage/tests/assertions-layer-2.test.js b/evals/model-apps/genpage/tests/assertions-layer-2.test.jsnew file mode 100644index 000000000..56bf712b9--- /dev/null+++ b/evals/model-apps/genpage/tests/assertions-layer-2.test.js@@ -0,0 +1,412 @@+'use strict';+const { test } = require('node:test');+const assert = require('node:assert/strict');++const {+ ASSERTIONS,+ PHASE5_EXPECTATIONS,+ setVerifiedIcons,+ extractIconImports,+ isDataverseFile,+ isMockFile,+} = require('../lib/assertions-layer-2.js');++// Helper to build a fake "file" object the assertion API expects.+function f(name, content) {+ return { path: `/fake/${name}`, name, content };+}++function evalStub(id = 1) {+ return { id, tier: 'smoke', prompt: '', data: {}, expectations: [] };+}++// Seed verified-icons so tests don't depend on the on-disk list.+setVerifiedIcons(new Set(['AddRegular', 'EditRegular', 'DeleteRegular', 'PeopleRegular']));++// ---------- helpers ----------++test('extractIconImports parses single-line imports', () => {+ const src = `import { AddRegular, EditRegular } from "@fluentui/react-icons";`;+ assert.deepEqual(extractIconImports(src), ['AddRegular', 'EditRegular']);+});++test('extractIconImports handles multi-line imports and aliases', () => {+ const src = `import {+ AddRegular,+ EditRegular as Edit,+ DeleteRegular+ } from "@fluentui/react-icons";`;+ assert.deepEqual(extractIconImports(src), ['AddRegular', 'EditRegular', 'DeleteRegular']);+});++test('isDataverseFile / isMockFile based on RuntimeTypes import', () => {+ assert.equal(isDataverseFile(`import { X } from "./RuntimeTypes";`), true);+ assert.equal(isDataverseFile(`import { X } from "other";`), false);+ assert.equal(isMockFile(`import { X } from "other";`), true);+});++// ---------- assertion: export default GeneratedComponent ----------++test('export default GeneratedComponent: pass when present', () => {+ const check = ASSERTIONS.get('Generated .tsx is a single file with `export default GeneratedComponent`');+ const result = check({ files: [f('a.tsx', `export default GeneratedComponent;`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('export default GeneratedComponent: fail when missing', () => {+ const check = ASSERTIONS.get('Generated .tsx is a single file with `export default GeneratedComponent`');+ const result = check({ files: [f('a.tsx', `export default OtherName;`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: destructures pageInput ----------++test('destructures pageInput: pass on valid destructure', () => {+ const check = ASSERTIONS.get('Generated .tsx destructures props including `pageInput` (e.g., `const { dataApi, pageInput } = props;`)');+ const result = check({ files: [f('a.tsx', `const { dataApi, pageInput } = props;`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('destructures pageInput: fail when only dataApi is destructured', () => {+ const check = ASSERTIONS.get('Generated .tsx destructures props including `pageInput` (e.g., `const { dataApi, pageInput } = props;`)');+ const result = check({ files: [f('a.tsx', `const { dataApi } = props;`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: 100vh/100vw ----------++test('no 100vh/100vw: pass on clean code', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use `100vh` or `100vw`');+ const result = check({ files: [f('a.tsx', `height: '50%'`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('no 100vh/100vw: fail when used in code', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use `100vh` or `100vw`');+ const result = check({ files: [f('a.tsx', `height: '100vh'`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('no 100vh/100vw: pass when only in comments (stripComments ignores)', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use `100vh` or `100vw`');+ const result = check({ files: [f('a.tsx', `// rule: never use 100vh\nheight: '50%';`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('no 100vh/100vw: pass when only in block comment', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use `100vh` or `100vw`');+ const result = check({ files: [f('a.tsx', `/* avoid 100vh */ height: '50%';`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: forbidden theme functions ----------++test('forbidden theme funcs: fail on real usage', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT import `createTheme`, `mergeThemes`, or `useTheme` (these do not exist in Fluent UI V9)');+ const result = check({ files: [f('a.tsx', `const t = useTheme();`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('forbidden theme funcs: pass when only in comment', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT import `createTheme`, `mergeThemes`, or `useTheme` (these do not exist in Fluent UI V9)');+ const result = check({ files: [f('a.tsx', `// don't use useTheme\nconst t = tokens;`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: FluentProvider ----------++test('no <FluentProvider>: fail on top-level wrap', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT wrap content in a top-level `<FluentProvider>` (already provided at root)');+ const result = check({ files: [f('a.tsx', `return <FluentProvider><div/></FluentProvider>;`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: window.location / react-router ----------++test('no window.location: fail on use', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use React Router or construct raw URLs / manipulate `window.location` for navigation');+ const result = check({ files: [f('a.tsx', `window.location.href = '/foo'`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('no react-router: fail on import', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT use React Router or construct raw URLs / manipulate `window.location` for navigation');+ const result = check({ files: [f('a.tsx', `import { Link } from "react-router-dom";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: Xrm.Navigation.navigateTo ----------++test('Xrm.Navigation: skip when no nav intent', () => {+ const check = ASSERTIONS.get('Generated .tsx uses `Xrm.Navigation.navigateTo` for any in-app navigation');+ const result = check({ files: [f('a.tsx', `const x = 1;`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('Xrm.Navigation: pass when used correctly', () => {+ const check = ASSERTIONS.get('Generated .tsx uses `Xrm.Navigation.navigateTo` for any in-app navigation');+ const result = check({ files: [f('a.tsx', `Xrm.Navigation.navigateTo(pageInput);`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Xrm.Navigation: fail when nav intent but wrong API', () => {+ const check = ASSERTIONS.get('Generated .tsx uses `Xrm.Navigation.navigateTo` for any in-app navigation');+ const result = check({ files: [f('a.tsx', `openRecord('account', id);`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: unsized icons ----------++test('unsized icons: pass on AddRegular', () => {+ const check = ASSERTIONS.get('Generated .tsx uses Fluent UI icons in unsized form (e.g., `AddRegular`, not `Add24Regular`)');+ const result = check({ files: [f('a.tsx', `import { AddRegular } from "@fluentui/react-icons";`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('unsized icons: fail on Add24Regular', () => {+ const check = ASSERTIONS.get('Generated .tsx uses Fluent UI icons in unsized form (e.g., `AddRegular`, not `Add24Regular`)');+ const result = check({ files: [f('a.tsx', `import { Add24Regular } from "@fluentui/react-icons";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /Add24Regular/);+});++test('unsized icons: pass when sized name appears only in comment', () => {+ const check = ASSERTIONS.get('Generated .tsx uses Fluent UI icons in unsized form (e.g., `AddRegular`, not `Add24Regular`)');+ const result = check({ files: [f('a.tsx', `// use AddRegular not Add24Regular\nimport { AddRegular } from "@fluentui/react-icons";`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: verified-icons ----------++test('verified-icons: fail on hallucinated import', () => {+ const check = ASSERTIONS.get('Every named import from `@fluentui/react-icons` in the generated .tsx appears in references/verified-icons.txt — no hallucinated icon names');+ const result = check({ files: [f('a.tsx', `import { MadeUpIconRegular } from "@fluentui/react-icons";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+ assert.match(result.reason, /MadeUpIconRegular/);+});++test('verified-icons: pass on real icons', () => {+ const check = ASSERTIONS.get('Every named import from `@fluentui/react-icons` in the generated .tsx appears in references/verified-icons.txt — no hallucinated icon names');+ const result = check({ files: [f('a.tsx', `import { AddRegular, PeopleRegular } from "@fluentui/react-icons";`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: try/catch around dataApi ----------++test('dataApi try/catch: skip when no Dataverse files', () => {+ const check = ASSERTIONS.get('Generated .tsx wraps async `dataApi` calls in try-catch (Dataverse pages only)');+ const result = check({ files: [f('a.tsx', `const x = 1;`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('dataApi try/catch: pass when wrapped', () => {+ const check = ASSERTIONS.get('Generated .tsx wraps async `dataApi` calls in try-catch (Dataverse pages only)');+ const src = `import type { X } from "./RuntimeTypes";+async function fn() { try { await dataApi.queryTable('account'); } catch (e) {} }`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('dataApi try/catch: fail when missing', () => {+ const check = ASSERTIONS.get('Generated .tsx wraps async `dataApi` calls in try-catch (Dataverse pages only)');+ const src = `import type { X } from "./RuntimeTypes";+async function fn() { await dataApi.queryTable('account'); }`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- assertion: no TODO/FIXME ----------++test('no TODO: fail when present', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies');+ const result = check({ files: [f('a.tsx', `// TODO: implement this`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('no TODO: fail when bare ellipsis on a line', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies');+ const result = check({ files: [f('a.tsx', `function fn() {\n ...\n}`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('no TODO: pass when spreads exist (...props is fine)', () => {+ const check = ASSERTIONS.get('Generated .tsx does NOT include any `TODO`, `FIXME`, ellipsis placeholders, or incomplete function bodies');+ const result = check({ files: [f('a.tsx', `function fn(props) { return <Comp {...props} />; }`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: DataGrid needs createTableColumn + sizing ----------++test('DataGrid: skip when no DataGrid usage', () => {+ const check = ASSERTIONS.get('For DataGrids, generated .tsx imports `createTableColumn` from `@fluentui/react-components` and configures column sizing (columnSizingOptions or resizableColumns)');+ const result = check({ files: [f('a.tsx', `<div/>`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('DataGrid: fail when missing createTableColumn', () => {+ const check = ASSERTIONS.get('For DataGrids, generated .tsx imports `createTableColumn` from `@fluentui/react-components` and configures column sizing (columnSizingOptions or resizableColumns)');+ const src = `import { DataGrid } from "@fluentui/react-components";+return <DataGrid columnSizingOptions={{}} />;`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('DataGrid: pass with both createTableColumn and sizing', () => {+ const check = ASSERTIONS.get('For DataGrids, generated .tsx imports `createTableColumn` from `@fluentui/react-components` and configures column sizing (columnSizingOptions or resizableColumns)');+ const src = `import { DataGrid, createTableColumn } from "@fluentui/react-components";+return <DataGrid resizableColumns />;`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++// ---------- assertion: PAGEREF for multi-page ----------++test('PAGEREF: skip on single-page fixture', () => {+ const check = ASSERTIONS.get('For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs');+ const result = check({ files: [f('a.tsx', `Xrm.Navigation.navigateTo({});`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('PAGEREF: pass on multi-page with placeholder', () => {+ const check = ASSERTIONS.get('For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs');+ const files = [+ f('list.tsx', `Xrm.Navigation.navigateTo({ pageId: "PAGEREF_detail" });`),+ f('detail.tsx', `// no nav`),+ ];+ const result = check({ files, eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('PAGEREF: fail on multi-page with hard-coded GUIDs', () => {+ const check = ASSERTIONS.get('For multi-page builds, cross-page navigation uses quoted `"PAGEREF_<filename>"` placeholders that the orchestrator\'s Phase 6.5 resolves to real GUIDs');+ const files = [+ f('list.tsx', `Xrm.Navigation.navigateTo({ pageId: "abc-123-def" });`),+ f('detail.tsx', `const x = 1;`),+ ];+ const result = check({ files, eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- queryTable result.rows ----------++test('queryTable .rows: pass when result.rows accessed', () => {+ const check = ASSERTIONS.get('For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)');+ const src = `import { X } from "./RuntimeTypes";+async function fn() {+ const result = await dataApi.queryTable('account', { top: 100 });+ setRecords(result.rows);+}`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('queryTable .rows: fail when result iterated directly', () => {+ const check = ASSERTIONS.get('For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)');+ const src = `import { X } from "./RuntimeTypes";+async function fn() {+ const result = await dataApi.queryTable('account', { top: 100 });+ return result.map((r) => r.name); // BUG — result is DataTable, not Array+}`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('queryTable .rows: skip on mock pages (no RuntimeTypes import)', () => {+ const check = ASSERTIONS.get('For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)');+ const result = check({ files: [f('a.tsx', `const data = [{ a: 1 }, { a: 2 }];`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('queryTable .rows: skip when Dataverse file does not use queryTable', () => {+ const check = ASSERTIONS.get('For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)');+ const src = `import { X } from "./RuntimeTypes";+async function fn() {+ await dataApi.createRow('account', {});+}`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('queryTable .rows: comment-only "result.map" does not pass', () => {+ // Comments are stripped before the regex looks for .rows, so a file with+ // queryTable but only a commented-out result.rows reference fails.+ const check = ASSERTIONS.get('For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)');+ const src = `import { X } from "./RuntimeTypes";+async function fn() {+ const result = await dataApi.queryTable('account', {});+ // hint: use result.rows+ return result.length; // wrong: this is the DataTable, not an array+}`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++// ---------- Phase 5 expectations ----------++test('Phase 5 - charts: fail on Chart.js import', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Chart uses D3.js exclusively — no Chart.js, Recharts, or other libraries. D3 code uses group() not nest()');+ const result = check({ files: [f('a.tsx', `import Chart from "chart.js";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - charts: fail on d3.nest()', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Chart uses D3.js exclusively — no Chart.js, Recharts, or other libraries. D3 code uses group() not nest()');+ const result = check({ files: [f('a.tsx', `const grouped = d3.nest().key(d => d.cat);`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - charts: pass on d3.group()', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Chart uses D3.js exclusively — no Chart.js, Recharts, or other libraries. D3 code uses group() not nest()');+ const result = check({ files: [f('a.tsx', `const grouped = d3.group(arr, d => d.cat);`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 5 - DatePicker: fail on wrong import package', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): DatePicker (if used) is imported from @fluentui/react-datepicker-compat, not @fluentui/react-components');+ const result = check({ files: [f('a.tsx', `import { DatePicker } from "@fluentui/react-components";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - DatePicker: pass on correct compat import', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): DatePicker (if used) is imported from @fluentui/react-datepicker-compat, not @fluentui/react-components');+ const result = check({ files: [f('a.tsx', `import { DatePicker } from "@fluentui/react-datepicker-compat";`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});++test('Phase 5 - DnD: fail on react-dnd import', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Drag-and-drop uses native HTML5 events (onDragStart, onDragOver, onDrop) — no external DnD library');+ const result = check({ files: [f('a.tsx', `import { useDrag } from "react-dnd";`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - task entity: fail on plural', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Code uses entity logical name \'task\' (singular lowercase) not \'tasks\'');+ const result = check({ files: [f('a.tsx', `dataApi.queryTable("tasks", {});`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - submit handler: fail when no createRow', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Submit uses dataApi.createRow with verified column names from RuntimeTypes.ts');+ const src = `import { X } from "./RuntimeTypes";+function onSubmit() { console.log('submit'); }`;+ const result = check({ files: [f('a.tsx', src)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - submit handler: skip without RuntimeTypes import', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Submit uses dataApi.createRow with verified column names from RuntimeTypes.ts');+ const result = check({ files: [f('a.tsx', `function onSubmit() {}`)], eval: evalStub() });+ assert.equal(result.status, 'skip');+});++test('Phase 5 - raw HTML form elements: fail on <input>', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Form uses Fluent UI V9 components (Input, Dropdown, etc.) — not HTML form elements');+ const result = check({ files: [f('a.tsx', `<input type="text" />`)], eval: evalStub() });+ assert.equal(result.status, 'fail');+});++test('Phase 5 - raw HTML form elements: pass on Fluent <Input>', () => {+ const check = PHASE5_EXPECTATIONS.get('Phase 5 (Page Builder): Form uses Fluent UI V9 components (Input, Dropdown, etc.) — not HTML form elements');+ const result = check({ files: [f('a.tsx', `<Input value="" />`)], eval: evalStub() });+ assert.equal(result.status, 'pass');+});diff --git a/evals/model-apps/genpage/tests/run-layer-1.test.js b/evals/model-apps/genpage/tests/run-layer-1.test.jsnew file mode 100644index 000000000..3095a1cb2--- /dev/null+++ b/evals/model-apps/genpage/tests/run-layer-1.test.js@@ -0,0 +1,171 @@+'use strict';+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const { spawnSync } = require('node:child_process');++const runner = path.join(__dirname, '..', 'run-layer-1.js');++function mkTempFixturesDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'layer1-tests-'));+}++function writeFixture(rootDir, fixtureName, files) {+ const dir = path.join(rootDir, fixtureName);+ fs.mkdirSync(dir, { recursive: true });+ for (const [name, content] of Object.entries(files)) {+ fs.writeFileSync(path.join(dir, name), content);+ }+}++function runRunner(args) {+ const result = spawnSync(process.execPath, [runner, ...args], { encoding: 'utf8' });+ return { code: result.status, stdout: result.stdout, stderr: result.stderr };+}++// Minimal workflow log + plan that should satisfy core assertions for a mock+// (code-only) eval like id 2.+function mockEval2Artifacts() {+ return {+ 'workflow-log.md': `# Workflow Log+## Phase 0+- working directory created+## Phase 1+- node --version+- pac help → PAC CLI Version 2.7.3 (>= 2.7.0 verified)+- pac auth list — active profile, environment https://x.crm.dynamics.com+- AskUserQuestion: new or edit → create new+- Solution selection question SKIPPED (code-only flow)+- EnterPlanMode → approved+## Phase 2 — SKIPPED (mock data)+## Phase 4 — pac model genpage generate-types not run (mock data)+## Phase 5b — single-page fast path, inlined build+- Data mode: mock+- read verified-icons.txt+- read samples/8-dashboard-with-charts.tsx+- icon verification: grep "react-icons", verified icons against verified-icons.txt+## Phase 6+- pac model genpage upload --app-id 1 --code-file p.tsx --prompt "x" --model claude-sonnet --name "p" --agent-message "m" --add-to-sitemap+`,+ 'genpage-plan.md': `# Genpage Plan+## User Requirements+foo+## Working Directory+wd/+## Plugin Root+pr/+## Environment+- Solution: Default+- Publisher Prefix: new+## Pages+| Page | File |+| P | p.tsx |+## Entity Creation Required+No entity creation required — all entities already exist.+## Existing Entities+account+## Design Preferences+clean+## Relevant Samples+8-dashboard-with-charts.tsx+## Per-Page Specifications+### P+foo+`,+ };+}++// ---------- end-to-end: green-path fixture ----------++test('runner: exits 0 when fixture satisfies common assertions', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-mock', mockEval2Artifacts());+ // Add at least one .tsx so fixture-loader doesn't choke (it doesn't gate on .tsx for L1 but we keep parity)+ fs.writeFileSync(path.join(root, '2-mock', 'p.tsx'), `// pretend page`);+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 0, `expected exit 0 but got ${code}.\nstdout:\n${stdout}`);+ assert.match(stdout, /ok 1 - 2-mock/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: missing workflow-log.md ----------++test('runner: fails when workflow-log.md missing', () => {+ const root = mkTempFixturesDir();+ try {+ const artifacts = mockEval2Artifacts();+ delete artifacts['workflow-log.md'];+ writeFixture(root, '2-no-log', artifacts);+ fs.writeFileSync(path.join(root, '2-no-log', 'p.tsx'), `// page`);+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 1);+ assert.match(stdout, /not ok \d+ - A workflow-log\.md file is saved/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: missing genpage-plan.md ----------++test('runner: fails when genpage-plan.md missing', () => {+ const root = mkTempFixturesDir();+ try {+ const artifacts = mockEval2Artifacts();+ delete artifacts['genpage-plan.md'];+ writeFixture(root, '2-no-plan', artifacts);+ fs.writeFileSync(path.join(root, '2-no-plan', 'p.tsx'), `// page`);+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 1);+ assert.match(stdout, /not ok \d+ - .*'Solution:' and 'Publisher Prefix:'/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: filter by tier ----------++test('runner: --tier filters by eval tier', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-smoke', mockEval2Artifacts());+ fs.writeFileSync(path.join(root, '2-smoke', 'p.tsx'), `// page`);+ writeFixture(root, '4-full', mockEval2Artifacts());+ fs.writeFileSync(path.join(root, '4-full', 'p.tsx'), `// page`);+ const { stdout } = runRunner(['--fixtures', root, '--tier', 'smoke']);+ assert.match(stdout, /# Subtest: 2-smoke/);+ assert.doesNotMatch(stdout, /# Subtest: 4-full/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: missing fixtures dir ----------++test('runner: exits 2 when fixtures dir missing', () => {+ const { code, stderr } = runRunner(['--fixtures', '/nonexistent/path/zzz']);+ assert.equal(code, 2);+ assert.match(stderr, /Fixtures directory does not exist/);+});++// ---------- end-to-end: TAP shape ----------++test('runner: emits TAP version 13 and aggregate counts', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-x', mockEval2Artifacts());+ fs.writeFileSync(path.join(root, '2-x', 'p.tsx'), `// page`);+ const { stdout } = runRunner(['--fixtures', root]);+ assert.match(stdout, /^TAP version 13/m);+ assert.match(stdout, /# tests \d+/);+ assert.match(stdout, /# pass\s+\d+/);+ assert.match(stdout, /# fail\s+\d+/);+ assert.match(stdout, /# skip\s+\d+/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/evals/model-apps/genpage/tests/run-layer-2.test.js b/evals/model-apps/genpage/tests/run-layer-2.test.jsnew file mode 100644index 000000000..9da58f348--- /dev/null+++ b/evals/model-apps/genpage/tests/run-layer-2.test.js@@ -0,0 +1,219 @@+'use strict';+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const { spawnSync } = require('node:child_process');++const runner = path.join(__dirname, '..', 'run-layer-2.js');++function mkTempFixturesDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'layer2-tests-'));+}++function writeFixture(rootDir, fixtureName, files) {+ const dir = path.join(rootDir, fixtureName);+ fs.mkdirSync(dir, { recursive: true });+ for (const [name, content] of Object.entries(files)) {+ fs.writeFileSync(path.join(dir, name), content);+ }+}++function runRunner(args) {+ const result = spawnSync(process.execPath, [runner, ...args], { encoding: 'utf8' });+ return { code: result.status, stdout: result.stdout, stderr: result.stderr };+}++// ---------- end-to-end: green-path fixture ----------++test('runner: exits 0 when fixture passes all assertions', () => {+ const root = mkTempFixturesDir();+ try {+ // Minimal v2.1-compliant single-file mock page.+ writeFixture(root, '2-mock-clean', {+ 'page.tsx': `import { makeStyles, tokens } from '@fluentui/react-components';+const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });+const data = [{ a: 1, b: 'x' }, { a: 2, b: 'y' }];+const GeneratedComponent = (props) => {+ const { pageInput } = props;+ void pageInput;+ const styles = useStyles();+ return <div className={styles.root}>{data.length}</div>;+};+export default GeneratedComponent;`,+ });+ const { code } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 0);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: failing fixture ----------++test('runner: exits 1 when fixture has 100vh violation', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-bad', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ root: { height: '100vh' } });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => {+ const { pageInput } = props;+ void pageInput;+ return <div style={{ height: '100vh' }} />;+};+export default GeneratedComponent;`,+ });+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 1);+ assert.match(stdout, /not ok \d+ - Generated \.tsx does NOT use `100vh`/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: empty fixture ----------++test('runner: fails when fixture has no .tsx files', () => {+ const root = mkTempFixturesDir();+ try {+ fs.mkdirSync(path.join(root, '2-empty'));+ fs.writeFileSync(path.join(root, '2-empty', 'workflow-log.md'), '# log\n');+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 1);+ assert.match(stdout, /fixture has at least one \.tsx file/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: filter by tier ----------++test('runner: --tier smoke filters to smoke evals only', () => {+ const root = mkTempFixturesDir();+ try {+ // eval 2 is smoke; eval 4 is full+ writeFixture(root, '2-smoke', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ });+ writeFixture(root, '4-full', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ });+ const { code, stdout } = runRunner(['--fixtures', root, '--tier', 'smoke']);+ assert.equal(code, 0);+ assert.match(stdout, /# Subtest: 2-smoke/);+ assert.doesNotMatch(stdout, /# Subtest: 4-full/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: --eval flag ----------++test('runner: --eval <id> runs only that eval id', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-x', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ });+ writeFixture(root, '4-y', {+ 'page.tsx': `// won't be selected`,+ });+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 0);+ assert.match(stdout, /1\.\.1/);+ assert.match(stdout, /# Subtest: 2-x/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: missing fixtures dir ----------++test('runner: exits 2 when fixtures dir missing', () => {+ const { code, stderr } = runRunner(['--fixtures', '/nonexistent/path/that/does/not/exist']);+ assert.equal(code, 2);+ assert.match(stderr, /Fixtures directory does not exist/);+});++// ---------- end-to-end: malformed fixture folder name ----------++test('runner: skips folders without numeric prefix', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, 'not-a-fixture', { 'page.tsx': `export default x;` });+ writeFixture(root, '2-valid', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ });+ const { code, stdout } = runRunner(['--fixtures', root]);+ assert.equal(code, 0);+ assert.match(stdout, /1\.\.1/);+ assert.doesNotMatch(stdout, /not-a-fixture/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- end-to-end: TAP shape ----------++test('runner: emits TAP version 13 header and aggregate counts', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-x', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ });+ const { stdout } = runRunner(['--fixtures', root]);+ assert.match(stdout, /^TAP version 13/m);+ assert.match(stdout, /# tests \d+/);+ assert.match(stdout, /# pass\s+\d+/);+ assert.match(stdout, /# fail\s+\d+/);+ assert.match(stdout, /# skip\s+\d+/);+ assert.match(stdout, /# fixtures \d+/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++// ---------- fixture-loader: RuntimeTypes excluded ----------++test('fixture-loader: excludes RuntimeTypes.ts from check', () => {+ const root = mkTempFixturesDir();+ try {+ writeFixture(root, '2-rt-test', {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{ a: 1 }, { a: 2 }];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ 'RuntimeTypes.tsx': `// This file should be excluded from checks - it has TODO`,+ });+ const { code, stdout } = runRunner(['--fixtures', root, '--eval', '2']);+ assert.equal(code, 0);+ // The TODO inside RuntimeTypes.tsx must not cause the TODO assertion to fail.+ assert.doesNotMatch(stdout, /not ok \d+ - .*TODO/);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex c4b29aeb9..cd83184dc 100644--- a/plugins/model-apps/.claude-plugin/plugin.json+++ b/plugins/model-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.1.0",+ "version": "2.2.0","description": "Build and deploy Power Apps generative pages for model-driven apps with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x → v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex cad3735b0..8d5bb86ae 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -29,6 +29,10 @@ claude --plugin-dir /path/to/plugins/model-apps.mcp.json ← MCP server config (Playwright for browser verification)AGENTS.md ← Plugin guidance for AI agents (this file)CLAUDE.md ← Symlink → AGENTS.md+README.md ← User-facing intro and prereqs+CHANGELOG.md ← Keep-a-Changelog+docs/+ architecture.md ← One-page architecture overview with diagramsagents/ ← Agent definitions (invoked by skills via Task tool)genpage-planner.md ← Requirements, discovery, plan doc, user approval (create flow)genpage-entity-builder.md ← DV entity creation via plugin's Web API scripts (create flow)@@ -39,9 +43,10 @@ references/ ← Shared reference docsplan-schema.md ← Schema contract for genpage-plan.mddata-caching.md ← Rule 15 list/detail caching pattern (loaded conditionally)localization.md ← Multi-language + RTL pattern (loaded conditionally)+ supported-dependencies.md ← Versioned package list for generated pagestroubleshooting.md ← Deployment/runtime/env issuesverified-icons.txt ← ~5000 Fluent UI icon names; Grep-validated by page-builder-samples/ ← Example .tsx files (10 samples)+samples/ ← Example .tsx files (11 samples)scripts/launch-playwright-mcp.js ← Playwright MCP server launcher (detects system browser)regenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm@@ -53,8 +58,11 @@ scripts/create-record.js ← Creates one or many records (auto-batches via $batch)create-solution.js ← Creates a Dataverse solution with env's Default Publisheradd-to-solution.js ← Adds an existing component to a solution+ generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.ts+ capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/dataverse-auth.js ← Shared auth + HTTP helpers (uses `az account get-access-token`)+ supported-dependencies.js ← Single source of truth for runtime + dev deps versionstests/ ← node --test coverage for the scripts aboveskills/genpage/@@ -119,6 +127,33 @@ After modifying this plugin:1. Run `claude --debug` to see plugin loading details2. Run `node --test plugins/model-apps/scripts/tests/*.test.js` (must pass)-3. Test skill invocation with `/genpage`-4. Test with both Dataverse entity pages and mock data pages (smoke + edit)-5. Verify Playwright browser verification works (navigate, snapshot, click, screenshot)+3. Run `node --test evals/model-apps/genpage/tests/*.test.js` (must pass)+4. Run both eval-suite runners against shipping fixtures (Layer 1 + Layer 2):+ - `node evals/model-apps/genpage/run-layer-1.js --tier smoke`+ - `node evals/model-apps/genpage/run-layer-2.js --tier smoke`+5. Test skill invocation with `/genpage`+6. Test with both Dataverse entity pages and mock data pages (smoke + edit)+7. Verify Playwright browser verification works (navigate, snapshot, click, screenshot)++## Eval Suite++The plugin has a 3-layer eval suite under `evals/model-apps/genpage/`. Two+layers are automated (TAP v13 runners); Layer 3 is manual.++- **Comprehensive guide:** `evals/model-apps/genpage/EVAL_GUIDE.md` — what+ we evaluate, the 3 layers, tiers (smoke/full/stress), fixture types+ (synthetic vs real captures), runner output, capture flow, cadence,+ diagnosing failures, adding evals and assertions.+- **Eval definitions:** `evals/model-apps/genpage/evals.json` — 16 evals+ with prompts, answers, and expectations.+- **Fixtures:** `evals/model-apps/genpage/fixtures/<eval-id>-<slug>/` —+ one folder per captured or synthetic run. Each contains the `.tsx`,+ `workflow-log.md`, `genpage-plan.md`, and (when applicable)+ `entity-creation-log.md` and `RuntimeTypes.ts`.++Run on every PR that touches the skill, agents, rules, or evals:++```bash+node evals/model-apps/genpage/run-layer-1.js --tier smoke+node evals/model-apps/genpage/run-layer-2.js --tier smoke+```diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 155c863d0..74e023233 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -2,6 +2,44 @@All notable changes to the **model-apps** plugin.+## [Unreleased] — 2.2.0++Local-dev ergonomics, sample coverage, and an automated eval suite with+real and synthetic fixtures. Builds on v2.1; no breaking changes.++### Added+- **Phase 0.5 — local-dev manifest.** Working dirs now get `package.json`+ and `genpage.d.ts` so `npm install` + editor IntelliSense work after+ generation. Versions in `references/supported-dependencies.md`.+- **Eval suite runners.** `run-layer-1.js` (workflow assertions) and+ `run-layer-2.js` (code assertions) emit TAP v13. `EVAL_GUIDE.md` covers+ types, tiers, capture flow.+- **10 fixtures** under `evals/.../fixtures/` (6 synthetic + 4 real+ captures; all green under the tightened v2.2 spec).+- `scripts/capture-fixture.js` — copies `/genpage` working dirs into+ fixtures and runs both layers.+- `samples/11-kanban-with-dnd.tsx` — native HTML5 drag-and-drop sample.++### Changed+- Spec tightening so workflow-logs are command-verbatim and `pageInput`+ destructure is required even on mock pages (planner, page-builder,+ SKILL.md Phase 6 + Phase 8).+- 8 runner regex relaxations to accept functionally-equivalent agent+ patterns (typed `(window as any).Xrm` aliases, `pac solution list`,+ local enum mapping, etc.) — no rule loosening.++### Fixed+- **Synthetic fixtures + sample 11 now follow Rule 11 (queryTable returns+ DataTable, not an array).** 7 files were iterating `result` directly+ (`setTasks(result)`, `result.map(...)`) instead of `result.rows`,+ producing `X.map is not a function` at runtime. Fixed in+ `samples/11-kanban-with-dnd.tsx` and 6 fixture `.tsx` files.+ New Layer 2 assertion catches this pattern going forward: any Dataverse+ file calling `dataApi.queryTable` must access `.rows` somewhere.++### Tests+- 215 passing across `scripts/tests/` + `evals/.../tests/`.+## 2.1.0 — 2026-05-13Replaces the Dataverse MCP server + Python SDK fallback with Node.js Web APIdiff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex f5173c946..0c3b74045 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -183,12 +183,21 @@ const GeneratedComponent = (props: Props) => {export default GeneratedComponent;```-Always destructure `pageInput` (even if unused on a particular page) — the eval-suite enforces this and downstream features (dark mode, navigation state) rely-on it.-### Mandatory Rules+- **Always destructure `pageInput`** — even on mock-data pages and pages that+ don't consume it. The eval suite enforces this and downstream features (dark+ mode, navigation state injection) rely on it. Acceptable forms:+ ```typescript+ const { dataApi, pageInput } = props; // Dataverse page+ const { pageInput } = props; // mock page+ const { dataApi, pageInput } = props; // Dataverse, pageInput unused+ void pageInput; // mark intentional-unused (NOT `void props`)+ ```+ **Forbidden:** `void props;` or any pattern that omits `pageInput` from+ destructuring. The runner greps for+ `const { ... pageInput ... } = props` — `void props` is detected as missing+ the destructure and fails.- **React 17 + TypeScript** — all generated code- **Fluent UI V9** — `@fluentui/react-components` exclusively- DatePicker from `@fluentui/react-datepicker-compat`diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.mdindex 23c459632..c90912f81 100644--- a/plugins/model-apps/agents/genpage-planner.md+++ b/plugins/model-apps/agents/genpage-planner.md@@ -34,6 +34,29 @@ You will be invoked by the `/genpage` skill with a prompt that includes:---+## Workflow-log requirements (applies to every step below)++As you work through the steps, append a Phase 1 section to+`<working-dir>/workflow-log.md` (create the file if it doesn't exist). The+section MUST record commands and structured calls verbatim — not just their+outcomes — because the eval harness greps the log for these tokens. Concretely:++- Every shell command invocation is recorded on its own line as+ `` `node --version` `` / `` `pac help` `` / `` `pac auth list` `` / `` `pac model list-tables --search '<term>'` ``. Include the literal flag values. Result goes on the next line.+- Every `AskUserQuestion` call is recorded as+ `AskUserQuestion: <question text> → <selected option>`. The literal string+ `AskUserQuestion` is required.+- The plan-presentation call is recorded as `EnterPlanMode called` followed+ by the user's response (`approved` / `revised`).+- The PAC CLI version output is recorded explicitly (the assertion checks+ for `>= 2.7.0`-shaped text — `PAC CLI Version 2.7.x` is the canonical+ form).++Decisions and outcomes can be summarized at the end of the section, but they+do **not** substitute for command-level entries. See an existing fixture+(`evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md`)+for the expected format.+## Step 1 — Validate PrerequisitesRun these checks (first invocation per session only). Run each command separately —diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.mdnew file mode 100644index 000000000..396e7d723--- /dev/null+++ b/plugins/model-apps/docs/architecture.md@@ -0,0 +1,193 @@+# Model Apps Plugin — Architecture++How `/genpage` is wired together. One page, ASCII diagrams. For per-component+behavioral specs, see `AGENTS.md`.++## High-level flow++```+ User invokes /genpage+ │+ v+ ┌────────────────────────┐+ │ skills/genpage/ │+ │ SKILL.md │ <-- orchestrator+ │ (the "skill") │+ └────────────┬───────────┘+ │+ ┌──────────────────┼──────────────────────────────┐+ v v v+ ┌────────────────┐ ┌────────────────┐ ┌────────────────────┐+ │ genpage- │ │ genpage- │ │ genpage- │+ │ planner │ │ entity-builder │ │ page-builder │+ │ (Task agent) │ │ (Task agent) │ │ (Task agent — N×) │+ └────────────────┘ └────────────────┘ └────────────────────┘+ │ │ │+ │ v │+ │ ┌────────────────────────┐ │+ │ │ scripts/ (Node CLIs) │ │+ │ │ check-auth.js │ │+ │ │ create-table.js │ │+ │ │ add-column.js │ │+ │ │ create-relationship.js│ │+ │ │ create-record.js │ │+ │ │ create-solution.js │ │+ │ │ dataverse-request.js │ │+ │ └─────────────┬──────────┘ │+ │ │ │+ │ v │+ │ ┌────────────────────────┐ │+ │ │ lib/dataverse-auth.js │ │+ │ │ (az + Web API HTTP) │ │+ │ └────────────────────────┘ │+ │ │+ └──────────────── genpage-plan.md ────────────────┘+ (machine-readable contract)+```++The orchestrator never inlines planner/builder logic — it dispatches via+`Task` and waits for the agent to return. The plan document is the contract:+the planner writes it; subsequent phases (and other agents) read it.++## Edit flow++```+ User invokes /genpage (edit intent)+ │+ v+ ┌────────────────────────┐+ │ skills/genpage/ │+ │ SKILL.md │+ │ edit-flow.md │ <-- loaded conditionally+ └────────────┬───────────┘+ │+ pac model list+ pac model genpage list+ pac model genpage download+ │+ v+ ┌────────────────────────┐+ │ <working-dir>/ │+ │ <page-id>/page.tsx │+ │ <page-id>/config.json│+ │ <page-id>/prompt.txt │+ └────────────┬───────────┘+ │+ v+ ┌────────────────────────┐+ │ genpage-edit-planner │ <-- Task agent+ │ (writes │ reads downloaded artifacts+ │ genpage-edit-plan.md) │+ └────────────┬───────────┘+ │+ v+ Orchestrator applies edits inline (Edit tool)+ on <working-dir>/<page-id>/page.tsx+ │+ v+ pac model genpage upload --page-id ...+```++## Working directory layout++Every `/genpage` run creates a kebab-case working directory with this layout:++```+<working-dir>/+ package.json <-- Phase 0.5 (generate-page-manifest.js)+ genpage.d.ts <-- Phase 0.5 (ambient Xrm + window cache types)+ genpage-plan.md <-- Phase 1 (planner writes; contract for later)+ entity-creation-log.md <-- Phase 2b (if entities created)+ RuntimeTypes.ts <-- Phase 4 (pac model genpage generate-types)+ <page>.tsx <-- Phase 5 (page-builder writes; one per page)+ workflow-log.md <-- written incrementally across all phases+```++The deployed artifact is just `<page>.tsx`. Everything else is local-dev+scaffolding that helps the developer keep iterating without re-running the+full skill.++## Where the plugin lives++```+plugins/model-apps/+├── .claude-plugin/plugin.json <-- version, name, keywords+├── AGENTS.md / CLAUDE.md <-- agent guidance (this is the source)+├── README.md <-- user-facing intro+├── CHANGELOG.md <-- Keep-a-Changelog+├── docs/+│ └── architecture.md <-- this file+├── skills/+│ └── genpage/+│ ├── SKILL.md <-- orchestrator phases (always loaded)+│ ├── edit-flow.md <-- conditional: edit path+│ └── verify-flow.md <-- conditional: browser verify path+├── agents/+│ ├── genpage-planner.md+│ ├── genpage-entity-builder.md+│ ├── genpage-page-builder.md+│ └── genpage-edit-planner.md+├── references/ <-- read on demand by agents+│ ├── rules.md <-- code-gen rules (page-builder hot path)+│ ├── plan-schema.md <-- plan doc contract+│ ├── data-caching.md <-- Rule 15 list/detail pattern+│ ├── localization.md <-- multi-language + RTL pattern+│ ├── supported-dependencies.md <-- v2.2: package.json input list+│ ├── troubleshooting.md <-- deploy / runtime / env issues+│ └── verified-icons.txt <-- ~5000 Fluent icon names+├── samples/ <-- 11 sample .tsx files (1-11)+└── scripts/+ ├── check-auth.js <-- pre-flight: az + pac + WhoAmI+ ├── dataverse-request.js <-- generic Web API wrapper+ ├── create-table.js+ ├── add-column.js+ ├── create-relationship.js+ ├── create-record.js+ ├── create-solution.js+ ├── add-to-solution.js+ ├── generate-page-manifest.js <-- v2.2: writes package.json + genpage.d.ts+ ├── regenerate-verified-icons.js+ ├── launch-playwright-mcp.js+ ├── lib/+ │ ├── dataverse-auth.js <-- shared az auth + HTTP helpers+ │ └── supported-dependencies.js <-- v2.2: deps single source of truth+ └── tests/ <-- node --test coverage+```++## The plan document as a contract++The planner writes `genpage-plan.md` once. Every later phase reads it; nothing+else passes state.++Key sections the orchestrator and other agents rely on:++| Section | Read by | Purpose |+|---------|---------|---------|+| `## Environment` (Solution + Publisher Prefix) | entity-builder | Solution scoping + prefix construction |+| `## Entity Creation Required` | orchestrator (Phase 2 gate) + entity-builder | Whether to invoke entity-builder; what to create |+| `## Existing Entities` | orchestrator (Phase 4) | Which entities feed `pac model genpage generate-types` |+| `## Pages` | orchestrator (Phase 5) | How many builders to dispatch; target filenames |+| `## Per-Page Specifications` | each page-builder | Each builder reads ONLY its own page's spec |+| `## Relevant Samples` | each page-builder | Closest-match sample to read for structural reference |+| `## Localization` | page-builder | Whether to load `references/localization.md` |++The schema is enforced by `references/plan-schema.md` and validated by+`evals/model-apps/genpage/run-layer-1.js`.++## Eval suite++Three layers, graded against captured fixtures:++```+fixtures/<eval-id>-<slug>/+ *.tsx <-- Layer 2 grades these (code assertions)+ workflow-log.md <-- Layer 1 grades this (workflow assertions)+ genpage-plan.md <-- Layer 1 grades this (plan-schema + Environment)+ entity-creation-log.md <-- Layer 1 grades this (prefix discipline)+```++Layer 1 (`run-layer-1.js`) and Layer 2 (`run-layer-2.js`) emit TAP v13. Both+runners are stateless — they read fixtures, grep + structural-check, write+results. CI can run both in seconds. Layer 3 (UX rubric) stays manual.++See `evals/model-apps/genpage/EVAL_GUIDE.md` for the full grading flow.diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex 379c8eea9..7cd33991a 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -91,6 +91,23 @@ export default GeneratedComponent;- Root container is flex column; use flex properties to fill space- `boxSizing: border-box`; images: `max-width: 100%, height: auto`- NEVER use `100vh`/`100vw`+- **Media queries go INSIDE the slot they modify** — never as a top-level+ `makeStyles` key. Griffel compiles each top-level key as an independent+ class, so a top-level `'@media (...)'` slot generates an unused class+ (its overrides never apply) and also fails type-checking. Nest the query+ in each slot and override only that slot's properties:+```typescript+const useStyles = makeStyles({+ // CORRECT: @media nested inside the slot+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ '@media (max-width: 768px)': { gridTemplateColumns: '1fr' },+ },+ // WRONG: @media as a top-level key reaching into other slots+ // '@media (max-width: 768px)': { grid: { gridTemplateColumns: '1fr' } },+});+```### Page Layout- Page-level functions (nav, search, filters) in header opposite title@@ -572,3 +589,27 @@ const useStyles = makeStyles({const styles = useStyles();<div className={styles.container}>```++### 4. Media Queries as Top-Level makeStyles Keys+Each top-level `makeStyles` key is compiled to an independent class. A media+query placed at the top level becomes a class literally named+`@media (...)`, whose nested slot overrides are never applied to any element+— the responsive behavior silently does nothing, and it fails type-checking+(`'<prop>' does not exist in type 'string[]'` when a slot name collides with a+CSS shorthand). Nest the query inside each slot instead.+```typescript+// Error: media query as a top-level key, reaching into other slots+const useStyles = makeStyles({+ grid: { display: "grid", gridTemplateColumns: "repeat(3, 1fr)" },+ "@media (max-width: 768px)": { grid: { gridTemplateColumns: "1fr" } }+});++// Fix: nest the media query inside the slot it modifies+const useStyles = makeStyles({+ grid: {+ display: "grid",+ gridTemplateColumns: "repeat(3, 1fr)",+ "@media (max-width: 768px)": { gridTemplateColumns: "1fr" }+ }+});+```diff --git a/plugins/model-apps/references/supported-dependencies.md b/plugins/model-apps/references/supported-dependencies.mdnew file mode 100644index 000000000..818e9a422--- /dev/null+++ b/plugins/model-apps/references/supported-dependencies.md@@ -0,0 +1,70 @@+# Supported Dependencies++The list of npm packages the genux runtime supports for generated pages.++**Scope:** Versions here are used by `scripts/generate-page-manifest.js` to+populate the `package.json` written into each working dir during Phase 0.5.+This makes the working dir installable (`npm install`) so VSCode IntelliSense,+type-checking, and "go to definition" work after generation.++**Source of truth:** This doc tracks+`scripts/lib/supported-dependencies.js`. When the upstream genux runtime team+publishes an authoritative version list, update that file — this doc and the+generator both read from there.++## Confidence levels++| Confidence | Meaning |+|------------|---------|+| `pinned` | Locked to a specific version by a definitive source (regenerate-verified-icons.js for `@fluentui/[email protected]`, the genux runtime for React 17). |+| `compatible` | Reasonable default that works with the genux runtime today but may not be the exact patch version the runtime ships. Editor/type-check accuracy is high; runtime behavior may differ in rare cases. |++## Runtime dependencies++| Package | Version | Confidence | Notes |+|---------|---------|------------|-------|+| `react` | `17.0.2` | pinned | Genux runtime is React 17. |+| `react-dom` | `17.0.2` | pinned | Pairs with `[email protected]`. |+| `@fluentui/react-components` | `^9.54.0` | compatible | Fluent UI V9 — APIs used by samples stable since 9.40. |+| `@fluentui/react-icons` | `2.0.326` | pinned | Pinned by `scripts/regenerate-verified-icons.js` to keep `references/verified-icons.txt` in sync. |+| `@fluentui/react-datepicker-compat` | `^0.4.50` | compatible | V9 compat — used only when the page has a DatePicker. |+| `@fluentui/react-timepicker-compat` | `^0.2.40` | compatible | V9 compat — used only when the page has a TimePicker. |+| `d3` | `^7.8.5` | compatible | D3 v7+ required for `d3.group()`. Used only by chart-bearing pages. |++## Dev dependencies++| Package | Version | Confidence | Notes |+|---------|---------|------------|-------|+| `typescript` | `^5.4.0` | compatible | Any TS 5.x works for editor support. |+| `@types/react` | `^17.0.80` | compatible | |+| `@types/react-dom` | `^17.0.25` | compatible | |+| `@types/d3` | `^7.4.3` | compatible | Include only when the page uses D3. |++## Features++The generator includes feature-specific deps only when the page uses them.++| Feature flag | Adds (runtime) | Adds (dev) |+|--------------|----------------|------------|+| `charts` | `d3` | `@types/d3` |+| `datepicker` | `@fluentui/react-datepicker-compat` | — |+| `timepicker` | `@fluentui/react-timepicker-compat` | — |++Pass features to the generator:++```bash+node scripts/generate-page-manifest.js <working-dir> <page-slug> --features charts,datepicker+```++The generator passes the list through `buildDependencyMap()` /+`buildDevDependencyMap()` in `scripts/lib/supported-dependencies.js`.++## Updating versions++When upstream confirms versions or a runtime upgrade lands:++1. Edit `scripts/lib/supported-dependencies.js` — change the `version` field and (if applicable) flip `confidence` from `compatible` to `pinned`.+2. Re-run `node --test plugins/model-apps/scripts/tests/generate-page-manifest.test.js` — the tests assert the generated manifest's dependency map, feature-flag handling, and `--force` behavior.+3. Update this doc to reflect the new versions (the table is hand-maintained from the JS module — a small sync script could automate it later).+4. Bump the plugin minor or patch version in `.claude-plugin/plugin.json`.+5. CHANGELOG entry under the appropriate version section.diff --git a/plugins/model-apps/samples/11-kanban-with-dnd.tsx b/plugins/model-apps/samples/11-kanban-with-dnd.tsxnew file mode 100644index 000000000..67c34d967--- /dev/null+++ b/plugins/model-apps/samples/11-kanban-with-dnd.tsx@@ -0,0 +1,287 @@+import * as React from 'react';+import {+ makeStyles,+ tokens,+ Card,+ CardHeader,+ Body1,+ Caption1,+ Text,+ Badge,+ Spinner,+ MessageBar,+ MessageBarBody,+} from '@fluentui/react-components';+import {+ ClipboardTaskRegular,+ PlayRegular,+ CheckmarkCircleRegular,+} from '@fluentui/react-icons';+import { GeneratedComponentProps, Task } from './RuntimeTypes';++// Sample: kanban board with native HTML5 drag-and-drop.+// Demonstrates:+// - Rule: no external DnD library (no react-dnd / @dnd-kit / react-beautiful-dnd)+// - Status updates persist via dataApi.updateRow on drop+// - Native HTML5 events: onDragStart, onDragOver (with preventDefault),+// onDrop, onDragEnd+// - Three columns mapped to task statuscode values (Not Started=2,+// In Progress=3, Completed=5 — Dataverse defaults for the `task` entity;+// see task_statuscode in RuntimeTypes)+// - Window cache (window.__genpage_tasks_v1) for the inline IIFE pattern+// - Realistic empty / loading / error states+// - Logical CSS properties (paddingInline, paddingBlock, marginInlineStart)+// - Unsized Fluent icons (ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular)+// - export default GeneratedComponent and pageInput destructured++// ---------- Constants ----------++const STATUS_NOT_STARTED = 2 as const;+const STATUS_IN_PROGRESS = 3 as const;+const STATUS_COMPLETED = 5 as const;++type StatusValue = typeof STATUS_NOT_STARTED | typeof STATUS_IN_PROGRESS | typeof STATUS_COMPLETED;++interface Column {+ key: StatusValue;+ label: string;+ icon: React.ReactNode;+ accent: 'brand' | 'warning' | 'success';+}++const COLUMNS: Column[] = [+ { key: STATUS_NOT_STARTED, label: 'To Do', icon: <ClipboardTaskRegular />, accent: 'brand' },+ { key: STATUS_IN_PROGRESS, label: 'In Progress', icon: <PlayRegular />, accent: 'warning' },+ { key: STATUS_COMPLETED, label: 'Done', icon: <CheckmarkCircleRegular />, accent: 'success' },+];++// ---------- Styles ----------++const useStyles = makeStyles({+ root: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ paddingInline: tokens.spacingHorizontalL,+ paddingBlock: tokens.spacingVerticalL,+ gap: tokens.spacingVerticalM,+ boxSizing: 'border-box',+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalS,+ },+ board: {+ display: 'grid',+ gridTemplateColumns: 'repeat(3, minmax(240px, 1fr))',+ gap: tokens.spacingHorizontalM,+ flex: 1,+ overflowX: 'auto',+ overflowY: 'hidden',+ },+ column: {+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ paddingInline: tokens.spacingHorizontalS,+ paddingBlock: tokens.spacingVerticalS,+ backgroundColor: tokens.colorNeutralBackground2,+ borderRadius: tokens.borderRadiusMedium,+ minHeight: 0,+ },+ columnHover: {+ backgroundColor: tokens.colorBrandBackground2,+ outline: `2px dashed ${tokens.colorBrandStroke1}`,+ },+ columnHeader: {+ display: 'flex',+ alignItems: 'center',+ gap: tokens.spacingHorizontalXS,+ paddingBlockEnd: tokens.spacingVerticalXS,+ },+ columnBody: {+ flex: 1,+ overflowY: 'auto',+ display: 'flex',+ flexDirection: 'column',+ gap: tokens.spacingVerticalS,+ minHeight: 0,+ },+ card: {+ padding: tokens.spacingHorizontalS,+ cursor: 'grab',+ },+ cardDragging: { opacity: 0.5 },+ emptyHint: {+ color: tokens.colorNeutralForeground3,+ fontStyle: 'italic',+ textAlign: 'center',+ paddingBlock: tokens.spacingVerticalL,+ },+});++// ---------- Component ----------++const GeneratedComponent = (props: GeneratedComponentProps) => {+ const { dataApi, pageInput } = props;+ void pageInput; // board does not consume incoming pageInput+ const styles = useStyles();++ const [tasks, setTasks] = React.useState<Task[]>([]);+ const [loading, setLoading] = React.useState(true);+ const [error, setError] = React.useState<string | null>(null);+ const [draggingId, setDraggingId] = React.useState<string | null>(null);+ const [hoverColumn, setHoverColumn] = React.useState<StatusValue | null>(null);++ React.useEffect(() => {+ (async () => {+ const cacheKey = '__genpage_tasks_v1';+ const w = window as unknown as Record<string, Task[] | undefined>;+ if (w[cacheKey]) {+ setTasks(w[cacheKey] as Task[]);+ setLoading(false);+ return;+ }+ try {+ const result = await dataApi.queryTable<Task>('task', {+ select: ['activityid', 'subject', 'description', 'statuscode', 'prioritycode'],+ top: 200,+ });+ // queryTable returns DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() } — access records via .rows+ w[cacheKey] = result.rows;+ setTasks(result.rows);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setLoading(false);+ }+ })();+ }, [dataApi]);++ const handleDragStart = (e: React.DragEvent<HTMLDivElement>, taskId: string) => {+ e.dataTransfer.effectAllowed = 'move';+ e.dataTransfer.setData('text/plain', taskId);+ setDraggingId(taskId);+ };++ const handleDragEnd = () => {+ setDraggingId(null);+ setHoverColumn(null);+ };++ const handleDragOver = (e: React.DragEvent<HTMLDivElement>, columnKey: StatusValue) => {+ // preventDefault is required to allow drop+ e.preventDefault();+ e.dataTransfer.dropEffect = 'move';+ if (hoverColumn !== columnKey) setHoverColumn(columnKey);+ };++ const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {+ // Only clear hover state when leaving the column entirely (not entering a child)+ if (e.currentTarget === e.target) setHoverColumn(null);+ };++ const handleDrop = async (+ e: React.DragEvent<HTMLDivElement>,+ targetStatus: StatusValue,+ ) => {+ e.preventDefault();+ const taskId = e.dataTransfer.getData('text/plain');+ setHoverColumn(null);+ if (!taskId) return;++ const current = tasks.find((t) => t.activityid === taskId);+ if (!current || current.statuscode === targetStatus) return;++ // Optimistic update + window cache sync; rollback on failure.+ const nextTasks: Task[] = tasks.map((t) =>+ t.activityid === taskId ? { ...t, statuscode: targetStatus } : t,+ );+ const prevTasks = tasks;+ setTasks(nextTasks);+ const w = window as unknown as Record<string, Task[] | undefined>;+ w.__genpage_tasks_v1 = nextTasks;++ try {+ await dataApi.updateRow('task', taskId, { statuscode: targetStatus });+ } catch (err) {+ setTasks(prevTasks);+ w.__genpage_tasks_v1 = prevTasks;+ setError(err instanceof Error ? err.message : String(err));+ }+ };++ if (loading) return <Spinner label="Loading tasks..." />;+ if (error) return (+ <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar>+ );++ return (+ <div className={styles.root}>+ <div className={styles.header}>+ <ClipboardTaskRegular />+ <Text size={500} weight="semibold">Task Board ({tasks.length})</Text>+ </div>++ <div className={styles.board}>+ {COLUMNS.map((col) => {+ const items = tasks.filter((t) => t.statuscode === col.key);+ const columnClass = `${styles.column} ${+ hoverColumn === col.key ? styles.columnHover : ''+ }`;+ return (+ <div+ key={col.key}+ className={columnClass}+ onDragOver={(e) => handleDragOver(e, col.key)}+ onDragLeave={handleDragLeave}+ onDrop={(e) => handleDrop(e, col.key)}+ aria-label={col.label}+ >+ <div className={styles.columnHeader}>+ {col.icon}+ <Body1 weight="semibold">{col.label}</Body1>+ <Badge appearance="filled" color={col.accent}>{items.length}</Badge>+ </div>+ <div className={styles.columnBody}>+ {items.length === 0 ? (+ <Caption1 className={styles.emptyHint}>+ Drop tasks here+ </Caption1>+ ) : (+ items.map((task) => {+ const cardClass = `${styles.card} ${+ draggingId === task.activityid ? styles.cardDragging : ''+ }`;+ return (+ <Card+ key={task.activityid}+ className={cardClass}+ draggable+ onDragStart={(e) => handleDragStart(e, task.activityid)}+ onDragEnd={handleDragEnd}+ aria-grabbed={draggingId === task.activityid}+ >+ <CardHeader+ header={+ <Body1 weight="semibold">{task.subject}</Body1>+ }+ />+ {task.description && (+ <Caption1>{task.description}</Caption1>+ )}+ </Card>+ );+ })+ )}+ </div>+ </div>+ );+ })}+ </div>+ </div>+ );+};++export default GeneratedComponent;diff --git a/plugins/model-apps/samples/6-comprehensive-form.tsx b/plugins/model-apps/samples/6-comprehensive-form.tsxindex bd4766aec..40ca63bec 100644--- a/plugins/model-apps/samples/6-comprehensive-form.tsx+++ b/plugins/model-apps/samples/6-comprehensive-form.tsx@@ -5,21 +5,20 @@ import { TimePicker } from "@fluentui/react-timepicker-compat";import { CheckmarkCircle20Filled, ErrorCircle20Filled } from "@fluentui/react-icons";const useStyles = makeStyles({- container: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalXL, padding: tokens.spacingHorizontalM, maxWidth: "800px", margin: "0 auto", width: "100%", boxSizing: "border-box", height: '100%', overflowY: 'auto' },- formSection: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL, borderRadius: tokens.borderRadiusMedium, border: `1px solid ${tokens.colorNeutralStroke2}`, backgroundColor: tokens.colorNeutralBackground1 },+ container: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalXL, padding: tokens.spacingHorizontalM, maxWidth: "800px", margin: "0 auto", width: "100%", boxSizing: "border-box", height: '100%', overflowY: 'auto', "@media (max-width: 768px)": { padding: tokens.spacingHorizontalS, gap: tokens.spacingVerticalL }, "@media (max-width: 480px)": { padding: tokens.spacingHorizontalXS } },+ formSection: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL, borderRadius: tokens.borderRadiusMedium, border: `1px solid ${tokens.colorNeutralStroke2}`, backgroundColor: tokens.colorNeutralBackground1, "@media (max-width: 768px)": { padding: tokens.spacingHorizontalM }, "@media (max-width: 480px)": { padding: tokens.spacingHorizontalS } },sectionHeader: { marginBottom: tokens.spacingVerticalM, paddingBottom: tokens.spacingVerticalS, borderBottom: `1px solid ${tokens.colorNeutralStroke2}` },formGrid: { display: "grid", gridTemplateColumns: "1fr", gap: tokens.spacingVerticalL, width: "100%" },- twoColumnGrid: { gridTemplateColumns: "1fr 1fr", gap: tokens.spacingHorizontalL },+ twoColumnGrid: { gridTemplateColumns: "1fr 1fr", gap: tokens.spacingHorizontalL, "@media (max-width: 768px)": { gridTemplateColumns: "1fr", gap: tokens.spacingVerticalL } },radioGroupContainer: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalS },- radioGroupHorizontal: { flexDirection: "row", flexWrap: "wrap", gap: tokens.spacingHorizontalL },+ radioGroupHorizontal: { flexDirection: "row", flexWrap: "wrap", gap: tokens.spacingHorizontalL, "@media (max-width: 768px)": { flexDirection: "column", gap: tokens.spacingVerticalS } },sliderContainer: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalXS, width: "100%" },sliderValue: { color: tokens.colorNeutralForeground2, fontSize: tokens.fontSizeBase200, textAlign: "right" },- buttonGroup: { display: "flex", gap: tokens.spacingHorizontalM, justifyContent: "flex-end", alignItems: "center", marginTop: tokens.spacingVerticalL, paddingTop: tokens.spacingVerticalM, borderTop: `1px solid ${tokens.colorNeutralStroke2}` },+ buttonGroup: { display: "flex", gap: tokens.spacingHorizontalM, justifyContent: "flex-end", alignItems: "center", marginTop: tokens.spacingVerticalL, paddingTop: tokens.spacingVerticalM, borderTop: `1px solid ${tokens.colorNeutralStroke2}`, "@media (max-width: 768px)": { flexDirection: "column-reverse", gap: tokens.spacingVerticalS } },messageContainer: { marginBottom: tokens.spacingVerticalM },validationSummary: { padding: tokens.spacingHorizontalM, borderRadius: tokens.borderRadiusSmall, backgroundColor: tokens.colorPaletteRedBackground1, border: `1px solid ${tokens.colorPaletteRedBorder1}` },comboboxListbox: { backgroundColor: tokens.colorNeutralBackground1, border: `1px solid ${tokens.colorNeutralStroke1}` },- "@media (max-width: 768px)": { container: { padding: tokens.spacingHorizontalS, gap: tokens.spacingVerticalL }, formSection: { padding: tokens.spacingHorizontalM }, twoColumnGrid: { gridTemplateColumns: "1fr", gap: tokens.spacingVerticalL }, radioGroupHorizontal: { flexDirection: "column", gap: tokens.spacingVerticalS }, buttonGroup: { flexDirection: "column-reverse", gap: tokens.spacingVerticalS } },- "@media (max-width: 480px)": { container: { padding: tokens.spacingHorizontalXS }, formSection: { padding: tokens.spacingHorizontalS } }+ datePicker: { width: "100%" }});interface FormData { textInput: string; textArea: string; comboboxValue: string; spinButtonValue: number; checkboxChecked: boolean; sliderValue: number; switchEnabled: boolean; radioSelection: string; email: string; phone: string; dateOfBirth: Date | null; preferredContactTime: string; }diff --git a/plugins/model-apps/samples/7-responsive-cards.tsx b/plugins/model-apps/samples/7-responsive-cards.tsxindex 3e6188121..b79cc2028 100644--- a/plugins/model-apps/samples/7-responsive-cards.tsx+++ b/plugins/model-apps/samples/7-responsive-cards.tsx@@ -3,9 +3,9 @@ import { makeStyles, tokens, Button, Text, Caption1, Subtitle1, Body1, mergeClasimport { MoreHorizontal20Regular } from '@fluentui/react-icons';const useStyles = makeStyles({- container: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXL, padding: tokens.spacingHorizontalM, width: '100%', boxSizing: 'border-box' },- cardsGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: tokens.spacingVerticalL, width: '100%' },- card: { width: '100%', maxWidth: '480px', height: 'fit-content', cursor: 'pointer', transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out', '&:hover': { transform: 'translateY(-2px)', boxShadow: tokens.shadow8 }, '&:focus-visible': { outline: `2px solid ${tokens.colorBrandBackground}`, outlineOffset: '2px' } },+ container: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXL, padding: tokens.spacingHorizontalM, width: '100%', boxSizing: 'border-box', '@media (max-width: 768px)': { padding: tokens.spacingHorizontalS } },+ cardsGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: tokens.spacingVerticalL, width: '100%', '@media (max-width: 768px)': { gridTemplateColumns: '1fr', gap: tokens.spacingVerticalM } },+ card: { width: '100%', maxWidth: '480px', height: 'fit-content', cursor: 'pointer', transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out', '&:hover': { transform: 'translateY(-2px)', boxShadow: tokens.shadow8 }, '&:focus-visible': { outline: `2px solid ${tokens.colorBrandBackground}`, outlineOffset: '2px' }, '@media (max-width: 768px)': { maxWidth: '100%' } },sectionHeader: { marginBottom: tokens.spacingVerticalM },sectionTitle: { marginBottom: tokens.spacingVerticalXS, display: 'block' },sectionDescription: { color: tokens.colorNeutralForeground2, marginBottom: tokens.spacingVerticalM, display: 'block' },@@ -13,7 +13,6 @@ const useStyles = makeStyles({logo: { borderRadius: tokens.borderRadiusSmall, width: '48px', height: '48px', backgroundColor: tokens.colorNeutralBackground3, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '24px' },cardHeader: { margin: 0, fontWeight: tokens.fontWeightSemibold },cardCaption: { color: tokens.colorNeutralForeground3, display: 'block' },- '@media (max-width: 768px)': { container: { padding: tokens.spacingHorizontalS }, cardsGrid: { gridTemplateColumns: '1fr', gap: tokens.spacingVerticalM }, card: { maxWidth: '100%' } }});const SectionHeader: React.FC<{ title: string; description: string; titleId: string; descriptionId: string; }> = ({ title, description, titleId, descriptionId }) => {diff --git a/plugins/model-apps/scripts/capture-fixture.js b/plugins/model-apps/scripts/capture-fixture.jsnew file mode 100644index 000000000..9293f4309--- /dev/null+++ b/plugins/model-apps/scripts/capture-fixture.js@@ -0,0 +1,311 @@+#!/usr/bin/env node+'use strict';++// Captures a /genpage working directory into an eval fixture folder.+//+// Copies the agent-produced artifacts (.tsx, RuntimeTypes.ts, workflow-log.md,+// genpage-plan.md, genpage-edit-plan.md, entity-creation-log.md) into+// evals/model-apps/genpage/fixtures/<eval-id>-<slug>/, skipping local-dev+// scaffolding (package.json, genpage.d.ts) and build artifacts (node_modules,+// dist, *.log).+//+// After copying, runs both Layer 1 and Layer 2 against the new fixture and+// prints the pass/fail counts. Capture exit code stays 0 regardless of runner+// results — drift detection is diagnostic, not failure.+//+// Usage:+// node capture-fixture.js --working-dir <path> --eval <id> --slug <slug> [--force] [--skip-verify]+//+// Flags:+// --working-dir <path> Absolute or relative path to the /genpage working dir+// --eval <id> Numeric eval id (must exist in evals.json)+// --slug <slug> Kebab-case slug for the fixture folder name+// --force Overwrite an existing fixture directory+// --skip-verify Skip running Layer 1 / Layer 2 after capture+//+// Exit codes:+// 0 success (capture written; runner results are informational only)+// 1 invalid arguments+// 2 I/O error (working dir missing, etc.)++const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');+const FIXTURES_DIR = path.join(+ REPO_ROOT,+ 'evals',+ 'model-apps',+ 'genpage',+ 'fixtures',+);+const EVALS_JSON = path.join(+ REPO_ROOT,+ 'evals',+ 'model-apps',+ 'genpage',+ 'evals.json',+);+const LAYER1_SCRIPT = path.join(+ REPO_ROOT,+ 'evals',+ 'model-apps',+ 'genpage',+ 'run-layer-1.js',+);+const LAYER2_SCRIPT = path.join(+ REPO_ROOT,+ 'evals',+ 'model-apps',+ 'genpage',+ 'run-layer-2.js',+);++const COPY_ALLOWLIST = [+ /\.tsx$/,+ /\.md$/,+ /^RuntimeTypes\.ts$/i,+];++// Files we never want in fixtures — they're either local-dev scaffolding+// generated by Phase 0.5 (not the agent's output) or build artifacts.+const DENYLIST_FILES = new Set([+ 'package.json',+ 'package-lock.json',+ 'genpage.d.ts',+ '.DS_Store',+ 'Thumbs.db',+]);+const DENYLIST_DIRS = new Set([+ 'node_modules',+ 'dist',+ 'build',+ '.cache',+ '.tmp',+ '.next',+]);++function parseArgs(argv) {+ const args = {+ workingDir: null,+ eval: null,+ slug: null,+ force: false,+ skipVerify: false,+ };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ switch (a) {+ case '--working-dir':+ args.workingDir = argv[++i];+ break;+ case '--eval':+ args.eval = parseInt(argv[++i], 10);+ if (Number.isNaN(args.eval)) throw new Error('--eval requires a numeric id');+ break;+ case '--slug':+ args.slug = argv[++i];+ break;+ case '--force':+ args.force = true;+ break;+ case '--skip-verify':+ args.skipVerify = true;+ break;+ case '--help':+ case '-h':+ printHelp();+ process.exit(0);+ default:+ throw new Error(`Unknown argument: ${a}`);+ }+ }+ if (!args.workingDir) throw new Error('--working-dir is required');+ if (args.eval === null) throw new Error('--eval is required');+ if (!args.slug) throw new Error('--slug is required');+ if (!/^[a-z][a-z0-9-]*$/.test(args.slug)) {+ throw new Error(`--slug must be kebab-case (got: ${args.slug})`);+ }+ return args;+}++function printHelp() {+ console.log(`Usage: capture-fixture.js --working-dir <path> --eval <id> --slug <slug> [options]++Required:+ --working-dir <path> Path to a /genpage working dir+ --eval <id> Numeric eval id (must exist in evals.json)+ --slug <slug> Kebab-case slug for the fixture folder++Options:+ --force Overwrite an existing fixture+ --skip-verify Skip running Layer 1 / Layer 2 after capture+ --help Show this message++Copies agent-produced artifacts (.tsx, RuntimeTypes.ts, *.md files) into:+ evals/model-apps/genpage/fixtures/<eval-id>-<slug>/++Excluded automatically: package.json, genpage.d.ts (Phase 0.5 scaffolding),+node_modules/, dist/, build/, *.log files.+`);+}++function evalExists(evalId) {+ const data = JSON.parse(fs.readFileSync(EVALS_JSON, 'utf8'));+ return data.evals.some((e) => e.id === evalId);+}++function shouldCopyFile(name) {+ if (DENYLIST_FILES.has(name)) return false;+ if (name.endsWith('.log')) return false;+ return COPY_ALLOWLIST.some((re) => re.test(name));+}++function copyAllowedFiles(srcDir, dstDir) {+ fs.mkdirSync(dstDir, { recursive: true });+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });+ const copied = [];+ const skipped = [];+ for (const entry of entries) {+ const srcPath = path.join(srcDir, entry.name);+ if (entry.isDirectory()) {+ if (DENYLIST_DIRS.has(entry.name)) {+ skipped.push({ name: entry.name + '/', reason: 'denylisted directory' });+ continue;+ }+ // Don't recurse — /genpage working dirs are flat.+ // Exception: edit-flow downloads put files under <page-id>/, but we+ // capture those separately if needed by passing the page-id dir directly.+ skipped.push({ name: entry.name + '/', reason: 'subdirectory (not captured)' });+ continue;+ }+ if (!shouldCopyFile(entry.name)) {+ skipped.push({ name: entry.name, reason: 'not in allowlist or denylisted' });+ continue;+ }+ const dstPath = path.join(dstDir, entry.name);+ fs.copyFileSync(srcPath, dstPath);+ copied.push(entry.name);+ }+ return { copied, skipped };+}++function runRunner(scriptPath, evalId) {+ const result = spawnSync(+ process.execPath,+ [scriptPath, '--eval', String(evalId)],+ { encoding: 'utf8' },+ );+ return {+ exitCode: result.status,+ stdout: result.stdout || '',+ stderr: result.stderr || '',+ };+}++function parseTapSummary(stdout) {+ const m = {+ tests: stdout.match(/^# tests\s+(\d+)/m)?.[1],+ pass: stdout.match(/^# pass\s+(\d+)/m)?.[1],+ fail: stdout.match(/^# fail\s+(\d+)/m)?.[1],+ skip: stdout.match(/^# skip\s+(\d+)/m)?.[1],+ };+ return {+ tests: Number(m.tests ?? 0),+ pass: Number(m.pass ?? 0),+ fail: Number(m.fail ?? 0),+ skip: Number(m.skip ?? 0),+ };+}++function extractFailures(stdout) {+ // Pull only indented assertion failures (" not ok N - <text>"), excluding+ // the non-indented fixture-level result lines emitted by the TAP reporter.+ const lines = stdout.split('\n');+ return lines+ .filter((l) => /^\s{4}not ok \d+ - /.test(l))+ .map((l) => l.trim());+}++function main() {+ let args;+ try {+ args = parseArgs(process.argv.slice(2));+ } catch (err) {+ console.error(`error: ${err.message}`);+ process.exit(1);+ }++ const workingDir = path.resolve(args.workingDir);+ if (!fs.existsSync(workingDir) || !fs.statSync(workingDir).isDirectory()) {+ console.error(`error: working directory does not exist or is not a directory: ${workingDir}`);+ process.exit(2);+ }++ if (!evalExists(args.eval)) {+ console.error(`error: no eval with id ${args.eval} in evals.json`);+ process.exit(1);+ }++ const fixtureName = `${args.eval}-${args.slug}`;+ const fixtureDir = path.join(FIXTURES_DIR, fixtureName);++ if (fs.existsSync(fixtureDir)) {+ if (!args.force) {+ console.error(+ `error: fixture already exists: ${fixtureDir}\n` ++ ` pass --force to overwrite, or pick a different --slug`,+ );+ process.exit(2);+ }+ fs.rmSync(fixtureDir, { recursive: true, force: true });+ }++ const { copied, skipped } = copyAllowedFiles(workingDir, fixtureDir);++ if (copied.length === 0) {+ console.error(+ `error: no allowlisted files found in ${workingDir}\n` ++ ` expected at least one of: *.tsx, *.md, RuntimeTypes.ts`,+ );+ fs.rmSync(fixtureDir, { recursive: true, force: true });+ process.exit(2);+ }++ const summary = {+ eval: args.eval,+ slug: args.slug,+ fixtureDir,+ copied,+ skipped,+ };++ if (!args.skipVerify) {+ const layer1 = runRunner(LAYER1_SCRIPT, args.eval);+ const layer2 = runRunner(LAYER2_SCRIPT, args.eval);+ summary.layer1 = {+ ...parseTapSummary(layer1.stdout),+ failures: extractFailures(layer1.stdout),+ };+ summary.layer2 = {+ ...parseTapSummary(layer2.stdout),+ failures: extractFailures(layer2.stdout),+ };+ }++ console.log(JSON.stringify(summary, null, 2));+}++if (require.main === module) main();++module.exports = {+ parseArgs,+ shouldCopyFile,+ copyAllowedFiles,+ parseTapSummary,+ extractFailures,+ COPY_ALLOWLIST,+ DENYLIST_FILES,+ DENYLIST_DIRS,+};diff --git a/plugins/model-apps/scripts/generate-page-manifest.js b/plugins/model-apps/scripts/generate-page-manifest.jsnew file mode 100644index 000000000..3f4c053e7--- /dev/null+++ b/plugins/model-apps/scripts/generate-page-manifest.js@@ -0,0 +1,276 @@+#!/usr/bin/env node+'use strict';++// Writes two files into a working dir to make it editor-friendly:+// package.json — installable manifest with the deps from+// scripts/lib/supported-dependencies.js (Ask 2)+// genpage.d.ts — ambient global declarations only: `window.Xrm` and+// the bare `Xrm` identifier with the navigation/utility+// surface used by generative pages, plus the+// `__genpage_*` window cache-key index signature+// (Ask 3). `GeneratedComponentProps` is exported by+// RuntimeTypes.ts and is intentionally not re-declared+// here.+//+// Run by the /genpage orchestrator in Phase 0.5 (after working-dir creation).+// Idempotent by default — skips files that already exist. Pass --force to+// overwrite.+//+// Usage:+// node generate-page-manifest.js <working-dir> <page-slug> [--features <list>] [--force]+//+// Arguments:+// <working-dir> Path to the working directory (relative or absolute)+// <page-slug> Used as the package "name" field (e.g., "account-card-gallery")+//+// Flags:+// --features <list> Comma-separated feature flags to include extra deps.+// Supported: charts, datepicker, timepicker+// --force Overwrite existing files instead of preserving them.+//+// Exit codes:+// 0 success+// 1 invalid arguments+// 2 I/O error++const fs = require('node:fs');+const path = require('node:path');+const {+ RUNTIME_DEPENDENCIES,+ DEV_DEPENDENCIES,+ buildDependencyMap,+ buildDevDependencyMap,+ FEATURE_RUNTIME_KEYS,+} = require('./lib/supported-dependencies.js');++const VALID_FEATURES = new Set(Object.keys(FEATURE_RUNTIME_KEYS));++function parseArgs(argv) {+ const args = { positional: [], features: [], force: false };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--force') args.force = true;+ else if (a === '--features') {+ const list = argv[++i];+ if (!list) throw new Error('--features requires a comma-separated value');+ args.features = list.split(',').map((s) => s.trim()).filter(Boolean);+ } else if (a === '--help' || a === '-h') {+ printHelp();+ process.exit(0);+ } else if (a.startsWith('--')) {+ throw new Error(`Unknown flag: ${a}`);+ } else {+ args.positional.push(a);+ }+ }+ if (args.positional.length !== 2) {+ throw new Error('expected <working-dir> <page-slug> as positional arguments');+ }+ for (const f of args.features) {+ if (!VALID_FEATURES.has(f)) {+ throw new Error(`Unknown feature '${f}'. Valid: ${[...VALID_FEATURES].join(', ')}`);+ }+ }+ return args;+}++function printHelp() {+ console.log(`Usage: generate-page-manifest.js <working-dir> <page-slug> [options]++Options:+ --features <list> Comma-separated feature flags (charts, datepicker, timepicker)+ --force Overwrite existing package.json / genpage.d.ts+ --help Show this message++Writes package.json and genpage.d.ts into <working-dir>.+`);+}++function buildPackageJson(slug, features) {+ return {+ name: slug,+ private: true,+ version: '0.0.1',+ description: `Local development manifest for genpage '${slug}' (auto-generated by /genpage Phase 0.5).`,+ dependencies: buildDependencyMap(features),+ devDependencies: buildDevDependencyMap(features),+ // No scripts — the runtime owns build and deploy.+ // `pac model genpage upload` reads <page>.tsx directly.+ };+}++// Static ambient declarations for the genux runtime. Same content for every+// working dir — no parameterization.+function buildAmbientDeclarations() {+ return `// Auto-generated by /genpage Phase 0.5 (do not edit by hand).+//+// Provides type definitions for runtime globals injected by the Power Apps+// model-driven app shell. After this file exists alongside the page's .tsx,+// the page can use \`window.Xrm.Navigation.navigateTo(...)\` without+// \`(window as any).\` casts.+//+// Regenerate by running:+// node \${CLAUDE_PLUGIN_ROOT}/scripts/generate-page-manifest.js <dir> <slug> --force++export {};++declare global {+ /** Subset of Xrm v9 surface used by generative pages. Extend as needed. */+ interface XrmShape {+ Navigation: {+ navigateTo: (+ pageInput: XrmPageInput,+ navigationOptions?: { target?: 1 | 2 },+ ) => Promise<XrmNavigationResult>;+ openForm: (+ formOptions: { entityName: string; entityId?: string },+ formParameters?: Record<string, unknown>,+ ) => Promise<unknown>;+ openUrl: (url: string, options?: { target?: 1 | 2 }) => void;+ };+ Utility: {+ getGlobalContext: () => XrmGlobalContext;+ };+ }++ type XrmPageInput =+ | { pageType: 'entityrecord'; entityName: string; entityId?: string }+ | { pageType: 'entitylist'; entityName: string }+ | {+ pageType: 'custom';+ pageId: string;+ entityName?: string;+ recordId?: string;+ data?: Record<string, unknown>;+ }+ | {+ /** Cross-page navigation between generative pages — see rules.md PAGEREF_ placeholder. */+ pageType: 'generative';+ pageId: string;+ entityName?: string;+ recordId?: string;+ data?: Record<string, unknown>;+ };++ interface XrmNavigationResult {+ savedEntityReference?: Array<{ entityType: string; id: string; name?: string }>;+ }++ interface XrmGlobalContext {+ userSettings: {+ userId: string;+ userName: string;+ languageId: number;+ dateFormattingInfo?: Record<string, unknown>;+ };+ organizationSettings: {+ organizationId: string;+ languageId: number;+ baseCurrency?: { id: string };+ };+ getClientUrl: () => string;+ }++ interface Window {+ /** Provided by the model-driven app shell. */+ Xrm: XrmShape;+ }++ /**+ * Bare \`Xrm\` identifier (used by generated pages as \`Xrm.Navigation...\`+ * without the \`window.\` prefix). Same shape as \`window.Xrm\`.+ */+ const Xrm: XrmShape;++ /**+ * Per-page cache keys MUST follow the pattern \`__genpage_<entity>_<v>\`+ * (see references/data-caching.md). The string-key index signature lets+ * TypeScript accept dynamic cache reads/writes without \`(window as any)\`.+ */+ interface Window {+ [cacheKey: \`__genpage_\${string}\`]: unknown;+ }+}+`;+}++function writeIfAllowed(filePath, content, force) {+ if (fs.existsSync(filePath) && !force) {+ return { wrote: false, reason: 'exists (use --force to overwrite)' };+ }+ try {+ fs.writeFileSync(filePath, content);+ } catch (err) {+ const e = new Error(`failed to write ${filePath}: ${err.message}`);+ e.code = 'IO_ERROR';+ throw e;+ }+ return { wrote: true };+}++function main() {+ let args;+ try {+ args = parseArgs(process.argv.slice(2));+ } catch (err) {+ console.error(`error: ${err.message}`);+ process.exit(1);+ }++ const workingDir = path.resolve(args.positional[0]);+ const slug = args.positional[1];++ try {+ if (!fs.existsSync(workingDir)) {+ console.error(`error: working directory does not exist: ${workingDir}`);+ process.exit(2);+ }+ if (!fs.statSync(workingDir).isDirectory()) {+ console.error(`error: not a directory: ${workingDir}`);+ process.exit(2);+ }+ } catch (err) {+ console.error(`error: failed to stat working directory: ${err.message}`);+ process.exit(2);+ }++ if (!/^[a-z][a-z0-9-]*$/.test(slug)) {+ console.error(`error: page-slug must be kebab-case (got: ${slug})`);+ process.exit(1);+ }++ let pkgResult;+ let dtsResult;+ try {+ const pkg = buildPackageJson(slug, args.features);+ const pkgPath = path.join(workingDir, 'package.json');+ pkgResult = writeIfAllowed(pkgPath, JSON.stringify(pkg, null, 2) + '\n', args.force);++ const dtsPath = path.join(workingDir, 'genpage.d.ts');+ dtsResult = writeIfAllowed(dtsPath, buildAmbientDeclarations(), args.force);+ } catch (err) {+ console.error(`error: ${err.message}`);+ process.exit(2);+ }++ const summary = {+ workingDir,+ slug,+ features: args.features,+ files: {+ 'package.json': pkgResult,+ 'genpage.d.ts': dtsResult,+ },+ };+ console.log(JSON.stringify(summary, null, 2));+}++if (require.main === module) main();++module.exports = {+ parseArgs,+ buildPackageJson,+ buildAmbientDeclarations,+ RUNTIME_DEPENDENCIES,+ DEV_DEPENDENCIES,+};diff --git a/plugins/model-apps/scripts/lib/supported-dependencies.js b/plugins/model-apps/scripts/lib/supported-dependencies.jsnew file mode 100644index 000000000..affd21e9b--- /dev/null+++ b/plugins/model-apps/scripts/lib/supported-dependencies.js@@ -0,0 +1,139 @@+'use strict';++// Single source of truth for dependency versions used by generated genux pages.+// Consumed by scripts/generate-page-manifest.js (writes package.json) and+// referenced by references/supported-dependencies.md (human-readable doc).+//+// Versions marked `confidence: 'pinned'` come from a definitive source+// (regenerate-verified-icons.js explicitly pins @fluentui/react-icons to+// 2.0.326; React 17 is fixed by the genux runtime).+//+// Versions marked `confidence: 'compatible'` are reasonable defaults that+// work with the genux runtime today but may not match the exact patch+// version the runtime ships. Adjusting to runtime-exact versions requires+// upstream cooperation from the genux platform team.+//+// When the upstream version list lands, update only this file — the+// reference doc and the generator both read from here.++const RUNTIME_DEPENDENCIES = {+ 'react': {+ version: '17.0.2',+ confidence: 'pinned',+ notes: 'Genux runtime is React 17. Patch version 17.0.2 is the last stable React 17 release.',+ },+ 'react-dom': {+ version: '17.0.2',+ confidence: 'pinned',+ notes: 'Pairs with [email protected].',+ },+ '@fluentui/react-components': {+ version: '^9.54.0',+ confidence: 'compatible',+ notes: 'Fluent UI V9 — APIs used by samples (DataGrid, Card, makeStyles+tokens, Field, Dropdown) stable since 9.40.',+ },+ '@fluentui/react-icons': {+ version: '2.0.326',+ confidence: 'pinned',+ notes: 'Pinned by scripts/regenerate-verified-icons.js to keep references/verified-icons.txt in sync with this exact icon set.',+ },+ '@fluentui/react-datepicker-compat': {+ version: '^0.4.50',+ confidence: 'compatible',+ notes: 'V9 compat package — used only when the page calls for a DatePicker.',+ },+ '@fluentui/react-timepicker-compat': {+ version: '^0.2.40',+ confidence: 'compatible',+ notes: 'V9 compat package — used only when the page calls for a TimePicker.',+ },+ 'd3': {+ version: '^7.8.5',+ confidence: 'compatible',+ notes: 'D3 v7+ required for d3.group() (the v6 replacement for d3.nest()). Used only by chart-bearing pages.',+ },+};++const DEV_DEPENDENCIES = {+ 'typescript': {+ version: '^5.4.0',+ confidence: 'compatible',+ notes: 'Any TS 5.x works for editor support; runtime does its own TS-to-JS transpile.',+ },+ '@types/react': {+ version: '^17.0.80',+ confidence: 'compatible',+ notes: 'Type definitions for React 17.',+ },+ '@types/react-dom': {+ version: '^17.0.25',+ confidence: 'compatible',+ notes: 'Type definitions for React DOM 17.',+ },+ '@types/d3': {+ version: '^7.4.3',+ confidence: 'compatible',+ notes: 'Type definitions for D3 v7. Include only when the page uses D3.',+ },+};++// Subset of runtime deps that every Dataverse-backed page needs.+// Chart and DatePicker deps are included only when the page actually+// uses them (the manifest generator can be told via --features).+const DEFAULT_RUNTIME_KEYS = [+ 'react',+ 'react-dom',+ '@fluentui/react-components',+ '@fluentui/react-icons',+];++const FEATURE_RUNTIME_KEYS = {+ charts: ['d3'],+ datepicker: ['@fluentui/react-datepicker-compat'],+ timepicker: ['@fluentui/react-timepicker-compat'],+};++const DEFAULT_DEV_KEYS = ['typescript', '@types/react', '@types/react-dom'];++const FEATURE_DEV_KEYS = {+ charts: ['@types/d3'],+};++function buildDependencyMap(features = []) {+ const runtime = {};+ for (const key of DEFAULT_RUNTIME_KEYS) {+ runtime[key] = RUNTIME_DEPENDENCIES[key].version;+ }+ for (const f of features) {+ const keys = FEATURE_RUNTIME_KEYS[f] ?? [];+ for (const key of keys) {+ if (RUNTIME_DEPENDENCIES[key]) runtime[key] = RUNTIME_DEPENDENCIES[key].version;+ }+ }+ return runtime;+}++function buildDevDependencyMap(features = []) {+ const dev = {};+ for (const key of DEFAULT_DEV_KEYS) {+ dev[key] = DEV_DEPENDENCIES[key].version;+ }+ for (const f of features) {+ const keys = FEATURE_DEV_KEYS[f] ?? [];+ for (const key of keys) {+ if (DEV_DEPENDENCIES[key]) dev[key] = DEV_DEPENDENCIES[key].version;+ }+ }+ return dev;+}++module.exports = {+ RUNTIME_DEPENDENCIES,+ DEV_DEPENDENCIES,+ DEFAULT_RUNTIME_KEYS,+ DEFAULT_DEV_KEYS,+ FEATURE_RUNTIME_KEYS,+ FEATURE_DEV_KEYS,+ buildDependencyMap,+ buildDevDependencyMap,+};diff --git a/plugins/model-apps/scripts/tests/capture-fixture.test.js b/plugins/model-apps/scripts/tests/capture-fixture.test.jsnew file mode 100644index 000000000..8b79d092b--- /dev/null+++ b/plugins/model-apps/scripts/tests/capture-fixture.test.js@@ -0,0 +1,360 @@+'use strict';+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 script = path.join(__dirname, '..', 'capture-fixture.js');+const {+ parseArgs,+ shouldCopyFile,+ copyAllowedFiles,+ parseTapSummary,+ extractFailures,+} = require('../capture-fixture.js');++function mkTempDir(prefix = 'capture-test-') {+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));+}++function writeFiles(dir, files) {+ for (const [name, content] of Object.entries(files)) {+ const full = path.join(dir, name);+ fs.mkdirSync(path.dirname(full), { recursive: true });+ fs.writeFileSync(full, content);+ }+}++function runScript(args) {+ const r = spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' });+ return { code: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };+}++// ---------- parseArgs ----------++test('parseArgs: requires --working-dir', () => {+ assert.throws(() => parseArgs(['--eval', '1', '--slug', 's']), /--working-dir/);+});++test('parseArgs: requires --eval', () => {+ assert.throws(() => parseArgs(['--working-dir', '/x', '--slug', 's']), /--eval/);+});++test('parseArgs: requires --slug', () => {+ assert.throws(() => parseArgs(['--working-dir', '/x', '--eval', '1']), /--slug/);+});++test('parseArgs: --eval must be numeric', () => {+ assert.throws(+ () => parseArgs(['--working-dir', '/x', '--eval', 'abc', '--slug', 's']),+ /numeric/,+ );+});++test('parseArgs: --slug must be kebab-case', () => {+ assert.throws(+ () => parseArgs(['--working-dir', '/x', '--eval', '1', '--slug', 'CamelCase']),+ /kebab-case/,+ );+});++test('parseArgs: --force defaults to false', () => {+ const args = parseArgs(['--working-dir', '/x', '--eval', '1', '--slug', 's']);+ assert.equal(args.force, false);+});++test('parseArgs: --skip-verify is recognized', () => {+ const args = parseArgs(['--working-dir', '/x', '--eval', '1', '--slug', 's', '--skip-verify']);+ assert.equal(args.skipVerify, true);+});++test('parseArgs: unknown flag throws', () => {+ assert.throws(+ () => parseArgs(['--working-dir', '/x', '--eval', '1', '--slug', 's', '--bogus']),+ /Unknown/,+ );+});++// ---------- shouldCopyFile ----------++test('shouldCopyFile: allowlists .tsx', () => {+ assert.equal(shouldCopyFile('page.tsx'), true);+});++test('shouldCopyFile: allowlists .md', () => {+ assert.equal(shouldCopyFile('workflow-log.md'), true);+ assert.equal(shouldCopyFile('genpage-plan.md'), true);+ assert.equal(shouldCopyFile('entity-creation-log.md'), true);+});++test('shouldCopyFile: allowlists RuntimeTypes.ts', () => {+ assert.equal(shouldCopyFile('RuntimeTypes.ts'), true);+});++test('shouldCopyFile: rejects package.json', () => {+ assert.equal(shouldCopyFile('package.json'), false);+});++test('shouldCopyFile: rejects genpage.d.ts', () => {+ assert.equal(shouldCopyFile('genpage.d.ts'), false);+});++test('shouldCopyFile: rejects .log files', () => {+ assert.equal(shouldCopyFile('something.log'), false);+});++test('shouldCopyFile: rejects unknown extensions', () => {+ assert.equal(shouldCopyFile('weird.txt'), false);+ assert.equal(shouldCopyFile('binary.bin'), false);+});++test('shouldCopyFile: rejects .DS_Store / Thumbs.db', () => {+ assert.equal(shouldCopyFile('.DS_Store'), false);+ assert.equal(shouldCopyFile('Thumbs.db'), false);+});++// ---------- copyAllowedFiles ----------++test('copyAllowedFiles: copies allowlisted files, skips others', () => {+ const src = mkTempDir('src-');+ const dst = mkTempDir('dst-');+ fs.rmSync(dst, { recursive: true, force: true }); // function will recreate+ try {+ writeFiles(src, {+ 'page.tsx': 'export default GeneratedComponent;',+ 'RuntimeTypes.ts': 'export interface Account {}',+ 'workflow-log.md': '# log',+ 'genpage-plan.md': '# plan',+ 'entity-creation-log.md': '# entity log',+ 'package.json': '{"name":"x"}',+ 'genpage.d.ts': 'declare global {}',+ 'something.log': 'noise',+ 'weird.txt': 'no',+ });+ const result = copyAllowedFiles(src, dst);+ assert.deepEqual(+ result.copied.sort(),+ ['entity-creation-log.md', 'genpage-plan.md', 'page.tsx', 'RuntimeTypes.ts', 'workflow-log.md'].sort(),+ );+ // Verify the right files actually landed+ assert.ok(fs.existsSync(path.join(dst, 'page.tsx')));+ assert.ok(fs.existsSync(path.join(dst, 'workflow-log.md')));+ assert.ok(!fs.existsSync(path.join(dst, 'package.json')));+ assert.ok(!fs.existsSync(path.join(dst, 'genpage.d.ts')));+ assert.ok(!fs.existsSync(path.join(dst, 'something.log')));+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ fs.rmSync(dst, { recursive: true, force: true });+ }+});++test('copyAllowedFiles: skips node_modules directory', () => {+ const src = mkTempDir('src-');+ const dst = mkTempDir('dst-');+ fs.rmSync(dst, { recursive: true, force: true });+ try {+ writeFiles(src, {+ 'page.tsx': 'x',+ 'node_modules/react/index.js': 'noise',+ });+ const result = copyAllowedFiles(src, dst);+ assert.ok(result.copied.includes('page.tsx'));+ assert.ok(!fs.existsSync(path.join(dst, 'node_modules')));+ assert.ok(result.skipped.some((s) => s.name.startsWith('node_modules')));+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ fs.rmSync(dst, { recursive: true, force: true });+ }+});++// ---------- parseTapSummary ----------++test('parseTapSummary: extracts counts from TAP output', () => {+ const stdout = `TAP version 13+1..1+ok 1 - fixture+# tests 24+# pass 14+# fail 0+# skip 10+# fixtures 1 (pass 1, fail 0)+`;+ const s = parseTapSummary(stdout);+ assert.deepEqual(s, { tests: 24, pass: 14, fail: 0, skip: 10 });+});++test('parseTapSummary: handles missing fields gracefully', () => {+ const s = parseTapSummary('garbage with no counts');+ assert.deepEqual(s, { tests: 0, pass: 0, fail: 0, skip: 0 });+});++// ---------- extractFailures ----------++test('extractFailures: pulls "not ok" assertion lines', () => {+ const stdout = `TAP version 13+1..1+# Subtest: 2-mock-dashboard+ ok 1 - first assertion+ not ok 2 - second assertion failed+ ---+ reason: "boom"+ ...+ ok 3 - third assertion+not ok 1 - 2-mock-dashboard+`;+ const fails = extractFailures(stdout);+ assert.equal(fails.length, 1);+ assert.match(fails[0], /second assertion failed/);+});++test('extractFailures: skips the subtest aggregate line', () => {+ const stdout = ` not ok 1 - real failure+not ok 1 - aggregate-fixture-name+`;+ const fails = extractFailures(stdout);+ assert.equal(fails.length, 1);+ assert.match(fails[0], /real failure/);+});++// ---------- CLI integration ----------++test('CLI: exits 1 when working dir does not exist', () => {+ const r = runScript([+ '--working-dir', '/nonexistent/zzz',+ '--eval', '2',+ '--slug', 'test',+ '--skip-verify',+ ]);+ assert.equal(r.code, 2);+ assert.match(r.stderr, /does not exist/);+});++test('CLI: exits 1 when eval id unknown', () => {+ const src = mkTempDir('src-');+ try {+ writeFiles(src, { 'page.tsx': 'x' });+ const r = runScript([+ '--working-dir', src,+ '--eval', '999',+ '--slug', 'test',+ '--skip-verify',+ ]);+ assert.equal(r.code, 1);+ assert.match(r.stderr, /no eval with id 999/);+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ }+});++test('CLI: exits 2 when no allowlisted files in working dir', () => {+ const src = mkTempDir('src-');+ try {+ writeFiles(src, { 'noise.log': 'x', 'package.json': '{}' });+ const r = runScript([+ '--working-dir', src,+ '--eval', '2',+ '--slug', 'empty-test',+ '--skip-verify',+ ]);+ assert.equal(r.code, 2);+ assert.match(r.stderr, /no allowlisted files/);+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ }+});++test('CLI: writes fixture and reports JSON summary', () => {+ const src = mkTempDir('src-');+ const slug = `capture-cli-test-${Date.now()}`;+ const fixtureDir = path.join(+ __dirname, '..', '..', '..', '..',+ 'evals', 'model-apps', 'genpage', 'fixtures',+ `2-${slug}`,+ );+ try {+ writeFiles(src, {+ 'page.tsx': `import { makeStyles } from '@fluentui/react-components';+const useStyles = makeStyles({ r: {} });+const data = [{a:1},{a:2}];+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+export default GeneratedComponent;`,+ 'workflow-log.md': '# log\n',+ 'package.json': '{"name":"x"}', // should be skipped+ });+ const r = runScript([+ '--working-dir', src,+ '--eval', '2',+ '--slug', slug,+ '--skip-verify',+ ]);+ assert.equal(r.code, 0, `stderr: ${r.stderr}`);+ const summary = JSON.parse(r.stdout);+ assert.equal(summary.eval, 2);+ assert.equal(summary.slug, slug);+ assert.ok(summary.copied.includes('page.tsx'));+ assert.ok(summary.copied.includes('workflow-log.md'));+ assert.ok(!summary.copied.includes('package.json'));+ assert.equal(summary.layer1, undefined, '--skip-verify omits layer1');+ assert.ok(fs.existsSync(fixtureDir));+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ fs.rmSync(fixtureDir, { recursive: true, force: true });+ }+});++test('CLI: refuses to overwrite without --force', () => {+ const src = mkTempDir('src-');+ const slug = `force-test-${Date.now()}`;+ const fixtureDir = path.join(+ __dirname, '..', '..', '..', '..',+ 'evals', 'model-apps', 'genpage', 'fixtures',+ `2-${slug}`,+ );+ try {+ // First capture+ writeFiles(src, { 'page.tsx': 'first', 'workflow-log.md': '#' });+ const r1 = runScript([+ '--working-dir', src, '--eval', '2', '--slug', slug, '--skip-verify',+ ]);+ assert.equal(r1.code, 0);++ // Second capture without --force should fail+ const r2 = runScript([+ '--working-dir', src, '--eval', '2', '--slug', slug, '--skip-verify',+ ]);+ assert.equal(r2.code, 2);+ assert.match(r2.stderr, /already exists/);+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ fs.rmSync(fixtureDir, { recursive: true, force: true });+ }+});++test('CLI: --force overwrites existing fixture', () => {+ const src = mkTempDir('src-');+ const slug = `overwrite-test-${Date.now()}`;+ const fixtureDir = path.join(+ __dirname, '..', '..', '..', '..',+ 'evals', 'model-apps', 'genpage', 'fixtures',+ `2-${slug}`,+ );+ try {+ writeFiles(src, { 'page.tsx': 'v1', 'workflow-log.md': '# v1' });+ runScript([+ '--working-dir', src, '--eval', '2', '--slug', slug, '--skip-verify',+ ]);+ // overwrite source+ fs.writeFileSync(path.join(src, 'page.tsx'), 'v2');+ const r = runScript([+ '--working-dir', src, '--eval', '2', '--slug', slug, '--skip-verify', '--force',+ ]);+ assert.equal(r.code, 0);+ const content = fs.readFileSync(path.join(fixtureDir, 'page.tsx'), 'utf8');+ assert.equal(content, 'v2');+ } finally {+ fs.rmSync(src, { recursive: true, force: true });+ fs.rmSync(fixtureDir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/scripts/tests/generate-page-manifest.test.js b/plugins/model-apps/scripts/tests/generate-page-manifest.test.jsnew file mode 100644index 000000000..05eb523fa--- /dev/null+++ b/plugins/model-apps/scripts/tests/generate-page-manifest.test.js@@ -0,0 +1,205 @@+'use strict';+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 script = path.join(__dirname, '..', 'generate-page-manifest.js');++const {+ parseArgs,+ buildPackageJson,+ buildAmbientDeclarations,+} = require('../generate-page-manifest.js');++function mkdirTemp() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-manifest-test-'));+}++function runScript(args) {+ const result = spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' });+ return { code: result.status, stdout: result.stdout, stderr: result.stderr };+}++// ---------- parseArgs ----------++test('parseArgs: requires two positional arguments', () => {+ assert.throws(() => parseArgs(['/tmp/foo']), /expected.*positional/);+});++test('parseArgs: rejects unknown flags', () => {+ assert.throws(() => parseArgs(['/tmp/foo', 'slug', '--bogus']), /Unknown flag/);+});++test('parseArgs: parses --features comma list', () => {+ const args = parseArgs(['/tmp/foo', 'slug', '--features', 'charts,datepicker']);+ assert.deepEqual(args.features, ['charts', 'datepicker']);+});++test('parseArgs: rejects unknown feature', () => {+ assert.throws(() => parseArgs(['/tmp/foo', 'slug', '--features', 'unicorn']), /Unknown feature/);+});++test('parseArgs: --force defaults to false', () => {+ const args = parseArgs(['/tmp/foo', 'slug']);+ assert.equal(args.force, false);+});++// ---------- buildPackageJson ----------++test('buildPackageJson: default has react + fluent + icons but NOT d3', () => {+ const pkg = buildPackageJson('slug', []);+ assert.ok(pkg.dependencies['react'], 'react present');+ assert.ok(pkg.dependencies['@fluentui/react-components'], 'fluent present');+ assert.ok(pkg.dependencies['@fluentui/react-icons'], 'icons present');+ assert.equal(pkg.dependencies['d3'], undefined, 'd3 absent by default');+});++test('buildPackageJson: charts feature adds d3 + @types/d3', () => {+ const pkg = buildPackageJson('slug', ['charts']);+ assert.ok(pkg.dependencies['d3'], 'd3 added');+ assert.ok(pkg.devDependencies['@types/d3'], '@types/d3 added');+});++test('buildPackageJson: datepicker feature adds the compat package', () => {+ const pkg = buildPackageJson('slug', ['datepicker']);+ assert.ok(pkg.dependencies['@fluentui/react-datepicker-compat']);+});++test('buildPackageJson: icons version stays pinned (no caret)', () => {+ const pkg = buildPackageJson('slug', []);+ assert.equal(+ pkg.dependencies['@fluentui/react-icons'],+ '2.0.326',+ 'icon version pinned exact per regenerate-verified-icons.js'+ );+});++test('buildPackageJson: name uses provided slug, marked private', () => {+ const pkg = buildPackageJson('account-card-gallery', []);+ assert.equal(pkg.name, 'account-card-gallery');+ assert.equal(pkg.private, true);+});++// ---------- buildAmbientDeclarations ----------++test('genpage.d.ts: declares Window.Xrm with Navigation.navigateTo', () => {+ const dts = buildAmbientDeclarations();+ assert.match(dts, /interface Window/);+ assert.match(dts, /Xrm: XrmShape/);+ assert.match(dts, /Navigation:/);+ assert.match(dts, /navigateTo:/);+});++test('genpage.d.ts: types the window cache key pattern', () => {+ const dts = buildAmbientDeclarations();+ assert.match(dts, /__genpage_/);+});++test('genpage.d.ts: declares Utility.getGlobalContext()', () => {+ const dts = buildAmbientDeclarations();+ assert.match(dts, /getGlobalContext/);+ assert.match(dts, /languageId:/);+});++test('genpage.d.ts: is a TypeScript module (has export {})', () => {+ const dts = buildAmbientDeclarations();+ assert.match(dts, /^export\s*\{\s*\}\s*;/m);+});++// ---------- CLI: invalid args ----------++test('CLI: exits 1 when args missing', () => {+ const r = runScript([]);+ assert.equal(r.code, 1);+ assert.match(r.stderr, /expected.*positional/);+});++test('CLI: exits 1 when slug is not kebab-case', () => {+ const dir = mkdirTemp();+ try {+ const r = runScript([dir, 'CapitalCase']);+ assert.equal(r.code, 1);+ assert.match(r.stderr, /kebab-case/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('CLI: exits 2 when working dir does not exist', () => {+ const r = runScript(['/nonexistent/zzz/yyy', 'foo']);+ assert.equal(r.code, 2);+ assert.match(r.stderr, /does not exist/);+});++// ---------- CLI: writes files ----------++test('CLI: writes package.json and genpage.d.ts to working dir', () => {+ const dir = mkdirTemp();+ try {+ const r = runScript([dir, 'my-page']);+ assert.equal(r.code, 0);+ assert.ok(fs.existsSync(path.join(dir, 'package.json')), 'package.json written');+ assert.ok(fs.existsSync(path.join(dir, 'genpage.d.ts')), 'genpage.d.ts written');+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ assert.equal(pkg.name, 'my-page');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('CLI: idempotent — does NOT overwrite without --force', () => {+ const dir = mkdirTemp();+ try {+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"already-here"}');+ const r = runScript([dir, 'my-page']);+ assert.equal(r.code, 0);+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ assert.equal(pkg.name, 'already-here', 'existing package.json preserved');+ assert.match(r.stdout, /"wrote": false/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('CLI: --force overwrites existing files', () => {+ const dir = mkdirTemp();+ try {+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"already-here"}');+ const r = runScript([dir, 'my-page', '--force']);+ assert.equal(r.code, 0);+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ assert.equal(pkg.name, 'my-page', 'package.json overwritten by --force');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('CLI: --features charts includes d3 in written package.json', () => {+ const dir = mkdirTemp();+ try {+ const r = runScript([dir, 'chart-page', '--features', 'charts']);+ assert.equal(r.code, 0);+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ assert.ok(pkg.dependencies['d3'], 'd3 in dependencies');+ assert.ok(pkg.devDependencies['@types/d3'], '@types/d3 in devDeps');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('CLI: stdout is valid JSON summary', () => {+ const dir = mkdirTemp();+ try {+ const r = runScript([dir, 'my-page']);+ assert.equal(r.code, 0);+ const summary = JSON.parse(r.stdout);+ assert.equal(summary.slug, 'my-page');+ assert.equal(summary.files['package.json'].wrote, true);+ assert.equal(summary.files['genpage.d.ts'].wrote, true);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex e3c27e907..4d1ee6218 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -1,6 +1,6 @@---name: genpage-version: 2.1.0+version: 2.2.0description: Creates, updates, and deploys Power Apps generative pages for model-driven apps using React v17, TypeScript, and Fluent UI V9. Orchestrates specialist agents for planning, entity creation, and code generation. Use it when user asks to build, retrieve, or update a page in an existing Microsoft Power Apps model-driven app. Use it when user mentions "generative page", "page in a model-driven", or "genux".author: Microsoft Corporationargument-hint: "<page description> | edit"@@ -67,6 +67,28 @@ Derive a short folder name from the user's requirements:3. Create the folder: `mkdir -p <folder-name>`4. Resolve its absolute path — this is the **working directory** for all subsequent phases+### Phase 0.5: Initialize Local-Dev Manifest++Write `package.json` and `genpage.d.ts` into the working directory so the+developer can `npm install` and get IntelliSense, type-checking, and "go to+definition" in their editor. Versions come from+`references/supported-dependencies.md` (single source of truth:+`scripts/lib/supported-dependencies.js`).++```bash+node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-page-manifest.js" <working-dir> <kebab-slug>+```++- `<kebab-slug>` is the same slug used for the working directory.+- Add `--features charts,datepicker,timepicker` (comma-separated) only when+ the requirements clearly call for them; otherwise omit and keep the+ manifest lean.+- The script is **idempotent** — it skips files that already exist. Pass+ `--force` to overwrite (used in regeneration flows when versions drift).+- Output is a JSON summary on stdout; pipe to stderr for visibility but do+ not block the workflow if the script returns non-zero — the manifest is a+ dev-ergonomics aid, not part of the deployed artifact.+### Phase 1: Plan> **⚠️ CRITICAL — you MUST invoke `genpage-planner` via the `Task` tool. You MUST@@ -313,6 +335,14 @@ For each `.tsx` file produced, deploy to Power Apps.**Copy the upload commands below exactly — `--app-id`, `--code-file`, `--prompt`, `--agent-message` are all required and must use these exact flag names.**+**Log the full command verbatim into `workflow-log.md` under a `## Phase 6 — Deploy` section before invoking it.** Including `--prompt` and all other flags. The eval harness greps the log for these tokens — a terse summary like `Command: pac model genpage upload --add-to-sitemap` will fail the `--prompt scoping` assertion. Format:++```markdown+## Phase 6 — Deploy+- Command: `pac model genpage upload --app-id <id> --code-file <path> --data-sources '<entities>' --prompt "<full prompt>" --model <model-id> --name "<page name>" --agent-message "<description>" --add-to-sitemap`+- Result: page-id = <returned-id>, status = success+```+#### `--prompt` semantics- **First upload** (`--add-to-sitemap`, no `--page-id`): full page description@@ -406,9 +436,32 @@ Options: **Yes, verify in browser** / **Skip verification**### Phase 8: Summary-Write a `workflow-log.md` file to the working directory summarizing the run:-agents invoked, commands executed, decisions made, files produced. This log is-useful for debugging and required by the eval harness.+By Phase 8 the `workflow-log.md` should already contain Phase 0 through Phase 7+sections written incrementally — the planner writes Phase 1 inside its agent+context, you (the orchestrator) write Phase 0 / 0.5 / 3 / 4 / 6 / 6.5 / 7 as+each runs, and the entity-builder and page-builder agents append their own+Phase 2 / 5 sections when invoked.++In Phase 8, append a final `## Phase 8 — Summary` section to the same file:++```markdown+## Phase 8 — Summary++| Page | File | Entities | Status |+|------|------|----------|--------|+| <Name> | <file>.tsx | <entities or "mock data"> | Deployed |++- App: <name> (<app-id>)+- Entities created: <list, or "none">+- Browser verification: <skipped | confirmed | failed: <reason>>+```++The log MUST contain command-level entries for every prereq / auth / question /+upload / script invocation — not just outcome summaries. The eval harness greps+the log for tokens like `node --version`, `pac auth list`, `AskUserQuestion`,+`EnterPlanMode`, `--prompt`, `check-auth.js`, etc. A decision-only log+(e.g., `Decision: new page` without the underlying `AskUserQuestion`) will+fail Layer 1 assertions even when the agent's behavior was correct.Then present a final summary to the user: