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
Optimize mobile Dataverse planning and deterministic creation (#440)
Shubham Agarwal4d41b4b93401
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.ymlnew file mode 100644index 000000000..0d4ca1b03--- /dev/null+++ b/.github/workflows/mobile-apps-script-tests.yml@@ -0,0 +1,40 @@+# Functional unit tests for the mobile-apps plugin across supported operating+# systems and Node versions. These scripts spawn Azure CLI shims and manipulate+# filesystem paths, so cross-platform coverage protects real behavior.+name: mobile-apps-script-tests++on:+ pull_request:+ branches:+ - main+ paths:+ - "plugins/mobile-apps/**"+ - ".github/workflows/mobile-apps-script-tests.yml"++jobs:+ test-mobile-apps-scripts:+ name: test-mobile-apps-scripts (${{ matrix.os }}, node ${{ matrix.node }})+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os:+ - ubuntu-latest+ - windows-latest+ - macos-latest+ node:+ - 20+ - 22+ steps:+ - name: checkout+ uses: actions/checkout@v4++ - name: setup-node+ uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}++ - name: run-mobile-apps-script-tests+ shell: bash+ working-directory: plugins/mobile-apps+ run: node --test scripts/tests/*.test.jsdiff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.mdindex 2fad8b3c3..6fd9a5bfd 100644--- a/plugins/mobile-apps/agents/data-model-architect.md+++ b/plugins/mobile-apps/agents/data-model-architect.md@@ -22,6 +22,12 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in- Wizard answers (target users, aesthetic, features)- The working directory- The plugin root+- **Normalized Dataverse foreground planning snapshot path (preferred)** — an absolute path to+ `<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json`.+- **Planning evidence path (preferred)** — an absolute path to the deterministic+ Markdown appendix rendered from that same foreground planning snapshot.+- **Dataverse planning mode** — `required` or `connector-only`.+ `connector-only` intentionally has no snapshot/evidence paths.- **Publisher prefix (detected from env)** — e.g. `cr8142a` (no trailing underscore). Use this literally when constructing logical names: `<prefix>_<entity>` → `cr8142a_inspection`. If the prefix is empty / `NOT DETECTED`, fall back to the placeholder `cr` and add a `DONE_WITH_CONCERNS` note that the actual prefix will be assigned by Dataverse at create time. **Do not invent or assume `cr_` if a real prefix was supplied.**- **`mode` (optional)** — one of `default` (full Steps 1–7, the original flow) or `cross-entity-audit` (the addendum pass spawned AFTER `screen-planner` returns; runs ONLY Step 6a + writes a `### Cross-entity Reads` addendum to `_dm_section.md`, skipping discovery and re-scoring). When omitted, treat as `default`.@@ -29,11 +35,35 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in- **Read-only.** You MUST NOT run `npx power-apps add-data-source --api-id dataverse --org-url <env-url> --resource-name <table>`, table-creation HTTP calls, or any mutating PowerShell. Mutation happens later in `/add-dataverse` after user approval.- **Power Apps CLI failure refresh.** Follow [shared-instructions.md](../shared/shared-instructions.md) command-failure handling for any failed `npx power-apps *` command; retry the original command once after auth is corrected.-- **Reuse-first.** Always query existing tables and prefer reuse > extension > new. Don't propose a `cr123_customer` table if a standard `contact` table fits.+- **Reuse-first and target-grounded.** Use exact target metadata for every+ proposed table, including standard tables, and prefer reuse > extension >+ new. In planning-snapshot-only mode that evidence comes only from the validated+ foreground planning snapshot. Don't propose a `cr123_customer` table if a verified+ target `contact` table fits.+- **Never invent existing schema.** Never propose recreating or imitating a missing standard, managed, or solution-owned table/column. If discovery cannot run, you may still draft a plan from requirements, but mark it `Discovery skipped` so every decision remains unverified and non-executable. Step 8 verifies approved decisions against fresh bounded metadata; it never invents `Adapt` or `Defer`.+- **Mode fidelity.** `connector-only` means zero Dataverse tables and zero+ Dataverse discovery. A Dataverse-required run with unreadable metadata is+ blocked by the foreground orchestrator before this agent is dispatched.+- **No automatic replacement.** This agent classifies schema as `Reuse`, `Extend`, `Create`, `Adapt` (create beside a conflicting object under a new name), `Defer` (leave out of this run), or `Unverified` (target metadata could not be read). Replacing an existing table/column requires a separately approved migration with dependency analysis and data movement; it is outside this workflow. A data-modelling conflict is never a blocker — it is an `Adapt` or a `Defer` with a recorded reason.- **Return a section, not a separate doc.** Output is a markdown `## Data Model` section the planner embeds verbatim.- **No JSON request bodies in the output.** Your `_dm_section.md` describes *what* to create (tables, columns, relationships) using the Mermaid ER + reuse/extend/create table + tier list. **Do NOT include POST body JSON** for `EntityDefinitions` or `RelationshipDefinitions` — `/add-dataverse` constructs those from its own canonical templates in [skills/add-dataverse/SKILL.md](../skills/add-dataverse/SKILL.md) Step 5b. JSON in your output is read as authoritative and will leak invented/wrong fields (e.g. `ReferencingAttribute` on a lookup) into the actual POST.- **No questions.** Do not ask the user anything — infer from the requirements provided. The planner runs the approval gate, not you.-- **MANDATORY progress reporting.** Every step in the workflow has a `**Print before starting:**` block. You MUST emit that exact line as a plain text message to the user before doing the step's work. Do not skip, do not paraphrase. The user has no other visibility — silence looks like a hang.+- **MANDATORY progress reporting.** For every step that is actually executed,+ emit its exact `**Print before starting:**` line. In snapshot-only mode,+ skipped live-discovery steps emit no legacy discovery line; their visibility+ is replaced by the snapshot/status milestones below. Do not paraphrase an+ executed step's line.+- **Progress contract.** Maintain+ `<working_dir>/.tmp/data-model-planning-status.json`. Each atomic update+ contains `version`, `state`, `startedAt`, `updatedAt`, `elapsedMs`,+ `milestoneId`, `message`, and factual `counts`. Use these milestone IDs in+ order: `snapshot-loaded`, `requirements-inferred`,+ `candidates-reconciled`, `relationships-tiered`, `artifact-written`.+ Counts include the values known at that point, such as+ `inventoryTables`, `detailedTables`, `requiredEntities`,+ `reconciledEntities`, `relationships`, and `tiers`. The foreground+ orchestrator owns user-visible rendering; this agent only writes the+ contract and its normal concise progress lines.## Workflow@@ -41,7 +71,7 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in2. Verify Dataverse access3. Discover existing tables4. Infer required entities from requirements-5. Score reuse / extend / create+5. Reconcile target metadata and classify reuse / extend / create / adapt / defer / unverified6. Build dependency tiers6a. Cross-entity Read Audit (when `_screens_section.md` exists OR `mode: cross-entity-audit`)7. Produce the `## Data Model` section@@ -50,8 +80,67 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in---+## Planning-mode short circuits++When `Dataverse planning mode: connector-only` is supplied, do not resolve an+environment, read metadata, or request snapshot artifacts. Write+`_dm_section.md` with an explicit zero-table `## Data Model` section (all+summary counts zero, no ER entities or dependency tiers, and a note that the+confirmed systems of record are the approved connectors), update the normal+artifact milestone, and return `DONE`.++## Snapshot-only fast path++In `required` mode, both snapshot and planning-evidence paths must be supplied.+Validate before planning:++- snapshot `version >= 3`;+- snapshot environment URL and tenant match the foreground-resolved target;+- inventory, detailed tables, candidate ranking, proposed-name checks, and+ timing metrics are present;+- the evidence appendix names the same environment and generated timestamp.++If validation succeeds, this path is mandatory:++1. Read the snapshot once and the evidence appendix once.+2. Skip Steps 1–3 environment resolution, access verification, and broad+ discovery. Skip every live Dataverse query in Step 5.+3. Do **not** run Bash discovery or call `resolve-environment.js`,+ `verify-dataverse-access.js`, `dataverse-request.js`, or+ `list-table-columns.js`.+4. Use `candidateRanking` for concept selection, `tables` for exact+ column/relationship/key/choice/computed evidence, and+ `proposedNameChecks` for Create/Adapt decisions. Do not rescan inventory.+ Treat candidates with `detailStatus: unavailable` and matching+ `detailLoadFailures` entries as advisory inventory evidence only; never+ describe them as detailed. Proposed-name checks are collision evidence, not+ required existing-table discovery.+5. If a required existing candidate, relationship target, or standard/managed+ dependency is present only in `inventory`, stop and return exactly:++ `NEEDS_CONTEXT: detailed-dataverse-metadata:<comma-separated-logical-names>`++ Sort and de-duplicate the names. This requests one bounded foreground+ expansion; do not downgrade the decision or perform another broad scan.+6. Before emitting any `Create` or `Adapt` decision, verify its final logical+ name appears in `proposedNameChecks.checked`. If one or more final names are+ absent, stop and return exactly:++ `NEEDS_CONTEXT: proposed-dataverse-names:<comma-separated-logical-names>`++ Sort and de-duplicate the names. The foreground will run one bounded+ collision-only expansion; do not infer absence from an unchecked name.++If either required artifact is missing, invalid, or mismatched, return+`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`. Do not fall back to+live discovery from `required` mode. The legacy live path below remains only+for callers that omit the new planning mode entirely (for example an older+`/edit-app` flow).+## Step 1 — Resolve Target Environment+**Legacy live path only. Skip entirely in the validated snapshot-only path.**+**Print before starting:**> "→ Resolving Dataverse environment from power.config.json or explicit environment URL/ID…"@@ -69,28 +158,34 @@ node "${PLUGIN_ROOT}/scripts/resolve-environment.js" <environment-id-or-url>Capture the **Environment URL** (e.g., `https://orgXXXXX.crm.dynamics.com`), **Environment ID**, and **Tenant ID** from the output. Use the URL as `<envUrl>` for subsequent script calls.-If resolution fails (not authenticated or environment not visible to the logged-in account), include a clear note in your output and stop further discovery — propose the data model from requirements only with a "Discovery skipped — environment not reachable" warning prepended to your section.+If resolution fails (not authenticated or environment not visible to the logged-in account), do not stop the run. Skip further discovery, prepend a `Discovery skipped — environment not reachable` warning to your section, and finish with `DONE_WITH_CONCERNS`. The plan is a draft for the user's Gate 1 review; `/add-dataverse` re-queries live metadata and blocks any mutation it cannot verify.## Step 2 — Verify Dataverse Access+**Legacy live path only. Skip entirely in the validated snapshot-only path.**+`resolve-environment.js` only resolves environment metadata; it does not prove Dataverse user access. Verify access before metadata discovery:```bashnode "${PLUGIN_ROOT}/scripts/verify-dataverse-access.js" <envUrl>```-If it fails, prepend a "Dataverse access failed — `az login` required" note and skip Steps 3.+If it fails, skip Step 3 and Step 5's live queries, prepend a `Dataverse access failed — az login required` warning to your section, and finish with `DONE_WITH_CONCERNS`. Do not convert unverified guesses into confident decisions.## Step 3 — Discover Existing Tables**Print before starting:**> "→ Discovering existing custom tables in the environment (cap: top 10 by relevance)…"-Query custom tables only (standard tables are well-known):+**Legacy live path only.** In the validated snapshot-only path, update the+`snapshot-loaded` milestone from snapshot counts and proceed directly to Step+4 without running this print line or any command.++Query custom tables to discover conceptual reuse candidates. This broad query is advisory only; Step 5 still queries every selected custom, standard, and managed table by exact logical name before classifying it:```bashnode "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions?\$select=LogicalName,DisplayName,Description&\$filter=IsCustomEntity eq true"+ "EntityDefinitions?\$select=MetadataId,LogicalName,DisplayName,Description,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes&\$filter=IsCustomEntity eq true"```For the relevant tables, fetch their user-defined columns in a single call (system columns like `createdon`, `modifiedby`, `statecode`, `ownerid`, `versionnumber` are filtered out automatically):@@ -124,65 +219,127 @@ Standard table mappings to bias toward:| An activity event | `appointment`, `task`, `phonecall`, `email` || A user / system identity | `systemuser` (read-only — never propose extending) |-## Step 5 — Score Reuse / Extend / Create+For every `Reuse` decision, add `Service required: yes|no`. Use `yes` whenever any screen, hook, role check, lookup picker, related-field fetch, or authenticated-identity flow reads the table. `systemuser` identity resolution is always `Service required: yes`; read-only means no schema mutation, not no generated data source.++Update progress milestone `requirements-inferred` with the required-entity+count and elapsed time.++## Step 5 — Reconcile Target and Score Reuse / Extend / Create / Adapt / Defer / Unverified**Print before starting:**-> "→ Scoring each required entity as Reuse / Extend / Create against discovered tables…"+> "→ Reconciling every required table and column against verified target metadata…"++In the validated snapshot-only path, interpret this line as "against the+foreground planning snapshot", run no command, and use detailed `snapshot.tables`+entries plus the deterministic appendix. Before assigning any decision on the+legacy live path, resolve every required entity — including `contact`,+`account`, `incident`, other standard tables, and managed-solution+dependencies — in a **single** filtered query that also expands their columns:++```bash+node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \+ "EntityDefinitions?\$select=MetadataId,LogicalName,SchemaName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes,PrimaryIdAttribute,PrimaryNameAttribute&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'&\$expand=Attributes(\$select=LogicalName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName)"+```++Build the `$filter` by OR-ing every selected logical name. This is the [documented way to query multiple table definitions at once](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#basic-retrievemetadatachanges-example) and replaces 2N requests with one. Keep the expanded `$select` to base `AttributeMetadata` properties — one query [cannot cast to a derived column type](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#evaluate-other-options-to-retrieve-schema-definitions).-For each required entity, classify it as one of:+A planned name **present** in `value[]` exists; a name **absent** from `value[]` does not. Interpret `IsCustomizable` and `CanCreateAttributes` as managed properties (`.Value`). Absence is actionable only after considering the planned dependency kind: an absent new custom table may be created; an absent standard, managed, reused, or extended dependency is `Defer` — it must be installed/imported or removed from the design, so leave it out of this run and record why. If the batched query itself fails, mark the affected entities `Unverified` rather than `Create`, and carry the reason into the section — `/add-dataverse` re-checks it at its own reconciliation step.++For each required entity, classify it as exactly one of:- **Reuse** — existing table fits as-is (no schema changes needed)-- **Extend** — existing table is the right concept but missing some columns; add only the missing ones-- **Create** — no existing table serves this purpose at all (neither by name nor by concept)+- **Extend** — existing table is the right concept, all same-name columns are compatible, missing columns are custom additions, and both `IsCustomizable.Value` and `CanCreateAttributes.Value` permit extension+- **Create** — the planned item is explicitly a new custom table, the exact logical name returns 404, the publisher prefix is verified, and all required-existing dependencies are present+- **Adapt** — a same-name custom table/column is incompatible or the intended custom table cannot be safely extended, so create an app-owned alternative under a new verified logical name and record the alias+- **Defer** — a standard, managed, solution-owned, or required-existing dependency is missing/incompatible, or no safe app-owned alternative can preserve the intended semantics; leave it out of this run and record the prerequisite+- **Unverified** — discovery could not run for this entity (Step 1/2 failure or a non-200/404 response). Record the intended decision plus the reason; `/add-dataverse` re-checks it before any write++Classify every planned column before finalizing its table decision:++- **Reuse** — same logical name exists with a compatible `AttributeType` / `AttributeTypeName.Value`.+- **Create** — column is absent, is explicitly a custom addition, and the target table permits attributes. The containing table becomes `Extend`, or the column is included inline when its table is `Create`.+- **Adapt** — a same-name custom column is incompatible and the table permits a new custom column under a verified logical name; record the old-to-new alias.+- **Defer** — a required standard/managed column is absent or incompatible, the target cannot be customized, or a renamed custom column would change the intended semantics.+- **Unverified** — the live column metadata could not be read reliably; preserve the intended decision for `/add-dataverse` to re-check.++`Extend` is a table decision, not a column operation. Do not classify any item as `Replace`; Dataverse cannot change column types in place, and replacement needs an explicit migration outside this workflow.**Decision priority (HARD — apply in order, stop at first match):**-1. **Standard table match** → always prefer a standard table (`contact`, `account`, `incident`, etc.) over creating a custom table for the same concept. Reuse if it fits; Extend if it needs columns.+1. **Standard table match** → always prefer a standard table (`contact`, `account`, `incident`, etc.) over creating a custom table for the same concept, but verify it by exact target GET. Reuse if it fits; Extend only when live managed properties permit the planned custom columns. If it is missing or incompatible, Defer — never create a custom imitation.2. **Existing custom table by name** → if the proposed logical name already exists in the Step 3 results, it MUST be Reuse or Extend. See collision check below.3. **Existing custom table by concept** → if a different-named existing table serves the same business purpose (e.g., an existing `cr8142a_site` table for a new "Inspection Site" entity), prefer Extend over Create.-4. **Create** → only when no existing table — standard or custom — serves the entity's purpose. The business use case genuinely requires a fresh schema.+4. **Extension-cost guardrail** → reuse remains preferred when the existing record is authoritative/shared, but do not extend a merely similar custom table by default when the app would add more than 8 columns or more than 50% of the final required schema. Prefer a new app-owned table unless shared identity, integrations, security, or reporting make the existing table the true system of record. Record the metadata-write tradeoff and rationale in `Why`.+5. **Create** → only when no existing table — standard or custom — serves the entity's purpose, the proposed custom logical name is absent in the target, and every required-existing dependency is verified.+6. **Adapt / Defer / Unverified** → incompatible custom schema becomes Adapt when a safe app-owned alias preserves semantics; missing/incompatible standard, managed, or required-existing schema becomes Defer; unavailable target facts become Unverified. Never reinterpret any of these states as Create under the conflicting logical name.> **⚠️ Plan-time collision check (HARD).** Before classifying any entity as `Create`, look up its **proposed logical name** (e.g. `cr8142a_inspection`) in the Step 3 IsCustomEntity result. If a row with that exact `LogicalName` already exists, the entity **CANNOT** be classified as `Create`. Apply the following decision tree in order:>> 1. **Downgrade to Reuse** — the existing table's columns from Step 3 already cover what the plan needs (≥70% column overlap or all required columns present). No schema changes.-> 2. **Downgrade to Extend** — the existing table is the right concept but missing some columns (any overlap, or same entity type). Add only the missing columns; never remove or rename existing ones.-> 3. **Rename and Create** — use ONLY when the existing table is a completely different entity concept (e.g., `cr8142a_inspection` exists but contains payroll or product catalog data — fundamentally incompatible). Bump the proposed name to `<prefix>_<entity>v2` and document the rename in the Notes column.+> 2. **Downgrade to Extend** — the existing table is the right concept but missing some custom columns (any overlap, or same entity type), and live `IsCustomizable.Value` plus `CanCreateAttributes.Value` permit extension. Add only the missing columns; never remove or rename existing ones.+> 3. **Adapt (rename and create)** — use ONLY when the existing custom table is a completely different entity concept (e.g., `cr8142a_inspection` exists but contains payroll or product catalog data — fundamentally incompatible). Bump the proposed name to `<prefix>_<entity>v2`, record the alias, and document the evidence in the Notes column.>-> **Default is Reuse or Extend — not Rename.** Rename-and-Create is the exceptional path, not the fallback. If unsure whether a schema is compatible, prefer Extend and add the missing columns — it is always safer to extend than to duplicate tables.+> **Default is Reuse or Extend only when compatibility is proven.** Adapt is the exceptional path, not the fallback. Request bounded detailed expansion only when the candidate is inventory-only. If live metadata could not be read, mark Unverified. If already-detailed metadata remains incompatible or ambiguous, classify Defer and record what evidence or prerequisite is missing; never loop a no-op expansion or extend merely to keep the workflow moving.>> Surfacing the collision at PLAN time (not at create time) prevents the user from approving Gate 1 with a name that will explode at Step 5a of `/add-dataverse`.Build a table:```markdown-| Required entity | Decision | Existing match | Why | Missing columns |-|---|---|---|---|---|-| Customer profile | Reuse | `contact` | Standard table; name/email/phone fields match | — |-| Job site | Create | — | No matching custom or standard table for this concept | n/a |-| Inspection report | Extend | `cr123_inspection` (existing) | Same concept; has site reference, missing photos field | `cr123_photourl` (Image) |-| Equipment inspection | Extend | `cr3e9_inspection` (existing) | Name match; different FK schema but same inspection concept — add equipment-specific columns | `cr3e9_equipmentid` (Lookup), `cr3e9_equipmenttype` (Choice) |-| Payroll record | Create (renamed from cr3e9_inspection) | `cr3e9_inspection` exists | Existing table is inspection data — fundamentally different concept; using `cr3e9_payrollrecord` | n/a |+| Required entity | Decision | Existing match | Target evidence | Column decisions | Why |+|---|---|---|---|---|---|+| Customer profile | Reuse | `contact` | 200; exact standard table verified | Reuse: fullname, emailaddress1 | Standard table and required columns exist |+| Job site | Create | — | 404; verified custom prefix | Create inline: cr123_name, cr123_address | No matching custom or standard table for this concept |+| Inspection report | Extend | `cr123_inspection` | 200; customizable + can create attributes | Reuse: cr123_name; Create: cr123_photo | Same concept; one custom column is missing |+| Required managed asset | Defer | — | 404 for required-existing dependency | Defer: all dependent fields | Install/import the owning solution; never recreate it. Left out of this run, not a blocker |```+In snapshot-only mode, keep `Target evidence` concise: cite the relevant+concept/table anchor in the planning evidence appendix and state only the+decision-bearing fact (for example, "appendix: `contact`; customizable=yes;+2/2 required columns present"). Do not restate raw inventory, option lists, or+full column payloads.++Update progress milestone `candidates-reconciled` with reuse, extend, create,+adapt, defer, unverified, and reconciled-entity counts.+## Step 6 — Build Dependency Tiers-Order new tables so foreign keys can resolve. From [data-architecture-reference.md](${PLUGIN_ROOT}/skills/add-dataverse/references/data-architecture-reference.md):+Order new tables so foreign keys can resolve. See [dataverse-reference.md § Pre-flight ordering](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md#pre-flight-ordering):++Before assigning tiers, remove redundant relationships. Dataverse already+provides `ownerid`, `createdby`, `modifiedby`, `createdon`, and `modifiedon` on+user-owned tables. Do not create app-prefixed lookups that duplicate those+standard ownership/audit relationships unless the business meaning is distinct+(for example, `approvedby` or `assignedinspector`). Reuse the standard columns+and document their role instead.- **Tier 0** — reference tables (no lookups out)- **Tier 1** — primary entities (lookups to Tier 0)- **Tier 2** — dependent tables (lookups to Tier 1+)- **Tier 3+** — many-to-many relationship tables+For every planned relationship, state why the child lookup is needed, why the+cardinality fits the workflow, and whether ownership/audit columns already+cover the requirement. Do not add relationships solely because two entities+appear in the same brief.++Update progress milestone `relationships-tiered` with direct relationship and+dependency-tier counts.+## Step 6a — Cross-entity Read Audit**Print before starting:**-> "→ Auditing planned screens for cross-entity reads (calc-column candidates)…"+> "→ Auditing planned screens for supported cross-entity read paths…"**Run condition:** execute this step when EITHER (a) `<working_dir>/_screens_section.md` exists at this point in the workflow OR (b) you were invoked with `mode: cross-entity-audit`. **Skip silently otherwise** (default-mode first-pass run, before screen-planner has produced its section) — the orchestrator will re-spawn you in `mode: cross-entity-audit` after Gate 4a/4b lands.When `mode: cross-entity-audit`, the orchestrator's prompt also includes the path to the existing `_dm_section.md` so you can append (do NOT regenerate it from scratch — Steps 1–6 are skipped in this mode).-This step exists because of the runtime constraint documented at [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads) — the SDK has no `$expand`, so cross-entity fields on hot paths (lists, dashboards) MUST be denormalized via calculated columns at the data-model layer. This step proposes those calc columns based on the screen plan; `/setup-datamodel` (or `/add-dataverse`) Phase 6.1b creates them.+This step exists because the generated SDK has no `$expand`. It classifies each+cross-entity field into a supported formatted lookup or bounded chained fetch.+Dataverse does not support defining calculated/formula expressions through+code, so this audit never proposes generated formula metadata.**Algorithm:**@@ -190,36 +347,28 @@ This step exists because of the runtime constraint documented at [`shared/refere2. **Per entry, branch on `recommends`:**- - **`recommends: calc-column`** — confirm the `cardinality` is `1:1` (calc columns CANNOT traverse 1:many or M:N). If cardinality is wrong, downgrade silently to `chained-fetch` and add a `DONE_WITH_CONCERNS` note. Otherwise, propose a calculated column on the **primary entity of that screen** (the entity its primary `Data` service queries):- - **Logical name:** `<prefix>_<resolved_field>_calc` (lowercased, e.g. `cr3e9_gatename_calc`)- - **Schema name:** PascalCase variant (e.g. `Cr3e9_GateName_calc`)- - **Display name:** human label from the planner's `field` value (e.g. "Gate name")- - **Type:** matches the resolved field's TypeScript type → Dataverse type (`string` → `Edm.String`, `datetime` → `Edm.DateTimeOffset`, `decimal` / `money` → `Edm.Decimal`, `integer` → `Edm.Int32`, `boolean` → `Edm.Boolean`)- - **Formula source:** the dotted path from the planner's `source` field, normalized — e.g. `cr3e9_flightid → cr3e9_gateid → cr3e9_gatename` becomes `cr3e9_flightid.cr3e9_gateid.cr3e9_gatename`. The formula is N:1 lookup chain only; no aggregations, no conditionals, no string concat in v0.-- - **`recommends: chained-fetch`** — do NOT add any column. The screen-builder handles this at scaffold time per the decision table in `data-performance.md`. Just include the entry in the addendum's `Chained-fetch fields (informational)` row so the user sees what the screen-builder will scaffold.--3. **De-duplicate.** A field driven by N screens (e.g. "Gate name" used on home, list, AND detail) collapses to ONE calc-column row in the addendum. Track all driving screens in the `Driven by` column.+ - **`recommends: formatted-lookup`** — verify the source is the primary+ display name of a direct lookup. Create no column.+ - **`recommends: chained-fetch`** — create no column. The screen-builder+ performs one bounded related request outside row rendering.+ - **`recommends: external-projection-required`** — record a blocker for a hot+ list/dashboard field that cannot use the direct lookup annotation. Omit+ the field until the user supplies a maker-created formula column or other+ server-owned projection.-4. **Cap at 20 calc columns per parent entity.** If you exceed, truncate and add a `DONE_WITH_CONCERNS` note — large calc-column counts indicate a denormalization problem that should be solved at the data-model level (probably an extracted entity), not by piling on calc columns.+3. **De-duplicate.** Collapse identical source/resolution pairs and track all+ consuming screens.5. **Emit the addendum.** Write the `### Cross-entity Reads (auto-derived from screen plan)` subsection of `_dm_section.md`. Schema:```markdown### Cross-entity Reads (auto-derived from screen plan)- | Calc column | On table | Type | Resolves | Driven by |- |---|---|---|---|---|- | cr3e9_flightnumber_calc | cr3e9_inspection | string | cr3e9_flightid.cr3e9_flightnumber | inspections list |- | cr3e9_gatename_calc | cr3e9_inspection | string | cr3e9_flightid.cr3e9_gateid.cr3e9_gatename | home, inspections list |- | cr3e9_tailnumber_calc | cr3e9_inspection | string | cr3e9_flightid.cr3e9_aircraftid.cr3e9_tailnumber | inspections list |-- **Chained-fetch fields (informational — screen-builder will scaffold these, no schema changes):**-- | Field | On screen | Cardinality | Source |+ | Field | Resolution | Source | Driven by ||---|---|---|---|- | Defect count | inspection detail | 1:many | cr3e9_inspectionzoneid → cr3e9_defect |- | Inspector email | inspection detail | 1:1 | _ownerid_value → systemuser.internalemailaddress |+ | Flight | formatted-lookup | cr3e9_flightid primary display | inspections list |+ | Inspector email | chained-fetch | _ownerid_value → systemuser.internalemailaddress | inspection detail |+ | Gate code | external-projection-required | cr3e9_flightid → cr3e9_gateid → cr3e9_code | home |```In `mode: default` (Step 6a runs because `_screens_section.md` was found), append this subsection to the Step 7 output. In `mode: cross-entity-audit`, append it directly to the existing `_dm_section.md` (read it, append the subsection AFTER `### Notes` if present, otherwise at the end, then write back) and skip Step 7 entirely — return immediately.@@ -252,30 +401,49 @@ Write the section to a file in the working directory named `_dm_section.md` (the- Reuse: <N> existing tables- Extend: <N> tables (add columns only)- Create: <N> new tables across <T> tiers+- Adapt: <N> app-owned aliases created beside incompatible custom schema+- Defer: <N> missing/incompatible dependencies left out of this run+- Unverified: <N> tables discovery could not confirm (re-checked by `/add-dataverse`)++### Planning Evidence++- Deterministic appendix: `<relative planning evidence path>`+- Environment and generated timestamp match the validated snapshot.++### Target Reconciliation++| Required entity | Decision | Existing match | Target evidence | Column decisions | Why |+|---|---|---|---|---|---|+| ... | ... | ... | ... | ... | ... |-### Reuse / Extend / Create+### Decision Rationale-| Required entity | Decision | Match | Why | Missing columns |-|---|---|---|---|---|-| ... | ... | ... | ... | ... |+| Required entity | Selected approach | Strongest alternative | Trade-off and scope boundary |+|---|---|---|---|+| ... | ... | ... | ... |### ER Diagram```mermaiderDiagram- contact ||--o{ cr123_inspection : "has"- cr123_jobsite ||--o{ cr123_inspection : "located at"+ contact {+ guid contactid PK+ string fullname+ }cr123_inspection {- string title- datetime scheduledDate- string photourl "image"+ guid cr123_inspectionid PK+ string cr123_title+ datetime cr123_scheduleddate+ guid cr123_contactid FK+ guid cr123_jobsiteid FK}cr123_jobsite {- string sitename- string address- decimal latitude- decimal longitude+ guid cr123_jobsiteid PK+ string cr123_sitename+ string cr123_address}+ contact ||--o{ cr123_inspection : "has"+ cr123_jobsite ||--o{ cr123_inspection : "located at"```### Creation Order (for `/add-dataverse`)@@ -284,6 +452,9 @@ erDiagram2. **Tier 1** — `cr123_inspection` (lookups: contact, jobsite)3. **Extensions** — add `cr123_photourl` (Image) to existing `cr123_inspection` if it already exists+### Risks and Scope Boundaries+- <only decision-changing risks, projection requirements, migration boundaries, or security/integration coupling>+### Notes- Reuses standard `contact` table — no extension needed.- Image columns require special handling — see add-dataverse/references/dataverse-reference.md.@@ -291,7 +462,166 @@ erDiagram- Signature images from pen input normalize `data:image/png;base64,...` before Image column writes.```-If discovery was skipped (Step 1 or 2 failure), prepend the appropriate warning to the section, omit the "Reuse" column from the table, and fill all decisions as "Create" with a note that the user should re-run with environment access for accurate reuse detection.+Keep the authored section concise: decisions, rationale, ER columns and+relationships, dependency tiers, and risks. Reference the deterministic+appendix for repetitive candidate rankings, table fact counts, collision+checks, and timing evidence instead of copying them into `_dm_section.md`.++### Structured Dataverse schema contract (required for `required` mode)++Alongside `_dm_section.md`, write+`<working_dir>/.tmp/dataverse-schema-contract.json`. This is the deterministic+machine contract consumed after approval; `/add-dataverse` must not reconstruct+metadata operations from Markdown when this sidecar is valid.+Do not invent an `approvedPlanSha256` value here: Step 8 adds that content hash+deterministically only after verifying the gate-owned+`.tmp/mobile-plan-status.json` receipt. That+receipt binds the final plan hash to this exact normalized contract content/hash+and its final structured service dependencies; Step 8 cannot create it.++Use schema version `1` and include every planned table, column, relationship,+and alternate key exactly once. Decisions use only `reuse`, `extend`, `create`,+`adapt`, `defer`, or `unverified`; `replace` and unresolved conflict text are+forbidden. Adapt is fully specified, never inferred later:++- adapted tables include both `adaptedLogicalName` and `adaptedSchemaName`;+- adapted columns include both `adaptedLogicalName` and `adaptedSchemaName`;+- adapted 1:N relationships include `adaptedSchemaName` plus both adapted+ lookup names;+- adapted M:N relationships include `adaptedSchemaName` and+ `adaptedIntersectTable`;+- adapted alternate keys include `adaptedSchemaName`.++Every table/column `SchemaName` must resolve to its paired logical name by the+Dataverse casing rule (for example `cr123_Inspection` →+`cr123_inspection`), including adapted names. Relationship lookup definitions+must resolve to and match the same original/adapted child-column identities.+The lookup column's `requiredLevel` is authoritative; omit the duplicate+relationship value or make it identical.++Only explicit `create` or fully specified `adapt` items may become metadata+writes. Preserve `unverified` as non-executable targeted-read work; never+upgrade it to create. These approved values remain authoritative during Step+8: the deterministic builder may mark verification `verified`, `unverified`,+or `conflict`, but must not change `Reuse`, `Adapt`, or `Defer` into another+architecture decision. Every table includes `dependencyTier` and+`serviceRequired`, including reused tables needed by screens, hooks, lookups,+or identity resolution. An M:N relationship whose generated intersect service+is used by app code sets `serviceRequired: true` on that relationship.++```json+{+ "schemaVersion": 1,+ "publisherPrefix": "cr123",+ "tables": [{+ "logicalName": "cr123_inspection",+ "schemaName": "cr123_inspection",+ "displayName": "Inspection",+ "displayCollectionName": "Inspections",+ "plannedDecision": "create",+ "dependencyTier": 1,+ "serviceRequired": true,+ "ownershipType": "UserOwned",+ "columns": [{+ "logicalName": "cr123_name",+ "schemaName": "cr123_name",+ "displayName": "Inspection Name",+ "type": "string",+ "plannedDecision": "create",+ "primaryName": true,+ "requiredLevel": "ApplicationRequired",+ "maxLength": 200+ }, {+ "logicalName": "cr123_siteid",+ "schemaName": "cr123_siteid",+ "displayName": "Site",+ "type": "lookup",+ "lookupTarget": "cr123_site",+ "plannedDecision": "create",+ "requiredLevel": "None"+ }],+ "relationships": [{+ "kind": "many-to-one",+ "schemaName": "cr123_Site_Inspection",+ "plannedDecision": "create",+ "parentTable": "cr123_site",+ "childTable": "cr123_inspection",+ "lookup": {+ "logicalName": "cr123_siteid",+ "schemaName": "cr123_siteid",+ "displayName": "Site",+ "requiredLevel": "None"+ }+ }],+ "alternateKeys": [{+ "schemaName": "cr123_inspection_name_key",+ "displayName": "Inspection Name Key",+ "plannedDecision": "create",+ "columns": ["cr123_name"]+ }]+ }, {+ "logicalName": "cr123_site",+ "schemaName": "cr123_site",+ "displayName": "Site",+ "displayCollectionName": "Sites",+ "plannedDecision": "create",+ "dependencyTier": 0,+ "serviceRequired": true,+ "ownershipType": "UserOwned",+ "columns": [{+ "logicalName": "cr123_name",+ "schemaName": "cr123_name",+ "displayName": "Site Name",+ "type": "string",+ "plannedDecision": "create",+ "primaryName": true,+ "requiredLevel": "ApplicationRequired",+ "maxLength": 200+ }],+ "relationships": [],+ "alternateKeys": []+ }]+}+```++Supported ordinary `type` values are `string`, `memo`, `integer`, `bigint`,+`decimal`, `double`, `money`, `datetime`, `date`, `boolean`, `choice`,+`multiselectchoice`, `image`, and `file`. Choice/Boolean columns include exact+integer/label `options`. Existing computed dependencies use `computed` plus+`attributeType`, `sourceType`, `sourceTypeMask`, and exact+`formulaDefinition`; new calculated/rollup/formula columns are `defer` because+this workflow does not synthesize them. Lookups are represented both as a+column and as their relationship so coverage is mechanical.+For BigInt, omit `minValue`/`maxValue` unless the plan explicitly needs safely+representable integer bounds; never emit JavaScript-unsafe defaults.++After writing the JSON, normalize and validate it in place:++```bash+node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \+ --normalize-contract "<working_dir>/.tmp/dataverse-schema-contract.json" \+ --output "<working_dir>/.tmp/dataverse-schema-contract.json"+```++If normalization fails, fix the exact schema error and rerun it. Do not return+`DONE` with a malformed or incomplete sidecar. In `cross-entity-audit` mode,+preserve this contract unchanged because that pass adds read-path guidance, not+metadata schema.++**ER column contract:** every relationship endpoint has an attribute block;+each block includes its exact primary key (`PK`), primary name, every displayed+or written business/status column needed by the app, and each shown lookup+(`FK`). Use verified logical names for existing schema and planned logical+names for Create/Extend schema. Mechanically verify that no relationship+endpoint has an empty block and that every relationship's FK path is visible.++If any row is `Adapt` or `Defer`, write the evidence and reason into the section and finish with `DONE_WITH_CONCERNS` naming each one, so the user sees it at Gate 1 and can revise the design before `/add-dataverse` runs. Never return `BLOCKED` for a data-modelling conflict — that status is reserved for hard walls such as an unwritable working directory. If discovery was skipped (Step 1 or Step 2 failure), prepend the matching warning, mark every decision `Unverified`, and say the user should re-run with environment access for accurate reuse detection.++After `_dm_section.md` and the normalized schema contract are written,+atomically update milestone+`artifact-written` with `state: "completed"`, the final decision counts,+elapsed time, and both artifact paths. On a hard failure, write+`state: "blocked"` with the current milestone before returning `BLOCKED`.## Return Status@@ -300,7 +630,7 @@ You MUST return your final message with one of these four status codes as the **| Code | When to use | Example first line ||---|---|---|| `DONE` | Section written cleanly, all entities resolved, no caveats | `DONE` |-| `DONE_WITH_CONCERNS: <comma-separated concerns>` | Section written but you fell back from a planned reuse, guessed a column type, or skipped Dataverse discovery — the user should review before approving Gate 1 | `DONE_WITH_CONCERNS: contact reuse skipped (env access denied), all tables marked Create` |+| `DONE_WITH_CONCERNS: <comma-separated concerns>` | Section written, but discovery was skipped, an entity is `Adapt`/`Defer`/`Unverified`, or a design caveat remains | `DONE_WITH_CONCERNS: contact reuse skipped (env access denied), all decisions unverified` || `NEEDS_CONTEXT: <what is missing>` | Cannot complete without more info from the orchestrator — e.g. requirements brief is too thin to infer entities, or no environment was selected | `NEEDS_CONTEXT: requirements brief lists no nouns; need explicit entity list from user` || `BLOCKED: <reason>` | Hit a hard wall — file system error writing `_dm_section.md`, plugin root unreadable, environment resolver crashed. The planner MUST escalate to the user, never silently retry | `BLOCKED: cannot write to <working_dir>/_dm_section.md (permission denied)` |@@ -313,6 +643,6 @@ You MUST return your final message with one of these four status codes as the **After the status line and a blank line, write:-> Data Model section written to `<working_dir>/_dm_section.md`. Summary: <N reuse, M extend, K create across T tiers>. ER diagram includes <list of entities>.+> Data Model section written to `<working_dir>/_dm_section.md`; normalized contract written to `<working_dir>/.tmp/dataverse-schema-contract.json`. Summary: <N reuse, M extend, K create, A adapt, D defer, U unverified across T tiers>. ER diagram includes <list of entities>.The planner reads the file and embeds the contents verbatim into `native-app-plan.md`.diff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.mdindex 94ca48083..5d824f448 100644--- a/plugins/mobile-apps/agents/native-app-planner.md+++ b/plugins/mobile-apps/agents/native-app-planner.md@@ -25,14 +25,36 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:- Wizard answers collected by the skill (target users + device, target platforms, aesthetic, features)- The working directory where `native-app-plan.md` should be written- The plugin root directory (`${PLUGIN_ROOT}`)+- The foreground-generated normalized Dataverse planning snapshot path, when available+- The deterministic Dataverse planning evidence appendix path, when available+- Dataverse planning mode: `required` or `connector-only`## Hard Rules- **Read-only.** You MUST NOT create Dataverse tables, run `npx power-apps add-data-source`, install npm packages, or write project source code. Architects you spawn MUST also be read-only. All mutation happens later in `/create-mobile-app` after the user approves each section.- **Power Apps CLI failure refresh.** Follow [shared-instructions.md](../shared/shared-instructions.md) command-failure handling for any failed `npx power-apps *` command; retry the original command once after auth is corrected.-- **Single plan document.** Everything goes into `<working_dir>/native-app-plan.md`. No HTML, no separate per-domain files. Mermaid for diagrams.+- **Single human plan document.** Everything user-reviewed goes into+ `<working_dir>/native-app-plan.md`. Deterministic execution uses the+ normalized schema contract plus the gate-owned+ `<working_dir>/.tmp/mobile-plan-status.json` receipt; neither is a second+ human plan or a source+ for free-form Markdown parsing. No HTML or other per-domain plan files.+ Mermaid for diagrams.- **Per-section approval gates.** You enter plan mode four times — once per section. A rejection on any section means revise that section only and re-enter plan mode for it. Do not move on until each section is explicitly approved.- **Sequential then parallel.** Spawn `data-model-architect` first (alone). Plan native capabilities and connectors inline. Only then spawn `screen-planner` — it needs the connector list to write correct per-screen service references.+- **Dataverse planning forwarding is verbatim.** Pass the planning mode to every+ default-mode `data-model-architect` dispatch and revision. In `required`,+ pass both planning-snapshot/evidence absolute paths unchanged. In `connector-only`,+ state that both paths are not supplied. Never invent placeholder artifact+ paths. Do not+ resolve the environment, verify Dataverse access, run broad discovery, or+ issue any live Dataverse+ query in this planner. The foreground orchestrator owns planning-snapshot creation,+ degradation, and exact-name expansion.+- **Do not duplicate raw evidence.** Assemble the architect's concise decisions,+ rationale, ER diagram, tiers, and risks verbatim. Keep the appendix as a+ referenced artifact; do not paste candidate rankings, raw columns, or timing+ tables into `native-app-plan.md`.- **MANDATORY progress reporting.** Every step in the workflow has a `**Print before starting:**` block. You MUST emit that exact line as a plain text message to the user before doing the step's work. Do not skip, do not paraphrase, do not batch them. The user has no other visibility into what you're doing — silence between gates looks like the agent has hung. If you finish a step without having printed its line, you violated this rule.## Step 0 — Tool-surface preflight (MANDATORY — first thing you do)@@ -44,7 +66,8 @@ Required tool surface:- `EnterPlanMode` / `ExitPlanMode` — run the four approval gates- `AskUserQuestion` — industry-confirm and style-picker handoffs- `Read` / `Write` — read references, write `native-app-plan.md`-- `Bash` / `Grep` / `Glob` — discovery (Dataverse probe, working-dir checks)+- `Bash` / `Grep` / `Glob` — working-dir checks and legacy discovery only;+ never use them for Dataverse discovery when planning-snapshot/evidence paths are supplied**Detection:** attempt a no-op call to `Task` (e.g. spawn nothing, just check the tool exists). If the host raises `tool not available`, `unknown tool`, or any equivalent before you can dispatch, you are running in a degraded shell. Same check for `EnterPlanMode` and `AskUserQuestion`.@@ -88,18 +111,38 @@ While the architect runs, complete Steps 3, 3b, and 3c inline. By the time you f>> Requirements: [paste $ARGUMENTS]> Wizard answers: [target users & device, aesthetic, features]-> Target environment: read from `power.config.json` if it exists in the working directory, otherwise use the environment URL or ID provided by the orchestrator and resolve it with `scripts/resolve-environment.js`.+> Target environment: use the foreground-resolved environment URL and tenant.+> When planning-snapshot/evidence paths are supplied, do not read `power.config.json` or+> call `scripts/resolve-environment.js`.> Working directory: [absolute path]> Plugin root: ${PLUGIN_ROOT}+> Dataverse planning mode: [required | connector-only]+> Dataverse planning failure reason: none+> Normalized Dataverse foreground planning snapshot: [absolute path supplied by foreground verbatim, or NOT SUPPLIED]+> Dataverse planning evidence: [absolute path supplied by foreground verbatim, or NOT SUPPLIED]+> Structured schema contract output: [absolute+> `<working_dir>/.tmp/dataverse-schema-contract.json` in required mode, or NOT+> SUPPLIED in connector-only mode]>-> Follow the instructions in your agent file. You are read-only — do NOT create tables. Return a markdown `## Data Model` section ready to embed in native-app-plan.md, including a Mermaid ER diagram, a reuse/extend/create table, and dependency-tier ordering. Return per AGENTS.md rule #10: literal first line is `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:`, then a blank line, then your summary.+> Follow the instructions in your agent file. You are read-only — do NOT create tables. In required mode, return a markdown `## Data Model` section ready to embed in native-app-plan.md and write/normalize the structured schema contract sidecar covering every table, column, relationship, and alternate key. Include a Mermaid ER diagram, a reuse/extend/create table, and dependency-tier ordering. Return per AGENTS.md rule #10: literal first line is `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:`, then a blank line, then your summary.> If requirements mention generated PDFs, report exports, evidence packets, signatures, sign-off, pen/ink, drawings, or uploaded PDFs/documents, include the artifact storage target in the data model: on-device/share-only, Dataverse Image column, Dataverse File column, or child Evidence/Attachment table. Retained PDF content must use a File column, not long text/base64.After spawning, proceed immediately to Step 3 without waiting. Then, before writing the plan doc (Step 4), check the architect's result and parse its first line per AGENTS.md rule #10:-- `DONE` → embed section, continue.-- `DONE_WITH_CONCERNS: <list>` → embed section, propagate concerns.-- `NEEDS_CONTEXT: <missing>` → re-spawn once with missing context. If second return is also `NEEDS_CONTEXT`, return `BLOCKED`.+- `DONE` → in `required` mode, verify both `_dm_section.md` and the normalized+ `.tmp/dataverse-schema-contract.json` exist; then embed the section and+ continue. A missing sidecar is `BLOCKED`, not a Markdown-parsing fallback.+- `DONE_WITH_CONCERNS: <list>` → apply the same sidecar check, embed section,+ and propagate concerns.+- `NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>` → return that+ exact first line to the foreground orchestrator. Do not expand the foreground planning snapshot+ or re-run discovery here.+- `NEEDS_CONTEXT: proposed-dataverse-names:<logical names>` → return that exact+ first line to the foreground orchestrator for collision-only expansion. Do+ not infer absence or rewrite the proposed names here.+- `NEEDS_CONTEXT: <missing>` → re-spawn once with missing non-Dataverse context,+ forwarding the same planning-snapshot/evidence paths unchanged. If the second return+ is also `NEEDS_CONTEXT`, return `BLOCKED`.- `BLOCKED: <reason>` → return `BLOCKED: data-model-architect returned BLOCKED: <reason>` to orchestrator.## Step 3 — Plan Native Capabilities Inline (Gate 2)@@ -328,8 +371,15 @@ Approve? (Reject → revise data model only)Call `ExitPlanMode` to request approval.-- **Approved:** mark `[x] Data model approved` in the plan doc, continue to Gate 2.-- **Rejected:** re-spawn `data-model-architect` with the user's feedback, regenerate that section, re-enter plan mode. Loop until approved.+- **Approved:** mark `[x] Data model approved` in the plan doc and immediately+ initialize/update `<working_dir>/.tmp/mobile-plan-status.json` with the+ normalized contract's exact content/hash and a `dataModel` approval record.+ This receipt is written by this gate-owning planner, never by the Step 8+ manifest builder. Continue to Gate 2.+- **Rejected:** re-spawn `data-model-architect` with the user's feedback and+ the original planning-snapshot/evidence paths verbatim, regenerate that section, and+ regenerate/normalize the structured sidecar, then re-enter plan mode. Loop+ until approved; do not run discovery during a revision.### Gate 2 — Native Capabilities + Connectors (combined)@@ -498,13 +548,17 @@ Reject loop = re-spawn `screen-planner` with the user's feedback (layout, screen### Step 5c — Cross-entity Read Audit (Round 2 data-model pass)**Print before spawning:**-> "→ Auditing the locked screen plan for cross-entity reads (calc-column candidates from related_entity_fields blocks)…"+> "→ Auditing the locked screen plan for supported cross-entity read paths…"-**Run condition:** execute this step ONLY after Gate 4b has been approved AND the screen-planner's per-screen specs include at least one `related_entity_fields` block. Skip silently otherwise (no cross-entity reads = no calc-column proposals needed).+**Run condition:** execute this step ONLY after Gate 4b has been approved AND the screen-planner's per-screen specs include at least one `related_entity_fields` block. Skip silently otherwise.**Detection (cheap):** before spawning, `Grep` the locked plan for `related_entity_fields:` in `<working_dir>/native-app-plan.md`. Zero matches → skip Step 5c entirely, mark `[x]` and proceed to Step 6. One or more matches → spawn the audit pass below.-This step exists because of the runtime constraint documented at [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads) — the SDK has no `$expand`, so cross-entity fields on hot paths (lists, dashboards) MUST be denormalized via calculated columns at the data-model layer. The screen-planner emits `related_entity_fields` per screen; this step turns those into calc-column proposals.+This step exists because the SDK has no `$expand`. It verifies that every+cross-entity field uses a formatted lookup or bounded chained fetch, and flags+hot-path fields that require an externally supplied projection. It never+synthesizes calculated/formula metadata and must preserve the already approved+`.tmp/dataverse-schema-contract.json` unchanged.#### 5c.1 — Spawn `data-model-architect` in `cross-entity-audit` mode@@ -530,22 +584,23 @@ Wait for return; apply the Step 3.0 status switch:- `DONE_WITH_CONCERNS: <list>` → embed addendum, propagate concerns into your own final `DONE_WITH_CONCERNS:`.- `NEEDS_CONTEXT:` / `BLOCKED:` — propagate up per the standard switch.-#### 5c.2 — Gate 1 addendum (calc-column approval)+#### 5c.2 — Gate 1 addendum (cross-entity read paths)If 5c.1 wrote a `### Cross-entity Reads` addendum, present it to the user as a Gate 1 addendum (NOT a fresh Gate 1 — the original schema is already approved and unchanged):```## Gate 1 — Addendum: Cross-entity Reads-The screen plan you approved at Gate 4b reads N fields from related entities (gate names on inspections, customer phones on orders, etc.). Because the Power Apps SDK has no $expand, those fields need calculated columns on the parent tables to display efficiently — otherwise list screens would either render "—" or trigger N+1 fetches per row.+The screen plan reads N fields from related entities. The generated SDK has no+$expand, so each field must use a formatted lookup, a bounded chained fetch, or+an external server-owned projection.-Proposed calculated columns (auto-derived from your screen plan, no schema reshape):+Proposed read paths:[paste the ### Cross-entity Reads table from _dm_section.md]-[paste the Chained-fetch fields (informational) table if present — these need NO schema change, the screen-builder handles them at scaffold time]--Approve to add these calc columns to the data model? (Reject → revise the audit. Approve → /setup-datamodel will create them in Phase 6.1b.)+Approve these read paths? Any `external-projection-required` row remains a+blocker until the user supplies that projection outside this workflow.```Reject loop = re-spawn data-model-architect in `mode: cross-entity-audit` with the user's feedback (e.g. "drop cr3e9_tailnumber_calc, the list doesn't actually show it"). Approve = mark `[x]` Gate 1 addendum approved, proceed to Step 6.@@ -563,6 +618,79 @@ node "${PLUGIN_ROOT}/scripts/validate-mobile-files.js" --project-root "<working_Repair reported violations and rerun until it exits `0`. Pass exact changed files, never the whole project root.+In `required` mode, also validate the schema sidecar structurally one final+time:++```bash+node "${PLUGIN_ROOT}/scripts/build-dataverse-operation-manifest.js" \+ --normalize-contract "<working_dir>/.tmp/dataverse-schema-contract.json" \+ --output "<working_dir>/.tmp/dataverse-schema-contract.json"+```++The gate-owning planner must now finalize the pre-existing+`<working_dir>/.tmp/mobile-plan-status.json` receipt from the approved+screen/hook/identity/lookup service requirements. The receipt has this+deterministic shape:++```json+{+ "schemaVersion": 1,+ "workflow": "create-mobile-app",+ "approvals": {+ "dataModel": {+ "status": "approved",+ "approvedAt": "<ISO timestamp from Gate 1 acceptance>",+ "approvedContractSha256": "<sha256 of stable normalized contract content>"+ },+ "nativeCapabilities": {+ "status": "approved",+ "approvedAt": "<ISO timestamp>"+ },+ "connectors": {+ "status": "approved",+ "approvedAt": "<ISO timestamp>"+ },+ "screenPlan": {+ "status": "approved",+ "approvedAt": "<ISO timestamp>"+ }+ },+ "approvedPlanSha256": "<sha256 of final native-app-plan.md bytes>",+ "approvedContractSha256": "<same contract hash as dataModel approval>",+ "approvedContract": { "<exact normalized contract content>": "..." },+ "serviceRequiredTables": [+ {+ "logicalName": "cr123_inspection",+ "consumers": ["screen:Inspections", "screen:Inspection detail"]+ }+ ],+ "integritySha256": "<sha256 of stable receipt JSON without this field>"+}+```++Every row requires at least one deterministic consumer identifier. Its exact+logical-name set must equal the non-deferred `serviceRequired` table and M:N+intersect declarations in the normalized schema contract. If the final screen+plan introduces a service not present there, revise and re-approve the affected+earlier section rather than silently changing the contract.++Initialize the receipt when Gate 1 is accepted, then advance its other approval+records, current plan hash, and final service dependencies only when this same+planner accepts the corresponding existing gates. Before revising an approved+section, mark that section and dependent later sections non-approved; refresh+the receipt only after the existing approval loop accepts the revision.+Do not call the manifest builder to create or restamp this receipt. The local+filesystem trust model is non-adversarial: integrity hashes detect accidental+or out-of-workflow replacement, not a malicious process that can rewrite every+project artifact. Step 8 only consumes and verifies the completed receipt.++Do not return `DONE` if this fails. Connector-only mode must not create the+sidecar. Treat every `unverified` contract row as non-executable; only explicit+`create` or fully specified `adapt` rows may later become metadata operations.+Adapt rows must carry all adapted logical/schema/intersect names required by+the data-model-architect contract, rather than leaving names for the execution+agent to invent.+## Step 7 — Return StatusYou MUST return your final message to `/create-mobile-app` with one of these four status codes as the **literal first line** (no markdown, no preamble, no `Status:` prefix, no backticks). The orchestrator parses the first line to decide what to do next. After the status line, leave a blank line, then write the structured summary below.@@ -586,6 +714,8 @@ You MUST return your final message to `/create-mobile-app` with one of these fouPlan approved.Plan document: <absolute path to native-app-plan.md>+Dataverse schema contract: <absolute path, or "not applicable">+Mobile plan approval receipt: <absolute path, or "not applicable">Sections approved:✓ Data model — <N tables: M reuse, K extend, L create>diff --git a/plugins/mobile-apps/agents/screen-builder.md b/plugins/mobile-apps/agents/screen-builder.mdindex 476d60d52..6bc996f84 100644--- a/plugins/mobile-apps/agents/screen-builder.md+++ b/plugins/mobile-apps/agents/screen-builder.md@@ -32,7 +32,7 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil- **Use shared code via path aliases — NEVER re-define inline.** The project has `@/components`, `@/hooks`, `@/utils`, `@/tokens` configured in tsconfig. Import from them:- **Components:** `import { LoadingState, ErrorState, EmptyState, ScreenHeader, ModalHeader, BottomActionBar, FloatingActionButton, FilterChipRow, FormField, RowPick, StatusPill, AvatarInitials, InfoRow, ActionRow, SectionHeader } from '@/components'`- **Hooks:** `import { useListData, useCursorListData, useSearchFilter } from '@/hooks'` — use `useListData` only for bounded list screens whose spec says `pagination: none`. For unbounded Dataverse screens whose spec says `pagination: cursor`, use `useCursorListData`, `useInfiniteQuery`, or an app-specific cursor hook generated by the orchestrator. Use `useSearchFilter` only for bounded client-side lists; cursor lists must push search into the service call with `filter`.- - **Utils:** `import { formatDate, formatDateTime, formatRelative, truncate, pluralize, choiceLabel, STATUS_TONES } from '@/utils'`+ - **Utils:** `import { formatDate, formatDateTime, formatRelative, truncate, pluralize, choiceLabel, STATUS_TONES } from '@/utils'`. Dynamic Dataverse routes additionally import `normalizeDataverseGuid`.- **Generated:** `import { FooService } from '@/generated/services/FooService'` and `import type { Foo } from '@/generated/models/FooModel'`- **Native:** `import { captureFromCamera } from '@/native/camera'`Do NOT define `function LoadingState()`, `function formatDate()`, `function Field()`, `function Section()`, or status color maps inside your screen. Do NOT write the `useState(loading) + useFocusEffect(load) + onRefresh` pattern manually — use `useListData` instead.@@ -116,26 +116,26 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil```For lookup labels, select the real `_<lookup>_value` field in your `$select` and read with `lookupName(record, '<lookupLogicalName>')`. For choice / status / boolean / datetime / money labels, read with `formattedValue(record, '<columnLogicalName>')` or fall back to the generated option const. On bounded lists that use `useSearchFilter(...)`, fields MUST be real string properties from generated types; never add an inferred display-name field just to make search prettier. Cursor lists do not use `useSearchFilter`; they push search into the service `filter` option.-- **HARD RULE — Cross-entity Field Resolution.** Before writing the screen's `select: [...]` or load step, walk every UI field your spec displays. For each field that sources data from an entity OTHER than the screen's primary fetch target, follow this algorithm exactly. The full reference (with cost-profile rationale, calc-column naming, and pattern examples) is at [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads). The screen-builder MUST apply the rule mechanically — do NOT invent your own resolution.+- **HARD RULE — Cross-entity Field Resolution.** Before writing the screen's `select: [...]` or load step, walk every UI field your spec displays. For each field that sources data from an entity OTHER than the screen's primary fetch target, follow this algorithm exactly. The full supported-path reference is at [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads). The screen-builder MUST apply the rule mechanically — do NOT invent your own resolution.- 1. **Calc column check first.** Open `src/generated/models/<PrimaryEntity>Model.ts` and search for a column matching `<prefix>_<field>_calc` (or any `_calc`-suffixed column resolving the field you need). If present, add it to your `select: [...]` and render directly. Done — no chained fetch needed.- 2. **No calc column? Branch on screen archetype × cardinality** (archetype is in your spec under `**Archetype:**`):+ 1. **Follow the planned recommendation** from `related_entity_fields`.- | Archetype | Cardinality | Action |+ | Recommendation | Action ||---|---|---|- | List (`top ≥ 5`), Tab-root, Dashboard | 1:1 (N:1 lookup chain) | **STOP — do NOT chain a fetch in the list `map()` / `renderItem`.** Emit a `// TODO(cross-entity-read):` header comment naming the field, the related entity, and the recommended `<prefix>_<field>_calc` column to add. Render the cell as `'—'` for now. Then return `BLOCKED [<screen_name>]: list field <field> requires cross-entity read; needs calc column <prefix>_<field>_calc on <primary_entity> — re-run /setup-datamodel (or /add-dataverse for existing apps) to add the calc column.` Do NOT scaffold an N+1 fetch storm. |- | Detail (single record) | 1:1 (N:1 lookup chain) | Scaffold a chained `<RelatedService>.get(record._<lookup>_value, { select: [...] })` in the screen's load step. One record on screen = one extra round trip is fine. Display via `lookupName(...)` or direct field read. |- | Any | 1:many or M:N | Scaffold a chained `<ChildService>.getAll({ filter: \`_<parentid>_value eq '${id}'\`, select: [...] })`. Calc columns CANNOT traverse 1:many or M:N — chained fetch is the ONLY pattern. |+ | `formatted-lookup` | Select the real `_<lookup>_value` field and render `lookupName(record, '<lookupLogicalName>')`. |+ | `chained-fetch` | Perform one bounded related `get` / `getAll` in the screen load step, never inside `map()` or `renderItem`. |+ | `external-projection-required` | Render no fake fallback data. Return `BLOCKED` and name the field/source. The user must supply a supported server-owned projection outside this workflow. |- 3. **Verify before exit.** Every UI field in your spec must have either (a) a `select` entry on the primary fetch (covered by direct column or calc column) OR (b) a chained fetch path. If a field has neither, return `BLOCKED [<screen_name>]: field <field> on <screen> has no fetch path — add to spec or add calc column`.+ 2. **Verify before exit.** Every UI field in your spec must have either a+ primary select, formatted lookup annotation, or bounded chained fetch.+ Otherwise return `BLOCKED [<screen_name>]: field <field> requires an external projection`.- 4. **TODO comment shape** (when emitting at step 2 / list branch):+ 3. **TODO comment shape** for an external projection:```ts// TODO(cross-entity-read): screen displays <field> from related <entity>.- // Re-run /setup-datamodel (or /add-dataverse for existing apps) and add calc- // column <prefix>_<field>_calc to <primary_entity> for one-round-trip reads.- // List screens MUST NOT chain fetches in renderItem — N+1 storm.+ // Supply a maker-created formula column or another server-owned projection,+ // then rerun Dataverse reconciliation. Never chain reads in renderItem.```- **HARD RULE — server-managed columns are NEVER in a create or update payload.** The Dataverse server owns these fields; including them in a `*Service.create({...})` or `*Service.update({...})` returns HTTP 400 on every save. Generated `create()` types may include server-managed fields (`ownerid`, `statecode`, primary IDs, etc.) because they mirror the full model; do **not** satisfy those types by emitting junk values. For any screen with create/update behavior, use a narrow write helper/type whose input contains only editable fields. If the skeleton imports an app-level helper, call it; otherwise define the helper inside your assigned screen file. Do **not** create or modify shared `src/utils/`, `src/hooks/`, or service files from a screen-builder. Forbidden keys in any create/update payload:@@ -153,12 +153,17 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil};export async function createTask(input: CreateTaskInput): Promise<void> {- const payload: Record<string, unknown> = {+ type CreateFields = Pick<+ Parameters<typeof Cr3e9_tasksService.create>[0],+ 'cr3e9_name' | 'cr3e9_status' | '[email protected]'+ >;+ const payload: Omit<CreateFields, '[email protected]'>+ & Partial<Pick<CreateFields, '[email protected]'>> = {cr3e9_name: input.title,cr3e9_status: input.status,};if (input.projectId) {- payload['[email protected]'] = `/cr3e9_projects(${input.projectId})`;+ payload['[email protected]'] = `/cr3e9_projects(${input.projectId})`;}const result = await Cr3e9_tasksService.create(payload as Parameters<typeof Cr3e9_tasksService.create>[0]);@@ -168,17 +173,22 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil- **If a create flow needs the new record immediately, pre-generate its Dataverse ID.** Do not navigate, upload, create child rows, or build lookup binds from `result.data?.<primaryid>`. Use the create-then-navigate rule below: call `newId()` from `@/utils`, include the primary ID field in the create payload, check `result.success`, then navigate/bind/upload using the ID you generated before the POST. This is the only safe pattern for flows like scan → detail, create parent → child form, or create evidence row → upload image.- **Dynamic route IDs are untrusted.** Detail/edit/upload screens that read `useLocalSearchParams()` MUST normalize and validate the route ID before any Dataverse service call. Treat missing values and literal strings like `'undefined'` / `'null'` as invalid. Never pass `String(params.id ?? '')` directly into `Service.get(id)`, `Service.update(id, ...)`, or `Service.upload(id, ...)`; `enabled: !!id` is not enough because `'undefined'` is truthy. Required pattern:```ts- const id = normalizeRouteId(params.id);- const validId = isDataverseId(id);- const query = useQuery({ enabled: validId, queryFn: () => Service.get(id) });- if (!validId) return <MissingRecordIdState />;+ const params = useLocalSearchParams<{ id?: string | string[] }>();+ const rawId = Array.isArray(params.id) ? params.id[0] : params.id;+ const id = normalizeDataverseGuid(rawId);+ const query = useQuery({+ enabled: !!id,+ queryFn: () => Service.get(id!),+ });+ if (!id) return <MissingRecordIdState />;```+ Import `normalizeDataverseGuid` from `@/utils`. Do not invent alternate ID helpers or an inline UUID regex.- **Lookup writes use `@odata.bind`, NEVER raw GUIDs.** When a form creates or updates a record with a parent reference (Task → Project, Comment → Task, Inspection → Site, etc.), the foreign key field is set with the entity-bind syntax. Setting it any other way either silently saves `null` (data loss — form looks like it succeeded) or 400s with a cryptic Dataverse error.- - **Required pattern** — use the lookup's **schema name** (PascalCase navigation property), suffix with `@odata.bind`, value is `/<entitySetName>(<guid>)`:+ - **Required pattern** — open the generated target model and copy the exact quoted property ending in `@odata.bind`; value is `/<entitySetName>(<guid>)`:```tsawait Cr3e9_tasksService.create({cr3e9_name: title,- '[email protected]': `/cr3e9_projects(${projectId})`,+ '[email protected]': `/cr3e9_projects(${projectId})`,cr3e9_status: TaskStatus.Open, // choice = number});```@@ -186,12 +196,19 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil```ts{ _cr3e9_project_value: projectId } // _value props are READ-ONLY; silently dropped on create{ cr3e9_project: projectId } // raw GUID on nav property; 400- { '[email protected]': projectId } // missing /entitySet(guid) wrapper; 400+ { '[email protected]': projectId } // missing /entitySet(guid) wrapper; 400```- **Finding the right names:**- - **Schema name** (left of `@odata.bind`): the lookup column's PascalCase logical name, usually exposed in the generated model file (`src/generated/models/<Entity>Model.ts`). Often differs from the `_value` read property by case + dropped underscore (read `_cr3e9_project_value`, write `[email protected]`).+ - **Write property** (left of `@odata.bind`): use the exact key declared in `src/generated/models/<Entity>Model.ts`. It is case-sensitive and may be lowercase even when raw Web API metadata exposes a PascalCase navigation property. Never guess or transform the read `_value` property.- **Entity set name** (inside `/(...)`): always the **plural** logical collection name — `cr3e9_projects`, not `cr3e9_project`. Use `pluralName` from the model file or check the generated service filename (`Cr3e9_projectsService.ts` ⇒ entity set is `cr3e9_projects`).- - When in doubt, grep `@odata.bind` in `src/generated/services/` for an existing example, or ask the `microsoft-learn` MCP server. Full reference: [`skills/add-dataverse/references/dataverse-reference.md` § Setting Lookups](${PLUGIN_ROOT}/skills/add-dataverse/references/dataverse-reference.md#setting-lookups-creatingupdating-records).+ - Grep `@odata.bind` in the generated **model**, not the generated service. If the key is absent, return `BLOCKED` rather than inventing it.+ - **Typed payload rule:** do not start write payloads as `Record<string, unknown>`. Define a `Pick<Parameters<typeof Service.create|update>[N], ...>` containing the exact writable keys, then use a single boundary cast only when generated base types incorrectly require server-managed fields. This makes misspelled or wrongly-cased lookup keys fail TypeScript.+ - **Lookup filter rule:** generated mobile services do not reliably support raw Web API relationship traversal such as `lookupNav/relatedColumn eq ...`. Query the related table service first, then filter the source table using its read lookup GUID property (`_lookuplogicalname_value eq <guid>`).+- **Authenticated profile rule:** when the plan links a profile table to `systemuser`, import the generated `SystemusersService`. Resolve token `oid → systemuserid` by filtering `azureactivedirectoryobjectid`, and reject disabled, missing, or duplicate users.+ - Before writing the profile filter, open the generated profile model and locate the exact declared read lookup property for the planned `systemuser` lookup column. For a planned lookup logical name such as `new_systemuserid`, the expected shape is `_new_systemuserid_value`, but the generated model declaration is authoritative.+ - Copy that exact model property into the filter: `<exact_generated_lookup_read_key> eq <systemuserid>`. Never emit guessed placeholders such as `_lookup_value`, `_systemuserlookup_value`, or `_<table>_value`.+ - If the planned lookup column is absent, multiple candidate `systemuser` lookups exist, or the exact read key is not declared in the generated model, return `BLOCKED [<screen_name>]: exact systemuser lookup read key not verified`. Do not fall back to email matching or relationship traversal.+ - If `SystemusersService` is absent from the Generated Services snapshot, return `BLOCKED`; do not invent a raw Web API client.- **Form picker UI** — when the form's spec calls for a parent picker (e.g., "select Project"), the picker stores the selected record's `id` (GUID string), and the submit handler converts it to the bind string at write time. Never store the bind string in component state — only in the API payload.- **Pagination rule:** If your spec says `pagination: cursor`, do NOT use `useListData` or `useSearchFilter`. Use the skeleton's `useCursorListData` call, React Query's `useInfiniteQuery`, or an app-specific `use<Entity>CursorList` hook with FlatList `onEndReached` per the pattern in [`data-performance.md`](${PLUGIN_ROOT}/shared/references/data-performance.md). Never fetch all records at once, and never treat `top: 50` as pagination. Real generated Dataverse services use SDK `maxPageSize` for page size and return `IOperationResult.skipToken` for the next page; pass that value back as `skipToken`. Always include deterministic `orderBy` with a unique key and `select` in the service call. Push search/filter into Dataverse with `filter`. If the generated service in the app does not expose `maxPageSize`/`skipToken` for an unbounded table, return `BLOCKED [<screen_name>]: generated service does not expose cursor paging for <Service>; do not downgrade to useListData`.@@ -940,7 +957,13 @@ Before finishing the screen, mentally verify:24. **Forms wrap content in `<KeyboardAvoidingView>`** with `behavior="padding"` on iOS.25. **Form submit calls `router.back()` on success by default.** Exception: create-then-navigate workflows that immediately continue into the created record MUST pre-generate a Dataverse GUID with `newId()` from `@/utils` (which wraps `Crypto.randomUUID()`), include it as the primary ID field in the create payload, then navigate using that known ID. Do not read the new ID from `result.data`, and do not refetch/search after create just to find it. Never use meaningful/sensitive IDs, and do not use this exception for normal saves, bulk inserts, or sample data unless an immediate follow-up operation requires the ID.25. **Route intent matrix is enforced in code.** Singleton routes use `router.navigate(...)`; detail drill-down uses `router.push(...)`; auth/guard redirects use `router.replace(...)`. `router.push(...)` to known singleton routes is a generation error.-25. **Dynamic route IDs are validated before Dataverse calls.** Every detail/edit/upload route normalizes `useLocalSearchParams()` values and rejects missing, `'undefined'`, `'null'`, or non-GUID IDs before calling `Service.get`, `Service.update`, or `Service.upload`. `enabled: !!id` is not sufficient. Bug killed: HTTP 400 `table(undefined)` after create-then-navigate.+25. **Dynamic route IDs use the shared Dataverse GUID normalizer before every Dataverse call.** Every detail/edit/upload route MUST import `normalizeDataverseGuid` from `@/utils`; never write an inline UUID/GUID regex. Normalize array-valued Expo params first, then call the helper:+ ```ts+ const params = useLocalSearchParams<{ id?: string | string[] }>();+ const rawId = Array.isArray(params.id) ? params.id[0] : params.id;+ const id = normalizeDataverseGuid(rawId);+ ```+ Reject an undefined result before calling `Service.get`, `Service.update`, `Service.delete`, `Service.upload`, or `Service.download*`. `enabled: !!rawId`, a generic RFC UUID validator, and checks for only `'undefined'` / `'null'` are forbidden. Dataverse sequential GUIDs do not guarantee RFC version bits. Bug killed: valid Dataverse IDs rejected locally and HTTP 400 `table(undefined)` after create-then-navigate.25. **Scanner Dataverse writes are locked and reset on focus.** Any scanner callback that creates/updates Dataverse rows, uploads evidence, or navigates to a created record uses a `useRef` in-flight lock plus `paused` state, passes `paused` and `resetKey` to `BarcodeScannerView`, resets lock/paused/resetKey inside `useFocusEffect`, and routes manual code entry through the same guarded mutation. Bug killed: rapid QR callbacks creating duplicate or broken scan rows, and scanner stuck when returning from detail.25. **Camera evidence screens show a visible Take picture action.** Any evidence/photo capture flow has a first-class `Take picture` / `Take evidence photo` button wired to `takePhoto()` from `src/native/camera`. Gallery/upload/file picker actions may exist only as secondary siblings, never as the only visible capture path. Bug killed: evidence screen where camera capture exists technically but users cannot find it.26. **Create / update payloads NEVER include server-managed columns.** Forbidden keys in any `*Service.create({...})` or `*Service.update({...})` object literal: `ownerid`, `owneridtype`, `statecode`, `statuscode`, `importsequencenumber`, `overriddencreatedon`, `timezoneruleversionnumber`, `utcconversiontimezonecode`, `versionnumber`, `createdon`, `modifiedon`, `createdby`, `modifiedby`. If the generated model type marks them required, put the unavoidable cast inside the narrow write helper — never emit junk like `ownerid: ''` or `statecode: 0` to satisfy the type. Bug killed: every HTTP 400 on save.diff --git a/plugins/mobile-apps/agents/screen-planner.md b/plugins/mobile-apps/agents/screen-planner.mdindex e1982db91..07062b3f1 100644--- a/plugins/mobile-apps/agents/screen-planner.md+++ b/plugins/mobile-apps/agents/screen-planner.md@@ -210,12 +210,14 @@ Always include these baseline screens (already in template — keep them):Then design the user's screens. For a typical CRUD app:- **List screen** per primary entity (e.g., `accounts/index.tsx`)-- **Detail screen** per primary entity (e.g., `accounts/[id].tsx`)+- **Detail screen** per primary entity (e.g., `accounts/[id].tsx` when it has no children, or `accounts/[id]/index.tsx` when it owns child workflows)- **Create/edit form screen** per primary entity (e.g., `accounts/new.tsx`, `accounts/[id]/edit.tsx`)- Plus any workflow-specific screens (e.g., `capture-receipt.tsx`)**Folder rule (HARD — prevents phantom tabs):** any entity that has children (`[id]`, `new`, `edit`, sub-screens) becomes a **folder** with `<entity>/index.tsx` for the list/root view and the children inside. Never use a flat `accounts.tsx` AND a sibling `accounts/[id].tsx` — expo-router auto-registers every top-level `.tsx` under `app/(app)/` as a tab/drawer entry, so a flat `accounts.tsx` next to an `accounts/` folder produces both a phantom "accounts" tab AND the real "accounts" tab. Folders collapse the whole stack into one navigable entry.+**Dynamic-route collision rule (HARD):** never emit both `<parent>/[id].tsx` and `<parent>/[id]/<child>.tsx`. Expo Router maps the file and folder to the same `[id]` navigator entry and crashes with `duplicate screen named '[id]'`. When a detail route has child workflows, its detail file is `<parent>/[id]/index.tsx`; child files and `_layout.tsx` live in that same `[id]/` folder.+Decision rule per top-level destination:| Destination has any sub-routes? | Layout |@@ -226,7 +228,10 @@ Decision rule per top-level destination:Examples:- `home.tsx` (no children) → flat file `app/(app)/home.tsx`- `profile.tsx` (no children) → flat file `app/(app)/profile.tsx`-- `inspections` (list + detail + form) → folder `app/(app)/inspections/` with `index.tsx`, `[id].tsx`, `new.tsx`+- `inspections` (list + detail + form, no detail children) → folder `app/(app)/inspections/` with `index.tsx`, `[id].tsx`, `new.tsx`+- `inspections` (detail owns photo/edit children) → `app/(app)/inspections/[id]/index.tsx`, `app/(app)/inspections/[id]/photo.tsx`, and `app/(app)/inspections/[id]/edit.tsx`; never also create `inspections/[id].tsx`++**Authenticated Dataverse identity rule:** when app identity links through `systemuser`, require `SystemusersService` in the data-source/service plan and record the profile table's planned `systemuser` lookup logical column. Resolve the access-token `oid` with `SystemusersService.getAll({ filter: "azureactivedirectoryobjectid eq <oid> and isdisabled eq false", top: 2 })`. The screen-builder must open the generated profile model and use the exact declared read property corresponding to that lookup column (for example `_new_systemuserid_value` for `new_systemuserid`). Never put generic placeholders such as `_lookup_value` or `_systemuserlookup_value` in a concrete filter, and do not use relationship traversal (`lookupNavigation/azureactivedirectoryobjectid`).Keep total screen count tight — under 8 for v0 unless the requirements explicitly demand more. The user can iterate later.@@ -379,7 +384,7 @@ For each screen the user adds, provide this compact shape:- **Profile content** — REQUIRED on the Profile screen only. List 2-4 app-specific profile sections based on the app requirements and target users, for example `Role + team`, `Assigned site/territory`, `Default queue filters`, `App support/contact`, `Environment/app version`. Include any generated service needed for those sections; otherwise use local/static app context plus `useAuth()`.- **Sign-out affordance** — REQUIRED on the Profile screen and omitted from every other screen. Write `visible Button "Sign out" using useAuth().signOut with confirm`; sign-out returns to `/login` after completion.- **Data** — which generated services it calls, with method names (e.g., bounded lookup: `AccountsService.getAll({ top: 50, orderBy: ['name asc'], select: ['name'] })`; cursor list: `InspectionsService.getAll({ maxPageSize: 50, orderBy: ['scheduledDate asc', 'inspectionid asc'], select: [...] })` plus `skipToken` continuation support)-- **Related entity fields** (REQUIRED if any UI field on the screen displays data from an entity OTHER than the primary `Data` service's table; OMIT entirely otherwise) — one entry per cross-entity field. The `data-model-architect`'s Step 6a Cross-entity Read Audit reads this block to decide which calculated columns to propose. Mechanical schema:+- **Related entity fields** (REQUIRED if any UI field on the screen displays data from an entity OTHER than the primary `Data` service's table; OMIT entirely otherwise) — one entry per cross-entity field. The `data-model-architect` audits that each field has a supported read path. Mechanical schema:```yamlrelated_entity_fields:@@ -387,16 +392,19 @@ For each screen the user adds, provide this compact shape:source: <dotted path from primary entity to resolved column, e.g. cr3e9_flightid → cr3e9_gateid → cr3e9_gatename>cardinality: "1:1" | "1:many" | "M:N"archetype_class: list | detail | tab-root | dashboard- recommends: calc-column | chained-fetch+ recommends: formatted-lookup | chained-fetch | external-projection-required```**Mechanical derivation of `recommends`** (no judgement — pick from this table):| `archetype_class` | `cardinality` | `recommends` ||---|---|---|- | `list`, `tab-root`, `dashboard` | `1:1` | `calc-column` |+ | `list`, `tab-root`, `dashboard` | direct lookup primary display | `formatted-lookup` |+ | `list`, `tab-root`, `dashboard` | any other `1:1` related field | `external-projection-required` || `detail` | `1:1` | `chained-fetch` |- | any | `1:many` or `M:N` | `chained-fetch` (calc columns can't traverse) |+ | `list`, `tab-root`, `dashboard` | `1:many` or `M:N` per-row field/aggregate | `external-projection-required` |+ | `detail` | `1:many` | `chained-fetch` |+ | `detail` | `M:N` | `external-projection-required` unless a generated intersect-table service and exact bounded query contract are already named in the approved data model |**`archetype_class` mapping from `Archetype`:** `List` → `list`; `Tab-root` → `tab-root` (or `dashboard` if `Operational pattern: home-dashboard` / `assignment-dashboard`); `Detail` → `detail`; `Form` / `Modal-Sheet` / `Auth` / `Empty-onboarding` → `detail` (cold path, single-record context).@@ -410,22 +418,22 @@ For each screen the user adds, provide this compact shape:source: cr3e9_flightid → cr3e9_flightnumbercardinality: "1:1"archetype_class: list- recommends: calc-column+ recommends: formatted-lookup- field: "Gate name"source: cr3e9_flightid → cr3e9_gateid → cr3e9_gatenamecardinality: "1:1"archetype_class: list- recommends: calc-column+ recommends: external-projection-required- field: "Defect count"source: cr3e9_inspectionzoneid → cr3e9_defect (1:many)cardinality: "1:many"archetype_class: list- recommends: chained-fetch+ recommends: external-projection-required```**Hard rule:** if the screen displays a related-entity field but you do NOT emit a `related_entity_fields` block for it, the data-model-architect cannot propose the calc column, the screen-builder will hit `BLOCKED` at scaffold time, and the user will see a `—` cell in the built app. The block is the ONLY signal — there is no fallback inference.- **Audit** (omit for read-only / non-write screens) — one line per audit-bearing action: `<trigger>: event <code> (<event label>); payload: <field, field, field>`. Example: `On submit: event 100000006 (Inspection Submitted); payload: inspectionId, submittedAt, defectCount, openCriticalCount.` The screen-builder wraps the payload field list in `JSON.stringify({...})` and writes the full `cr3e9_audit_log_entriesService.create(...)` call from the Generated Services table — do NOT spell out the wrapper or service name.-- **Lookup writes** — for form/edit screens that set a parent reference (Task → Project, Comment → Task, etc.), explicitly list each lookup field with its `@odata.bind` name + entity set, e.g. `'[email protected]': '/cr3e9_projects(<guid>)'`. Without this the screen-builder will guess and silently lose the relationship. Skip for read-only and no-lookup screens.+- **Lookup writes** — for form/edit screens that set a parent reference (Task → Project, Comment → Task, etc.), explicitly copy the exact quoted `@odata.bind` property from the generated target model and pair it with the entity set, e.g. `'[email protected]': '/cr3e9_projects(<guid>)'` when that exact key exists in `src/generated/models/<Entity>Model.ts`. Never derive casing from Dataverse schema-name conventions. Without the generated-model key, mark the spec `BLOCKED: lookup write key not verified`. Skip for read-only and no-lookup screens.- **Pagination** — `cursor` if the table has no natural record ceiling (visits, inspections, work orders, tickets, any user-created records over time); `none` if the table is a bounded lookup (status types, categories, job types). When `cursor`, include SDK `maxPageSize: 50`, deterministic `orderBy` with a unique key, `select`, `skipToken` continuation support, and server-side `filter` for search in the data spec. Do not imply that `top: 50` alone is pagination.- **Native capabilities** — which native modules/wrappers it uses, and which iOS/Android platforms or permission states need fallback handling. For PDF/pen screens, be precise: `document-picker` (`expo-document-picker`) for user-picked files; `pdf-report` (`expo-print`, plus `expo-sharing` only when present and sharing is required) for generated local PDFs; `native-pdf-viewer` (`@microsoft/power-apps-native-pdf-viewer` 0.2.9+) for HTTPS PDF URLs and local `file://` URIs; `pen-input` (`@microsoft/power-apps-native-pen-input`) for signature/ink capture. For location screens, distinguish `geolocation` (`@microsoft/power-apps-native-bglocation`) — continuous/background tracking with native Dataverse sync, needs start/stop/tracking-status UI plus a permission-denied state — from one-shot `location` (`expo-location`) for a single foreground coordinate read.- **Calendar library** — REQUIRED for screens with `Calendar pattern` unless the pattern is `timeline-day-list`. Write `react-native-calendars` and name the exact components expected, for example `CalendarProvider`, `ExpandableCalendar`, `AgendaList`, `Calendar`, `CalendarList`, or `Agenda`. The package must also appear in `### JavaScript Dependencies`; the screen-builder imports it directly after the orchestrator installs it. No `/add-native` wrapper or native rebuild is involved.@@ -472,7 +480,7 @@ This is the target shape for every spec. ~120 words, ~450 tokens. No inlined cat- **UX contract:** header title = current zone name; primary action = `Save & Continue` bottom CTA; disabled reason = "Capture required photo first" when evidence missing; FAB = `extended FAB` on defects, label "Add defect"; badge count = `defects.filter(d => d.zone === currentZone).length`.- **Data:** `Cr3e9_zoneprogressService.getAll({ filter: 'cr3e9_inspectionid eq <id>', orderBy: 'cr3e9_zone asc' })`, `Cr3e9_zoneprogressService.update(...)` on save.- **Audit:** On zone Save: event 100000001 (Zone Step Completed); payload: zoneIndex, zoneName, completedAt, evidenceCount, defectCount.-- **Lookup writes:** `'[email protected]': '/cr3e9_inspections(<id>)'` on every zone-progress upsert.+- **Lookup writes:** exact generated-model key, for example `'[email protected]': '/cr3e9_inspections(<id>)'`, on every zone-progress upsert.- **Pagination:** `none` (6-row bounded set).- **Native capabilities:** `expo-camera`, `expo-image-picker` (capture tiles).- **Navigation:** from inspection detail; pushes to defect form; pops back to inspection summary on last zone Save.@@ -533,7 +541,7 @@ Section format (same in all phases):| OAuth callback | `/oauth-callback` | `app/oauth-callback.tsx` | default | Connector consent return | — | — | template (keep) || Home | `/(app)/home` | `app/(app)/home.tsx` | default | Today dashboard: assignment, progress, stats, recent inspections | `cr123_inspectionService.getAll({ top: 5 })` | — | replace template || Inspections list | `/(app)/inspections` | `app/(app)/inspections/index.tsx` | default | List + filter | `cr123_inspectionService.getAll` | — | new |-| Inspection detail | `/(app)/inspections/[id]` | `app/(app)/inspections/[id].tsx` | default | View + edit one | `getById`, `update` | — | new |+| Inspection detail | `/(app)/inspections/[id]` | `app/(app)/inspections/[id]/index.tsx` | default | View + edit one | `getById`, `update` | — | new || New inspection | `/(app)/inspections/new` | `app/(app)/inspections/new.tsx` | modal | Create form, slides up from list | `create` | — | new || Capture photo | `/(app)/inspections/[id]/photo` | `app/(app)/inspections/[id]/photo.tsx` | modal | Take or pick photo | `update` (photo column) | `expo-camera`, `expo-image-picker` | new || Profile | `/(app)/profile` | `app/(app)/profile.tsx` | default | User info + sign out | `useAuth()` only | — | new |@@ -687,7 +695,7 @@ Navigation: <Stack | Tabs | Tabs + Stack | Drawer>|-----------------|-----------------------------|-----------------------------------------|--------------|-----------|-------------------|---------------|| Home | /(app)/home | app/(app)/home.tsx | default | Tab-root | - | - || Inspections | /(app)/inspections | app/(app)/inspections/index.tsx | default | List | InspectionService | - |-| Inspection ID | /(app)/inspections/[id] | app/(app)/inspections/[id].tsx | default | Detail | InspectionService | - |+| Inspection ID | /(app)/inspections/[id] | app/(app)/inspections/[id]/index.tsx | default | Detail | InspectionService | - || New Inspection | /(app)/inspections/new | app/(app)/inspections/new.tsx | modal | Form | InspectionService | camera || Profile | /(app)/profile | app/(app)/profile.tsx | default | Tab-root | - | - |diff --git a/plugins/mobile-apps/scripts/benchmark-dataverse-planning.js b/plugins/mobile-apps/scripts/benchmark-dataverse-planning.jsnew file mode 100644index 000000000..7bd460aaf--- /dev/null+++ b/plugins/mobile-apps/scripts/benchmark-dataverse-planning.js@@ -0,0 +1,520 @@+#!/usr/bin/env node+'use strict';++const { createSnapshot, parseArgs } = require('./create-dataverse-snapshot');+const { renderPlanningEvidence } = require('./render-dataverse-planning-evidence');++function label(value) {+ return { UserLocalizedLabel: { Label: value } };+}++function entity(logicalName, displayName, overrides = {}) {+ return {+ LogicalName: logicalName,+ SchemaName: logicalName,+ EntitySetName: `${logicalName}s`,+ DisplayName: label(displayName),+ DisplayCollectionName: label(`${displayName}s`),+ Description: label(`${displayName} records`),+ PrimaryIdAttribute: `${logicalName}id`,+ PrimaryNameAttribute: `${logicalName}name`,+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ ...overrides,+ };+}++function column(logicalName, type = 'String', overrides = {}) {+ return {+ MetadataId: `${logicalName}-metadata`,+ LogicalName: logicalName,+ SchemaName: logicalName,+ AttributeType: type,+ AttributeTypeName: { Value: `${type}Type` },+ IsCustomAttribute: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ IsValidForCreate: true,+ IsValidForRead: true,+ IsValidForUpdate: true,+ SourceType: 0,+ SourceTypeMask: 0,+ ...overrides,+ };+}++function table(logicalName, columns, overrides = {}) {+ return {+ logicalName,+ columns,+ manyToOneRelationships: [],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ lookupTargets: {},+ computed: {},+ ...overrides,+ };+}++const REQUIREMENT_SETS = [+ {+ id: 'wildlife-rehabilitation',+ name: 'Wildlife rehabilitation',+ prompt: 'Plan a wildlife rehabilitation app for animal intake, medical assessments, care activities, enclosure assignment, and release events.',+ concepts: [+ 'animals',+ 'medical assessments',+ 'care activities',+ 'enclosures',+ 'release events',+ ],+ entities: [+ entity('wr_animal', 'Animal'),+ entity('wr_medicalassessment', 'Medical Assessment'),+ entity('wr_careactivity', 'Care Activity'),+ entity('wr_enclosure', 'Enclosure'),+ entity('wr_releaseevent', 'Release Event'),+ entity('wr_releaseeventv2', 'Release Event'),+ entity('demo_animal', 'Animal'),+ ],+ tables: [+ table('wr_animal', [+ column('wr_name'),+ column('wr_enclosureid', 'Lookup'),+ column('wr_releaseweight', 'Decimal', {+ SourceType: 1,+ SourceTypeMask: 1,+ }),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'wr_Animal_Enclosure',+ ReferencingAttribute: 'wr_enclosureid',+ ReferencedEntity: 'wr_enclosure',+ ReferencedAttribute: 'wr_enclosureid',+ IsManaged: false,+ }],+ alternateKeys: [{+ LogicalName: 'wr_animal_intake_key',+ SchemaName: 'wr_AnimalIntakeKey',+ KeyAttributes: ['wr_name'],+ EntityKeyIndexStatus: 'Active',+ IsManaged: false,+ }],+ lookupTargets: { wr_enclosureid: ['wr_enclosure'] },+ computed: {+ wr_releaseweight: {+ sourceType: 1,+ sourceTypeMask: 1,+ formulaDefinition: 'wr_intakeweight - wr_weightloss',+ },+ },+ }),+ table('wr_medicalassessment', [+ column('wr_name'),+ column('wr_animalid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'wr_MedicalAssessment_Animal',+ ReferencingAttribute: 'wr_animalid',+ ReferencedEntity: 'wr_animal',+ ReferencedAttribute: 'wr_animalid',+ IsManaged: false,+ }],+ lookupTargets: { wr_animalid: ['wr_animal'] },+ }),+ table('wr_careactivity', [+ column('wr_name'),+ column('wr_animalid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'wr_CareActivity_Animal',+ ReferencingAttribute: 'wr_animalid',+ ReferencedEntity: 'wr_animal',+ ReferencedAttribute: 'wr_animalid',+ IsManaged: false,+ }],+ lookupTargets: { wr_animalid: ['wr_animal'] },+ }),+ table('wr_enclosure', [column('wr_name')]),+ table('wr_releaseevent', [+ column('wr_name'),+ column('wr_animalid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'wr_ReleaseEvent_Animal',+ ReferencingAttribute: 'wr_animalid',+ ReferencedEntity: 'wr_animal',+ ReferencedAttribute: 'wr_animalid',+ IsManaged: false,+ }],+ lookupTargets: { wr_animalid: ['wr_animal'] },+ }),+ ],+ expectedDetailed: [+ 'wr_animal',+ 'wr_medicalassessment',+ 'wr_careactivity',+ 'wr_enclosure',+ 'wr_releaseevent',+ ],+ expectedRelationship: {+ table: 'wr_animal',+ lookupColumn: 'wr_enclosureid',+ targetTable: 'wr_enclosure',+ },+ expectedComputed: {+ table: 'wr_animal',+ logicalName: 'wr_releaseweight',+ sourceType: 1,+ sourceTypeMask: 1,+ formulaDefinition: 'wr_intakeweight - wr_weightloss',+ },+ proposedNames: ['wr_animal', 'wr_releasereview'],+ expectedCollision: 'wr_animal',+ expectedMissing: 'wr_releasereview',+ },+ {+ id: 'laboratory-chain-of-custody',+ name: 'Laboratory sample chain-of-custody',+ prompt: 'Plan a laboratory sample chain-of-custody app for samples, batches, custody transfers, test results, and evidence attachments.',+ concepts: [+ 'samples',+ 'batches',+ 'custody transfers',+ 'test results',+ 'evidence attachments',+ ],+ entities: [+ entity('lab_sample', 'Sample'),+ entity('lab_batch', 'Batch'),+ entity('lab_custodytransfer', 'Custody Transfer'),+ entity('lab_testresult', 'Test Result'),+ entity('lab_evidenceattachment', 'Evidence Attachment'),+ entity('lab_v3_sample', 'Sample'),+ entity('archive_custodytransfer', 'Custody Transfer'),+ ],+ tables: [+ table('lab_sample', [+ column('lab_name'),+ column('lab_batchid', 'Lookup'),+ column('lab_elapsedhours', 'Decimal', {+ SourceType: 3,+ SourceTypeMask: 4,+ }),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'lab_Sample_Batch',+ ReferencingAttribute: 'lab_batchid',+ ReferencedEntity: 'lab_batch',+ ReferencedAttribute: 'lab_batchid',+ IsManaged: false,+ }],+ alternateKeys: [{+ LogicalName: 'lab_sample_barcode_key',+ SchemaName: 'lab_SampleBarcodeKey',+ KeyAttributes: ['lab_name'],+ EntityKeyIndexStatus: 'Active',+ IsManaged: false,+ }],+ lookupTargets: { lab_batchid: ['lab_batch'] },+ computed: {+ lab_elapsedhours: {+ sourceType: 3,+ sourceTypeMask: 4,+ formulaDefinition: 'DiffInHours(lab_collectedon, Now())',+ },+ },+ }),+ table('lab_batch', [column('lab_name')]),+ table('lab_custodytransfer', [+ column('lab_name'),+ column('lab_sampleid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'lab_CustodyTransfer_Sample',+ ReferencingAttribute: 'lab_sampleid',+ ReferencedEntity: 'lab_sample',+ ReferencedAttribute: 'lab_sampleid',+ IsManaged: false,+ }],+ lookupTargets: { lab_sampleid: ['lab_sample'] },+ }),+ table('lab_testresult', [+ column('lab_name'),+ column('lab_sampleid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'lab_TestResult_Sample',+ ReferencingAttribute: 'lab_sampleid',+ ReferencedEntity: 'lab_sample',+ ReferencedAttribute: 'lab_sampleid',+ IsManaged: false,+ }],+ lookupTargets: { lab_sampleid: ['lab_sample'] },+ }),+ table('lab_evidenceattachment', [+ column('lab_name'),+ column('lab_sampleid', 'Lookup'),+ ], {+ manyToOneRelationships: [{+ SchemaName: 'lab_EvidenceAttachment_Sample',+ ReferencingAttribute: 'lab_sampleid',+ ReferencedEntity: 'lab_sample',+ ReferencedAttribute: 'lab_sampleid',+ IsManaged: false,+ }],+ lookupTargets: { lab_sampleid: ['lab_sample'] },+ }),+ ],+ expectedDetailed: [+ 'lab_sample',+ 'lab_batch',+ 'lab_custodytransfer',+ 'lab_testresult',+ 'lab_evidenceattachment',+ ],+ expectedRelationship: {+ table: 'lab_sample',+ lookupColumn: 'lab_batchid',+ targetTable: 'lab_batch',+ },+ expectedComputed: {+ table: 'lab_sample',+ logicalName: 'lab_elapsedhours',+ sourceType: 3,+ sourceTypeMask: 4,+ formulaDefinition: 'DiffInHours(lab_collectedon, Now())',+ },+ proposedNames: ['lab_sample', 'lab_storagecondition'],+ expectedCollision: 'lab_sample',+ expectedMissing: 'lab_storagecondition',+ },+];++function tableNameFromPath(apiPath) {+ const match = apiPath.match(/EntityDefinitions\(LogicalName='([^']+)'\)/);+ return match?.[1] || null;+}++function createFixtureRequest(requirementSet, calls) {+ const tables = new Map(requirementSet.tables.map((item) => [item.logicalName, item]));+ return async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ if (apiPath.includes('IsCustomizable/Value eq true')) {+ return { status: 200, data: { value: requirementSet.entities } };+ }+ return {+ status: 200,+ data: {+ value: requirementSet.entities.filter(+ (item) => apiPath.includes(`LogicalName eq '${item.LogicalName}'`),+ ),+ },+ };+ }++ const logicalName = tableNameFromPath(apiPath);+ const fixture = tables.get(logicalName);+ if (!fixture) return { status: 404, error: `Unknown fixture table ${logicalName}` };+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: fixture.columns } };+ }+ if (apiPath.includes('/ManyToOneRelationships?')) {+ return { status: 200, data: { value: fixture.manyToOneRelationships } };+ }+ if (apiPath.includes('/OneToManyRelationships?')) {+ return { status: 200, data: { value: fixture.oneToManyRelationships } };+ }+ if (apiPath.includes('/ManyToManyRelationships?')) {+ return { status: 200, data: { value: fixture.manyToManyRelationships } };+ }+ if (apiPath.includes('/Keys?')) {+ return { status: 200, data: { value: fixture.alternateKeys } };+ }+ if (apiPath.includes('LookupAttributeMetadata')) {+ return {+ status: 200,+ data: {+ value: Object.entries(fixture.lookupTargets).map(([name, targets]) => ({+ LogicalName: name,+ Targets: targets,+ })),+ },+ };+ }+ if (/AttributeMetadata/.test(apiPath) && apiPath.includes('$expand=OptionSet')) {+ return { status: 200, data: { value: [] } };+ }++ const metadataId = apiPath.match(/\/Attributes\(([^)]+)\)\//)?.[1];+ if (metadataId) {+ const attribute = fixture.columns.find((item) => item.MetadataId === metadataId);+ const computed = fixture.computed[attribute?.LogicalName];+ if (!computed) return { status: 404, error: 'Computed metadata fixture missing' };+ return {+ status: 200,+ data: {+ LogicalName: attribute.LogicalName,+ SourceType: computed.sourceType,+ SourceTypeMask: computed.sourceTypeMask,+ FormulaDefinition: computed.formulaDefinition,+ },+ };+ }+ return { status: 200, data: { value: [] } };+ };+}++function normalizeEvidence(markdown) {+ return markdown+ .replace(/\d+(?:\.\d+)? ms/g, '<duration>')+ .replace(/\s+/g, ' ')+ .trim();+}++async function evaluateRequirementSet(requirementSet) {+ const startedAt = process.hrtime.bigint();+ const calls = [];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://fixture.crm.dynamics.com',+ tenantId: 'fixture-tenant',+ concepts: requirementSet.concepts,+ proposedTableNames: requirementSet.proposedNames,+ request: createFixtureRequest(requirementSet, calls),+ nowIso: () => '2026-08-18T05:00:00.000Z',+ });+ const evidence = renderPlanningEvidence(snapshot);+ const normalizedEvidenceText = normalizeEvidence(evidence);+ const selectedNames = snapshot.tables.map((item) => item.logicalName).sort();+ const expectedNames = [...requirementSet.expectedDetailed].sort();+ const relationshipTable = snapshot.tables.find(+ (item) => item.logicalName === requirementSet.expectedRelationship.table,+ );+ const computedTable = snapshot.tables.find(+ (item) => item.logicalName === requirementSet.expectedComputed.table,+ );+ const computedColumn = computedTable?.columns.find(+ (item) => item.logicalName === requirementSet.expectedComputed.logicalName,+ );+ const checks = {+ candidateSelection: JSON.stringify(selectedNames) === JSON.stringify(expectedNames),+ relationshipExtraction: relationshipTable?.manyToOneRelationships.some((relationship) => (+ relationship.lookupColumn === requirementSet.expectedRelationship.lookupColumn+ && relationship.targetTable === requirementSet.expectedRelationship.targetTable+ )) || false,+ computedExtraction: computedColumn?.computed?.metadataStatus === 'available'+ && computedColumn.computed.sourceType === requirementSet.expectedComputed.sourceType+ && computedColumn.computed.sourceTypeMask === requirementSet.expectedComputed.sourceTypeMask+ && computedColumn.computed.formulaDefinition+ === requirementSet.expectedComputed.formulaDefinition,+ proposedNameChecks: snapshot.proposedNameChecks.collisions.some(+ (item) => item.logicalName === requirementSet.expectedCollision,+ ) && snapshot.proposedNameChecks.missing.includes(requirementSet.expectedMissing),+ evidenceOutput: expectedNames.every((name) => normalizedEvidenceText.includes(`\`${name}\``))+ && normalizedEvidenceText.includes(`\`${requirementSet.expectedCollision}\``)+ && normalizedEvidenceText.includes(`\`${requirementSet.expectedMissing}\``)+ && normalizedEvidenceText.includes('Detailed candidate facts')+ && normalizedEvidenceText.includes('Proposed logical-name checks'),+ };+ const passedChecks = Object.values(checks).filter(Boolean).length;+ const totalChecks = Object.keys(checks).length;+ const elapsedLocalProcessingMs = Number(process.hrtime.bigint() - startedAt) / 1e6;++ return {+ id: requirementSet.id,+ name: requirementSet.name,+ prompt: requirementSet.prompt,+ requiredConceptCount: requirementSet.concepts.length,+ selectedCandidateCount: selectedNames.length,+ selectedCandidates: selectedNames,+ detailedCandidateBreakdown: {+ required: snapshot.detailLoadSummary.requiredCandidates || 0,+ advisory: snapshot.detailLoadSummary.advisoryCandidates || 0,+ exactCoveredConcepts: snapshot.detailLoadSummary.exactCoveredConcepts || 0,+ advisoryLimit: snapshot.detailLoadSummary.advisoryLimit || 40,+ },+ metadataRequests: {+ snapshotForegroundRequests: calls.length,+ snapshotFirstAgentRequests: 0,+ },+ outputCompleteness: {+ checks,+ passedChecks,+ totalChecks,+ percent: Math.round((passedChecks / totalChecks) * 100),+ },+ evidenceCharacters: evidence.length,+ elapsedLocalProcessingMs: Number(elapsedLocalProcessingMs.toFixed(3)),+ };+}++async function runBenchmark(requirementSets = REQUIREMENT_SETS) {+ return {+ version: 2,+ methodology: 'Fixture-backed execution through createSnapshot and renderPlanningEvidence',+ limitation: 'Matched agent A/B runs are still required for model decision and timing claims.',+ scenarios: await Promise.all(requirementSets.map(evaluateRequirementSet)),+ };+}++function renderBenchmarkMarkdown(result) {+ const lines = [+ '# Dataverse snapshot-first planning benchmark',+ '',+ `> ${result.limitation}`,+ '',+ '| Requirements set | Selected candidates | Required / advisory | Exact-covered concepts | Foreground fixture requests | Snapshot-first agent requests | Completeness | Evidence output | Local processing |',+ '|---|---:|---:|---:|---:|---:|---:|---:|---:|',+ ];+ for (const scenario of result.scenarios) {+ lines.push(+ `| ${scenario.name} | ${scenario.selectedCandidateCount} | `+ + `${scenario.detailedCandidateBreakdown.required} / ${scenario.detailedCandidateBreakdown.advisory} | `+ + `${scenario.detailedCandidateBreakdown.exactCoveredConcepts} | `+ + `${scenario.metadataRequests.snapshotForegroundRequests} | `+ + `${scenario.metadataRequests.snapshotFirstAgentRequests} | `+ + `${scenario.outputCompleteness.passedChecks}/${scenario.outputCompleteness.totalChecks} `+ + `(${scenario.outputCompleteness.percent}%) | `+ + `${scenario.evidenceCharacters} chars | `+ + `${scenario.elapsedLocalProcessingMs.toFixed(3)} ms |`,+ );+ }+ lines.push(+ '',+ 'Each scenario executes the real snapshot candidate selection, detail loading, relationship and computed-column extraction, proposed-name checks, and deterministic evidence renderer against injected Dataverse responses.',+ '',+ 'The request count is the actual fixture executor call count. It does not measure network latency or agent behavior, and it does not substitute for matched agent A/B decision and timing runs.',+ '',+ );+ return lines.join('\n');+}++async function main() {+ const args = parseArgs(process.argv);+ const result = await runBenchmark();+ if (args.json) {+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ } else {+ process.stdout.write(renderBenchmarkMarkdown(result));+ }+}++if (require.main === module) {+ main().catch((error) => {+ process.stderr.write(`${error.message}\n`);+ process.exit(1);+ });+}++module.exports = {+ REQUIREMENT_SETS,+ createFixtureRequest,+ evaluateRequirementSet,+ normalizeEvidence,+ renderBenchmarkMarkdown,+ runBenchmark,+};diff --git a/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js b/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.jsnew file mode 100644index 000000000..ff79f30fb--- /dev/null+++ b/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js@@ -0,0 +1,3829 @@+#!/usr/bin/env node+'use strict';++const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');+const {+ compareDerivedColumn,+ normalizeOptions,+ validateOptions,+} = require('./lib/derived-metadata');+const {+ canonicalAttributeType,+ validateSnapshot,+} = require('./create-dataverse-snapshot');+const { operationFingerprint } = require('./dataverse-request');++const CONTRACT_SCHEMA_VERSION = 1;+const APPROVAL_RECEIPT_SCHEMA_VERSION = 1;+const MANIFEST_SCHEMA_VERSION = 2;+const PUBLISH_CHECKPOINT_SCHEMA_VERSION = 2;+const DEFAULT_MAX_RECONCILIATION_AGE_MS = 10 * 60 * 1000;+const PHASE_ORDER = [+ 'tableCreates',+ 'extensions',+ 'relationships',+ 'alternateKeys',+ 'publish',+];+const DECISIONS = new Set([+ 'reuse',+ 'extend',+ 'create',+ 'adapt',+ 'defer',+ 'unverified',+]);+const CONTRACT_DECISIONS = new Set([+ 'reuse',+ 'extend',+ 'create',+ 'adapt',+ 'defer',+ 'unverified',+]);+const DERIVED_COLUMN_TYPES = new Set([+ 'boolean',+ 'choice',+ 'multiselectchoice',+ 'lookup',+ 'computed',+]);+const NULL_SOURCE_TYPE_IS_ORDINARY_TYPES = new Set([+ 'lookup',+ 'memo',+ 'multiline',+]);++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ const token = argv[index];+ if (!token.startsWith('--')) continue;+ const value = argv[index + 1];+ if (value !== undefined && !String(value).startsWith('--')) {+ args[token.slice(2)] = value;+ index += 1;+ } else {+ args[token.slice(2)] = true;+ }+ }+ return args;+}++function normalizeUrl(value) {+ return String(value || '').trim().replace(/\/+$/, '').toLowerCase();+}++function normalizeName(value) {+ return String(value || '').trim().toLowerCase();+}++function sha256(content) {+ return crypto.createHash('sha256').update(content).digest('hex');+}++function stableClone(value) {+ if (Array.isArray(value)) return value.map(stableClone);+ if (!value || typeof value !== 'object') return value;+ return Object.keys(value)+ .sort((left, right) => left.localeCompare(right))+ .reduce((result, key) => {+ result[key] = stableClone(value[key]);+ return result;+ }, {});+}++function stableJson(value) {+ return `${JSON.stringify(stableClone(value), null, 2)}\n`;+}++function atomicWriteJson(file, value, fileSystem = fs) {+ fileSystem.mkdirSync(path.dirname(file), { recursive: true });+ const temporary = `${file}.tmp-${process.pid}-${Date.now()}`;+ try {+ fileSystem.writeFileSync(temporary, stableJson(value), 'utf8');+ fileSystem.renameSync(temporary, file);+ } finally {+ if (fileSystem.existsSync(temporary)) fileSystem.rmSync(temporary, { force: true });+ }+}++function label(value) {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.Label',+ LocalizedLabels: [{+ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel',+ Label: value,+ LanguageCode: 1033,+ }],+ };+}++function requiredLevel(value) {+ return { Value: value || 'None' };+}++function contractItemId(kind, ...parts) {+ return [kind, ...parts.map(normalizeName)].join(':');+}++function uniqueByNormalizedName(items, nameOf, labelText, errors) {+ const seen = new Set();+ for (const [index, item] of items.entries()) {+ const name = String(nameOf(item) || '').trim();+ if (!name) {+ errors.push(`${labelText}[${index}] requires a logical or schema name`);+ continue;+ }+ const key = name.toLowerCase();+ if (seen.has(key)) errors.push(`${labelText} contains duplicate ${name}`);+ seen.add(key);+ }+}++function validateLogicalName(value, labelText, errors) {+ if (typeof value !== 'string' || !/^[a-z][a-z0-9_]*$/i.test(value)) {+ errors.push(`${labelText} must be a Dataverse logical/schema name`);+ }+}++function logicalNameFromSchemaName(value) {+ return normalizeName(value);+}++function validateSchemaLogicalIdentity(logicalName, schemaName, labelText, errors) {+ validateLogicalName(logicalName, `${labelText}.logicalName`, errors);+ validateLogicalName(schemaName, `${labelText}.schemaName`, errors);+ if (+ typeof logicalName === 'string'+ && typeof schemaName === 'string'+ && logicalNameFromSchemaName(schemaName) !== normalizeName(logicalName)+ ) {+ errors.push(+ `${labelText}.schemaName must resolve to logicalName ${normalizeName(logicalName)} `+ + 'under Dataverse casing rules',+ );+ }+}++function hasOwn(value, key) {+ return Object.prototype.hasOwnProperty.call(value || {}, key);+}++function normalizeColumnType(value) {+ return String(value || '').replace(/[\s_-]/g, '').toLowerCase();+}++function dataverseType(column) {+ const type = normalizeColumnType(column.type);+ const mapping = {+ string: 'String',+ text: 'String',+ memo: 'Memo',+ multiline: 'Memo',+ integer: 'Integer',+ wholenumber: 'Integer',+ bigint: 'BigInt',+ decimal: 'Decimal',+ double: 'Double',+ float: 'Double',+ money: 'Money',+ currency: 'Money',+ datetime: 'DateTime',+ date: 'DateTime',+ boolean: 'Boolean',+ choice: 'Picklist',+ picklist: 'Picklist',+ multiselectchoice: 'Virtual',+ lookup: 'Lookup',+ image: 'Image',+ file: 'File',+ computed: String(column.attributeType || ''),+ calculated: String(column.attributeType || ''),+ rollup: String(column.attributeType || ''),+ formula: String(column.attributeType || ''),+ };+ return mapping[type] || String(column.attributeType || column.type || '');+}++function typeName(column) {+ const type = normalizeColumnType(column.type);+ if (type === 'multiselectchoice') return 'MultiSelectPicklistType';+ if (type === 'file') return 'FileType';+ if (type === 'image') return 'ImageType';+ const liveType = dataverseType(column);+ return liveType ? `${liveType}Type` : '';+}++function isComputedColumn(column) {+ return ['computed', 'calculated', 'rollup', 'formula'].includes(+ normalizeColumnType(column.type),+ ) || Number(column.sourceType || 0) !== 0;+}++function validateContract(contract) {+ const errors = [];+ if (!contract || typeof contract !== 'object' || Array.isArray(contract)) {+ return { valid: false, errors: ['contract must be an object'] };+ }+ if (contract.schemaVersion !== CONTRACT_SCHEMA_VERSION) {+ errors.push(`contract.schemaVersion must equal ${CONTRACT_SCHEMA_VERSION}`);+ }+ if (!Array.isArray(contract.tables)) errors.push('contract.tables must be an array');+ if (typeof contract.publisherPrefix !== 'string' || !contract.publisherPrefix.trim()) {+ errors.push('contract.publisherPrefix is required');+ }+ if (contract.publisherPrefix && !/^[a-z][a-z0-9]*$/i.test(contract.publisherPrefix)) {+ errors.push('contract.publisherPrefix must not contain an underscore');+ }+ if (contract.approvedPlanSha256 !== undefined+ && !/^[a-f0-9]{64}$/i.test(String(contract.approvedPlanSha256))) {+ errors.push('contract.approvedPlanSha256 must be a SHA-256 hex value when supplied');+ }+ if (contract.approvedContractSha256 !== undefined+ && !/^[a-f0-9]{64}$/i.test(String(contract.approvedContractSha256))) {+ errors.push('contract.approvedContractSha256 must be a SHA-256 hex value when supplied');+ }+ if (contract.approvalReceiptSha256 !== undefined+ && !/^[a-f0-9]{64}$/i.test(String(contract.approvalReceiptSha256))) {+ errors.push('contract.approvalReceiptSha256 must be a SHA-256 hex value when supplied');+ }+ if (errors.length > 0 || !Array.isArray(contract.tables)) {+ return { valid: false, errors };+ }++ uniqueByNormalizedName(+ contract.tables,+ (table) => table.logicalName,+ 'contract.tables',+ errors,+ );++ for (const [tableIndex, table] of contract.tables.entries()) {+ const prefix = `contract.tables[${tableIndex}]`;+ validateSchemaLogicalIdentity(+ table.logicalName,+ table.schemaName || table.logicalName,+ prefix,+ errors,+ );+ if (!CONTRACT_DECISIONS.has(normalizeName(table.plannedDecision))) {+ errors.push(`${prefix}.plannedDecision must use the reconciliation taxonomy`);+ }+ if (!Number.isInteger(table.dependencyTier) || table.dependencyTier < 0) {+ errors.push(`${prefix}.dependencyTier must be a non-negative integer`);+ }+ if (typeof table.serviceRequired !== 'boolean') {+ errors.push(`${prefix}.serviceRequired must be boolean`);+ }+ if (!Array.isArray(table.columns)) errors.push(`${prefix}.columns must be an array`);+ if (!Array.isArray(table.relationships)) {+ errors.push(`${prefix}.relationships must be an array`);+ }+ if (!Array.isArray(table.alternateKeys)) {+ errors.push(`${prefix}.alternateKeys must be an array`);+ }+ if (normalizeName(table.plannedDecision) === 'adapt') {+ validateSchemaLogicalIdentity(+ table.adaptedLogicalName,+ table.adaptedSchemaName,+ `${prefix}.adapted`,+ errors,+ );+ }++ const columns = Array.isArray(table.columns) ? table.columns : [];+ uniqueByNormalizedName(columns, (column) => column.logicalName, `${prefix}.columns`, errors);+ for (const [columnIndex, column] of columns.entries()) {+ const columnPrefix = `${prefix}.columns[${columnIndex}]`;+ validateSchemaLogicalIdentity(+ column.logicalName,+ column.schemaName || column.logicalName,+ columnPrefix,+ errors,+ );+ if (!CONTRACT_DECISIONS.has(normalizeName(column.plannedDecision))) {+ errors.push(`${columnPrefix}.plannedDecision must use the reconciliation taxonomy`);+ }+ if (!normalizeColumnType(column.type)) errors.push(`${columnPrefix}.type is required`);+ if (normalizeName(column.plannedDecision) === 'adapt') {+ validateSchemaLogicalIdentity(+ column.adaptedLogicalName,+ column.adaptedSchemaName,+ `${columnPrefix}.adapted`,+ errors,+ );+ }+ if (normalizeColumnType(column.type) === 'lookup' && !column.lookupTarget) {+ errors.push(`${columnPrefix}.lookupTarget is required for a lookup`);+ }+ if (+ ['choice', 'multiselectchoice', 'boolean'].includes(normalizeColumnType(column.type))+ && (!Array.isArray(column.options) || column.options.length === 0)+ ) {+ errors.push(`${columnPrefix}.options must be a non-empty array`);+ } else if (['choice', 'multiselectchoice', 'boolean'].includes(+ normalizeColumnType(column.type),+ )) {+ errors.push(...validateOptions(+ column.options,+ columnPrefix,+ normalizeColumnType(column.type) === 'boolean',+ ));+ }+ if (normalizeColumnType(column.type) === 'bigint') {+ for (const field of ['minValue', 'maxValue']) {+ if (hasOwn(column, field) && !Number.isSafeInteger(column[field])) {+ errors.push(`${columnPrefix}.${field} must be a safely representable integer`);+ }+ }+ }+ }++ const primaryNames = columns.filter((column) => column.primaryName);+ if (['create', 'adapt'].includes(normalizeName(table.plannedDecision))+ && primaryNames.length !== 1) {+ errors.push(`${prefix} create/adapt tables require exactly one primaryName column`);+ } else if (+ ['create', 'adapt'].includes(normalizeName(table.plannedDecision))+ && !['string', 'text'].includes(normalizeColumnType(primaryNames[0]?.type))+ ) {+ errors.push(`${prefix} primaryName column must be string/text`);+ } else if (+ ['create', 'adapt'].includes(normalizeName(table.plannedDecision))+ && normalizeName(primaryNames[0]?.plannedDecision) === 'defer'+ ) {+ errors.push(`${prefix} primaryName column cannot be deferred`);+ }+ if (normalizeName(table.plannedDecision) === 'reuse') {+ for (const column of columns) {+ if (['create', 'adapt'].includes(normalizeName(column.plannedDecision))) {+ errors.push(+ `${prefix} reuse table cannot authorize ${column.plannedDecision} `+ + `column ${column.logicalName}`,+ );+ }+ }+ }++ const relationships = Array.isArray(table.relationships) ? table.relationships : [];+ uniqueByNormalizedName(+ relationships,+ (relationship) => relationship.schemaName,+ `${prefix}.relationships`,+ errors,+ );+ for (const [relationshipIndex, relationship] of relationships.entries()) {+ const relationshipPrefix = `${prefix}.relationships[${relationshipIndex}]`;+ validateLogicalName(+ relationship.schemaName,+ `${relationshipPrefix}.schemaName`,+ errors,+ );+ if (!['many-to-one', 'many-to-many'].includes(relationship.kind)) {+ errors.push(`${relationshipPrefix}.kind must be many-to-one or many-to-many`);+ }+ if (!CONTRACT_DECISIONS.has(normalizeName(relationship.plannedDecision))) {+ errors.push(`${relationshipPrefix}.plannedDecision must use the reconciliation taxonomy`);+ }+ if (relationship.serviceRequired !== undefined+ && typeof relationship.serviceRequired !== 'boolean') {+ errors.push(`${relationshipPrefix}.serviceRequired must be boolean when supplied`);+ }+ if (normalizeName(relationship.plannedDecision) === 'adapt') {+ validateLogicalName(+ relationship.adaptedSchemaName,+ `${relationshipPrefix}.adaptedSchemaName`,+ errors,+ );+ }+ if (relationship.kind === 'many-to-one') {+ validateLogicalName(+ relationship.parentTable,+ `${relationshipPrefix}.parentTable`,+ errors,+ );+ validateLogicalName(+ relationship.childTable || table.logicalName,+ `${relationshipPrefix}.childTable`,+ errors,+ );+ validateSchemaLogicalIdentity(+ relationship.lookup?.logicalName,+ relationship.lookup?.schemaName || relationship.lookup?.logicalName,+ `${relationshipPrefix}.lookup`,+ errors,+ );+ if (normalizeName(relationship.plannedDecision) === 'adapt') {+ validateSchemaLogicalIdentity(+ relationship.lookup?.adaptedLogicalName,+ relationship.lookup?.adaptedSchemaName,+ `${relationshipPrefix}.lookup.adapted`,+ errors,+ );+ }+ } else {+ validateLogicalName(+ relationship.entity1,+ `${relationshipPrefix}.entity1`,+ errors,+ );+ validateLogicalName(+ relationship.entity2,+ `${relationshipPrefix}.entity2`,+ errors,+ );+ validateLogicalName(+ relationship.intersectTable,+ `${relationshipPrefix}.intersectTable`,+ errors,+ );+ if (normalizeName(relationship.plannedDecision) === 'adapt') {+ validateLogicalName(+ relationship.adaptedIntersectTable,+ `${relationshipPrefix}.adaptedIntersectTable`,+ errors,+ );+ }+ }+ }++ const alternateKeys = Array.isArray(table.alternateKeys) ? table.alternateKeys : [];+ uniqueByNormalizedName(+ alternateKeys,+ (key) => key.schemaName,+ `${prefix}.alternateKeys`,+ errors,+ );+ for (const [keyIndex, key] of alternateKeys.entries()) {+ const keyPrefix = `${prefix}.alternateKeys[${keyIndex}]`;+ validateLogicalName(key.schemaName, `${keyPrefix}.schemaName`, errors);+ if (!CONTRACT_DECISIONS.has(normalizeName(key.plannedDecision))) {+ errors.push(`${keyPrefix}.plannedDecision must use the reconciliation taxonomy`);+ }+ if (normalizeName(key.plannedDecision) === 'adapt') {+ validateLogicalName(+ key.adaptedSchemaName,+ `${keyPrefix}.adaptedSchemaName`,+ errors,+ );+ }+ if (!Array.isArray(key.columns) || key.columns.length === 0) {+ errors.push(`${keyPrefix}.columns must be a non-empty array`);+ }+ }+ }++ const tableByName = new Map(+ contract.tables.map((table) => [normalizeName(table.logicalName), table]),+ );+ const relationshipBackedLookups = new Set();+ const effectiveTableNames = new Set();+ for (const table of contract.tables) {+ const effectiveName = normalizeName(+ normalizeName(table.plannedDecision) === 'adapt'+ ? table.adaptedLogicalName+ : table.logicalName,+ );+ if (effectiveTableNames.has(effectiveName)) {+ errors.push(`contract tables resolve to duplicate effective name ${effectiveName}`);+ }+ effectiveTableNames.add(effectiveName);+ const effectiveColumns = new Set();+ for (const column of table.columns || []) {+ const effectiveColumn = normalizeName(+ normalizeName(column.plannedDecision) === 'adapt'+ ? column.adaptedLogicalName+ : column.logicalName,+ );+ if (effectiveColumns.has(effectiveColumn)) {+ errors.push(+ `${table.logicalName} columns resolve to duplicate effective name ${effectiveColumn}`,+ );+ }+ effectiveColumns.add(effectiveColumn);+ }+ }+ for (const table of contract.tables) {+ for (const relationship of table.relationships || []) {+ const endpointNames = relationship.kind === 'many-to-one'+ ? [relationship.parentTable, relationship.childTable || table.logicalName]+ : [relationship.entity1, relationship.entity2];+ for (const endpoint of endpointNames) {+ if (!tableByName.has(normalizeName(endpoint))) {+ errors.push(+ `${relationship.schemaName} endpoint ${endpoint} must be represented as a contract table`,+ );+ }+ }+ if (relationship.kind === 'many-to-one') {+ const child = tableByName.get(normalizeName(relationship.childTable || table.logicalName));+ const lookup = child?.columns?.find(+ (column) => normalizeName(column.logicalName)+ === normalizeName(relationship.lookup?.logicalName),+ );+ if (!lookup || normalizeColumnType(lookup.type) !== 'lookup') {+ errors.push(+ `${relationship.schemaName} lookup must match a lookup column on its child table`,+ );+ } else if (+ normalizeName(lookup.lookupTarget) !== normalizeName(relationship.parentTable)+ ) {+ errors.push(`${relationship.schemaName} lookup target does not match parentTable`);+ } else if (+ normalizeName(lookup.plannedDecision)+ !== normalizeName(relationship.plannedDecision)+ ) {+ errors.push(+ `${relationship.schemaName} decision must match its lookup column decision`,+ );+ } else if (+ relationship.lookup.requiredLevel !== undefined+ && String(relationship.lookup.requiredLevel || 'None')+ !== String(lookup.requiredLevel || 'None')+ ) {+ errors.push(+ `${relationship.schemaName} lookup requiredLevel must match `+ + `${child.logicalName}.${lookup.logicalName}`,+ );+ } else if (+ normalizeName(relationship.plannedDecision) === 'adapt'+ && (+ normalizeName(relationship.lookup.adaptedLogicalName)+ !== normalizeName(lookup.adaptedLogicalName)+ || logicalNameFromSchemaName(relationship.lookup.adaptedSchemaName)+ !== logicalNameFromSchemaName(lookup.adaptedSchemaName)+ )+ ) {+ errors.push(+ `${relationship.schemaName} adapted lookup identity must match `+ + `${child.logicalName}.${lookup.logicalName}`,+ );+ } else {+ relationshipBackedLookups.add(+ `${normalizeName(relationship.childTable || table.logicalName)}:`+ + `${normalizeName(relationship.lookup.logicalName)}`,+ );+ }+ }+ }+ const columnsByName = new Map(+ (table.columns || []).map((column) => [normalizeName(column.logicalName), column]),+ );+ for (const key of table.alternateKeys || []) {+ for (const columnName of key.columns || []) {+ const column = columnsByName.get(normalizeName(columnName));+ if (!column) {+ errors.push(`${key.schemaName} references missing column ${columnName}`);+ } else if (+ ['file', 'image', 'memo', 'multiline', 'multiselectchoice', 'lookup']+ .includes(normalizeColumnType(column.type))+ || isComputedColumn(column)+ ) {+ errors.push(`${key.schemaName} uses unsupported alternate-key column ${columnName}`);+ } else if (+ !['defer', 'unverified'].includes(normalizeName(key.plannedDecision))+ && ['defer', 'unverified'].includes(normalizeName(column.plannedDecision))+ ) {+ errors.push(+ `${key.schemaName} cannot depend on ${columnName} with decision `+ + `${column.plannedDecision}`,+ );+ }+ }+ }+ }+ for (const table of contract.tables) {+ for (const column of table.columns || []) {+ if (normalizeColumnType(column.type) !== 'lookup') continue;+ const lookupId = `${normalizeName(table.logicalName)}:${normalizeName(column.logicalName)}`;+ if (!relationshipBackedLookups.has(lookupId)) {+ errors.push(+ `${table.logicalName}.${column.logicalName} lookup has no matching many-to-one relationship`,+ );+ }+ }+ }++ return { valid: errors.length === 0, errors };+}++function normalizedContract(contract) {+ const normalized = {+ schemaVersion: CONTRACT_SCHEMA_VERSION,+ publisherPrefix: String(contract.publisherPrefix).trim().toLowerCase(),+ ...(contract.approvedPlanSha256+ ? { approvedPlanSha256: String(contract.approvedPlanSha256).toLowerCase() }+ : {}),+ ...(contract.approvedContractSha256+ ? { approvedContractSha256: String(contract.approvedContractSha256).toLowerCase() }+ : {}),+ ...(contract.approvalReceiptSha256+ ? { approvalReceiptSha256: String(contract.approvalReceiptSha256).toLowerCase() }+ : {}),+ tables: contract.tables.map((table) => ({+ ...table,+ logicalName: normalizeName(table.logicalName),+ schemaName: String(table.schemaName || table.logicalName).trim(),+ plannedDecision: normalizeName(table.plannedDecision),+ adaptedLogicalName: table.adaptedLogicalName+ ? normalizeName(table.adaptedLogicalName)+ : undefined,+ adaptedSchemaName: table.adaptedSchemaName+ ? String(table.adaptedSchemaName).trim()+ : undefined,+ columns: table.columns.map((column) => ({+ ...column,+ logicalName: normalizeName(column.logicalName),+ schemaName: String(column.schemaName || column.logicalName).trim(),+ plannedDecision: normalizeName(column.plannedDecision),+ adaptedLogicalName: column.adaptedLogicalName+ ? normalizeName(column.adaptedLogicalName)+ : undefined,+ adaptedSchemaName: column.adaptedSchemaName+ ? String(column.adaptedSchemaName).trim()+ : undefined,+ options: column.options ? normalizeOptions(column.options) : undefined,+ })).sort((left, right) => (+ Number(right.primaryName) - Number(left.primaryName)+ || left.logicalName.localeCompare(right.logicalName)+ )),+ relationships: table.relationships.map((relationship) => ({+ ...relationship,+ schemaName: String(relationship.schemaName).trim(),+ plannedDecision: normalizeName(relationship.plannedDecision),+ parentTable: relationship.parentTable+ ? normalizeName(relationship.parentTable)+ : undefined,+ childTable: relationship.childTable+ ? normalizeName(relationship.childTable)+ : undefined,+ entity1: relationship.entity1 ? normalizeName(relationship.entity1) : undefined,+ entity2: relationship.entity2 ? normalizeName(relationship.entity2) : undefined,+ intersectTable: relationship.intersectTable+ ? normalizeName(relationship.intersectTable)+ : undefined,+ adaptedIntersectTable: relationship.adaptedIntersectTable+ ? normalizeName(relationship.adaptedIntersectTable)+ : undefined,+ adaptedSchemaName: relationship.adaptedSchemaName+ ? String(relationship.adaptedSchemaName).trim()+ : undefined,+ lookup: relationship.lookup+ ? {+ ...relationship.lookup,+ logicalName: normalizeName(relationship.lookup.logicalName),+ schemaName: String(+ relationship.lookup.schemaName || relationship.lookup.logicalName,+ ).trim(),+ adaptedLogicalName: relationship.lookup.adaptedLogicalName+ ? normalizeName(relationship.lookup.adaptedLogicalName)+ : undefined,+ adaptedSchemaName: relationship.lookup.adaptedSchemaName+ ? String(relationship.lookup.adaptedSchemaName).trim()+ : undefined,+ }+ : undefined,+ })).sort((left, right) => left.schemaName.localeCompare(right.schemaName)),+ alternateKeys: table.alternateKeys.map((key) => ({+ ...key,+ schemaName: String(key.schemaName).trim(),+ plannedDecision: normalizeName(key.plannedDecision),+ columns: [...key.columns].map(normalizeName).sort((left, right) => left.localeCompare(right)),+ })).sort((left, right) => left.schemaName.localeCompare(right.schemaName)),+ })).sort((left, right) => (+ left.dependencyTier - right.dependencyTier+ || left.logicalName.localeCompare(right.logicalName)+ )),+ };+ const normalizedTableByName = new Map(+ normalized.tables.map((table) => [table.logicalName, table]),+ );+ for (const owner of normalized.tables) {+ for (const relationship of owner.relationships) {+ if (relationship.kind !== 'many-to-one') continue;+ const child = normalizedTableByName.get(+ normalizeName(relationship.childTable || owner.logicalName),+ );+ const lookupColumn = child?.columns.find(+ (column) => column.logicalName === normalizeName(relationship.lookup.logicalName),+ );+ if (lookupColumn) {+ relationship.lookup.requiredLevel = lookupColumn.requiredLevel || 'None';+ }+ }+ }+ return JSON.parse(JSON.stringify(normalized));+}++function contractApprovalContent(contract) {+ const content = normalizedContract(contract);+ delete content.approvedPlanSha256;+ delete content.approvedContractSha256;+ delete content.approvalReceiptSha256;+ return content;+}++function declaredServiceRequiredTableNames(contract) {+ const normalized = contractApprovalContent(contract);+ const names = [];+ for (const table of normalized.tables) {+ if (table.serviceRequired && table.plannedDecision !== 'defer') {+ names.push(+ table.plannedDecision === 'adapt'+ ? table.adaptedLogicalName+ : table.logicalName,+ );+ }+ for (const relationship of table.relationships) {+ if (relationship.kind !== 'many-to-many'+ || !relationship.serviceRequired+ || relationship.plannedDecision === 'defer') continue;+ names.push(+ relationship.plannedDecision === 'adapt'+ ? relationship.adaptedIntersectTable+ : relationship.intersectTable,+ );+ }+ }+ return [...new Set(names.map(normalizeName))]+ .sort((left, right) => left.localeCompare(right));+}++function normalizeServiceDependencies(serviceDependencies) {+ const errors = [];+ if (!serviceDependencies+ || typeof serviceDependencies !== 'object'+ || Array.isArray(serviceDependencies)) {+ return { valid: false, errors: ['service dependencies must be an object'] };+ }+ if (serviceDependencies.schemaVersion !== APPROVAL_RECEIPT_SCHEMA_VERSION) {+ errors.push(+ `service dependencies schemaVersion must equal ${APPROVAL_RECEIPT_SCHEMA_VERSION}`,+ );+ }+ if (!Array.isArray(serviceDependencies.serviceRequiredTables)) {+ errors.push('service dependencies serviceRequiredTables must be an array');+ return { valid: false, errors };+ }+ const tables = [];+ const seen = new Set();+ for (const [index, item] of serviceDependencies.serviceRequiredTables.entries()) {+ const prefix = `serviceRequiredTables[${index}]`;+ if (!item || typeof item !== 'object' || Array.isArray(item)) {+ errors.push(`${prefix} must be an object`);+ continue;+ }+ const logicalName = normalizeName(item.logicalName);+ validateLogicalName(logicalName, `${prefix}.logicalName`, errors);+ if (seen.has(logicalName)) errors.push(`${prefix}.logicalName must be unique`);+ seen.add(logicalName);+ if (!Array.isArray(item.consumers)+ || item.consumers.length === 0+ || item.consumers.some(+ (consumer) => typeof consumer !== 'string' || !consumer.trim(),+ )) {+ errors.push(`${prefix}.consumers must be a non-empty string array`);+ }+ tables.push({+ logicalName,+ consumers: [...new Set((item.consumers || [])+ .map((consumer) => String(consumer).trim())+ .filter(Boolean))]+ .sort((left, right) => left.localeCompare(right)),+ });+ }+ tables.sort((left, right) => left.logicalName.localeCompare(right.logicalName));+ return { valid: errors.length === 0, errors, tables };+}++function validateApprovalReceipt(approvalReceipt, {+ contract,+ planBytes,+}) {+ const errors = [];+ if (!approvalReceipt+ || typeof approvalReceipt !== 'object'+ || Array.isArray(approvalReceipt)) {+ return { valid: false, errors: ['mobile plan approval receipt must be an object'] };+ }+ if (approvalReceipt.schemaVersion !== APPROVAL_RECEIPT_SCHEMA_VERSION) {+ errors.push(+ `mobile plan approval receipt schemaVersion must equal ${APPROVAL_RECEIPT_SCHEMA_VERSION}`,+ );+ }+ if (approvalReceipt.workflow !== 'create-mobile-app') {+ errors.push('mobile plan approval receipt workflow must equal create-mobile-app');+ }+ const requiredApprovals = [+ 'dataModel',+ 'nativeCapabilities',+ 'connectors',+ 'screenPlan',+ ];+ for (const approval of requiredApprovals) {+ const record = approvalReceipt.approvals?.[approval];+ if (record?.status !== 'approved') {+ errors.push(`mobile plan approval receipt ${approval} status must be approved`);+ }+ if (!record?.approvedAt || !Number.isFinite(Date.parse(record.approvedAt))) {+ errors.push(`mobile plan approval receipt ${approval} approvedAt is invalid`);+ }+ }+ const withoutIntegrity = { ...approvalReceipt };+ delete withoutIntegrity.integritySha256;+ if (approvalReceipt.integritySha256 !== sha256(stableJson(withoutIntegrity))) {+ errors.push('mobile plan approval receipt integrity hash does not match');+ }+ if (!planBytes?.length) {+ errors.push('native-app-plan.md is required');+ } else if (approvalReceipt.approvedPlanSha256 !== sha256(planBytes)) {+ errors.push('mobile plan approval receipt plan hash does not match native-app-plan.md');+ }+ const contractValidation = validateContract(contract);+ if (!contractValidation.valid) {+ errors.push(...contractValidation.errors.map((error) => `contract: ${error}`));+ return { valid: false, errors };+ }+ const approvedContractValidation = validateContract(approvalReceipt.approvedContract);+ if (!approvedContractValidation.valid) {+ errors.push(...approvedContractValidation.errors.map(+ (error) => `approved contract: ${error}`,+ ));+ }+ const contractContent = contractApprovalContent(contract);+ if (approvalReceipt.approvedContractSha256+ !== sha256(stableJson(approvalReceipt.approvedContract))) {+ errors.push('mobile plan approval receipt contract hash does not match its content');+ }+ if (stableJson(approvalReceipt.approvedContract) !== stableJson(contractContent)) {+ errors.push('structured contract content does not match the approved contract');+ }+ if (approvalReceipt.approvedContractSha256 !== sha256(stableJson(contractContent))) {+ errors.push('structured contract hash does not match the approved contract hash');+ }+ if (approvalReceipt.approvals?.dataModel?.approvedContractSha256+ !== approvalReceipt.approvedContractSha256) {+ errors.push(+ 'data-model approval record does not match the approved contract hash',+ );+ }+ const dependencyValidation = normalizeServiceDependencies({+ schemaVersion: approvalReceipt.schemaVersion,+ serviceRequiredTables: approvalReceipt.serviceRequiredTables,+ });+ if (!dependencyValidation.valid) {+ errors.push(...dependencyValidation.errors.map(+ (error) => `mobile plan approval receipt: ${error}`,+ ));+ } else {+ const declaredServices = declaredServiceRequiredTableNames(contractContent);+ const approvedServices = dependencyValidation.tables.map((item) => item.logicalName);+ if (stableJson(declaredServices) !== stableJson(approvedServices)) {+ errors.push(+ 'approved service dependencies do not exactly match contract '+ + 'serviceRequired declarations',+ );+ }+ }+ return { valid: errors.length === 0, errors };+}++function bindContractToPlan(contract, planBytes, approvalReceipt) {+ if (!planBytes?.length) throw new Error('native-app-plan.md is required');+ const validation = validateApprovalReceipt(approvalReceipt, {+ contract,+ planBytes,+ });+ if (!validation.valid) {+ throw new Error(`Invalid mobile plan approval receipt: ${validation.errors.join('; ')}`);+ }+ return normalizedContract({+ ...contract,+ approvedPlanSha256: sha256(planBytes),+ approvedContractSha256: approvalReceipt.approvedContractSha256,+ approvalReceiptSha256: approvalReceipt.integritySha256,+ });+}++function reconciliationScope(contract) {+ const validation = validateContract(contract);+ if (!validation.valid) {+ throw new Error(`Invalid schema contract: ${validation.errors.join('; ')}`);+ }+ const normalized = normalizedContract(contract);+ const intersectNames = normalized.tables.flatMap((table) => (+ table.relationships+ .filter((relationship) => relationship.kind === 'many-to-many')+ .map((relationship) => normalizeName(+ relationship.adaptedIntersectTable || relationship.intersectTable,+ ))+ ));+ const proposedIntersectNames = normalized.tables.flatMap((table) => (+ table.relationships+ .filter((relationship) => (+ relationship.kind === 'many-to-many'+ && ['create', 'adapt'].includes(relationship.plannedDecision)+ ))+ .map((relationship) => normalizeName(+ relationship.adaptedIntersectTable || relationship.intersectTable,+ ))+ ));+ return {+ schemaVersion: 1,+ exactTables: [...new Set([+ ...normalized.tables.map((table) => normalizeName(+ table.plannedDecision === 'adapt'+ ? table.adaptedLogicalName+ : table.logicalName,+ )),+ ...intersectNames,+ ])].sort((left, right) => left.localeCompare(right)),+ proposedTables: [...new Set([+ ...normalized.tables+ .filter((table) => ['create', 'adapt'].includes(table.plannedDecision))+ .map((table) => normalizeName(+ table.plannedDecision === 'adapt'+ ? table.adaptedLogicalName+ : table.logicalName,+ )),+ ...proposedIntersectNames,+ ])].sort((left, right) => left.localeCompare(right)),+ };+}++function snapshotIndexes(snapshot) {+ const inventoryByName = new Map(+ (snapshot.inventory || []).map((table) => [normalizeName(table.logicalName), table]),+ );+ const tableByName = new Map(+ (snapshot.tables || []).map((table) => [normalizeName(table.logicalName), table]),+ );+ const proposedByName = new Map(+ (snapshot.proposedNameChecks?.checked || [])+ .map((item) => [normalizeName(item.logicalName), item]),+ );+ const exactRequested = new Set(+ (snapshot.exactNameResolution?.requestedTables || []).map(normalizeName),+ );+ const exactLoaded = new Set(+ (snapshot.exactNameResolution?.loadedTables || []).map(normalizeName),+ );+ const exactUnavailable = new Set(+ (snapshot.exactNameResolution?.unavailableTables || []).map(normalizeName),+ );+ return {+ inventoryByName,+ tableByName,+ proposedByName,+ exactRequested,+ exactLoaded,+ exactUnavailable,+ };+}++function absenceProven(logicalName, indexes) {+ const key = normalizeName(logicalName);+ return indexes.proposedByName.get(key)?.status === 'missing'+ || (indexes.exactRequested.has(key) && indexes.exactUnavailable.has(key));+}++function presence(logicalName, indexes) {+ const key = normalizeName(logicalName);+ return {+ inventory: indexes.inventoryByName.get(key) || null,+ detail: indexes.tableByName.get(key) || null,+ exactLoaded: indexes.exactLoaded.has(key),+ proposed: indexes.proposedByName.get(key) || null,+ };+}++function isCustomName(logicalName, publisherPrefix) {+ return normalizeName(logicalName).startsWith(`${normalizeName(publisherPrefix)}_`);+}++function metadataValue(value) {+ if (value && typeof value === 'object' && hasOwn(value, 'Value')) return value.Value;+ return value;+}++function compareRequiredEvidence(reasons, liveColumn, field, expected, {+ labelText = field,+ compare = (actual, planned) => actual === planned,+} = {}) {+ const actual = metadataValue(liveColumn[field]);+ if (actual === null || actual === undefined || actual === '') {+ reasons.push(`${labelText} evidence is missing`);+ } else if (!compare(actual, expected)) {+ reasons.push(`${labelText} mismatch: expected ${expected}, got ${actual}`);+ }+}++function expectedColumnConstraints(column) {+ const type = normalizeColumnType(column.type);+ const constraints = [];+ if (type === 'string' || type === 'text') {+ constraints.push(+ ['maxLength', Number(column.maxLength ?? 200), 'MaxLength',+ (actual, expected) => Number(actual) >= expected],+ ['formatName', column.format || 'Text', 'FormatName'],+ );+ } else if (type === 'memo' || type === 'multiline') {+ constraints.push(+ ['maxLength', Number(column.maxLength ?? 10000), 'MaxLength',+ (actual, expected) => Number(actual) >= expected],+ ['format', column.format || 'TextArea', 'Format'],+ );+ } else if (type === 'integer' || type === 'wholenumber') {+ constraints.push(+ ['minValue', Number(column.minValue ?? -2147483648), 'MinValue',+ (actual, expected) => Number(actual) <= expected],+ ['maxValue', Number(column.maxValue ?? 2147483647), 'MaxValue',+ (actual, expected) => Number(actual) >= expected],+ ['format', column.format || 'None', 'Format'],+ );+ } else if (type === 'bigint') {+ if (hasOwn(column, 'minValue')) {+ constraints.push(+ ['minValue', column.minValue, 'MinValue',+ (actual, expected) => Number(actual) <= expected],+ );+ }+ if (hasOwn(column, 'maxValue')) {+ constraints.push(+ ['maxValue', column.maxValue, 'MaxValue',+ (actual, expected) => Number(actual) >= expected],+ );+ }+ } else if (['decimal', 'double', 'float'].includes(type)) {+ constraints.push(+ ['minValue', Number(column.minValue ?? -100000000000), 'MinValue',+ (actual, expected) => Number(actual) <= expected],+ ['maxValue', Number(column.maxValue ?? 100000000000), 'MaxValue',+ (actual, expected) => Number(actual) >= expected],+ ['precision', Number(column.precision ?? 2), 'Precision'],+ );+ } else if (type === 'money' || type === 'currency') {+ constraints.push(+ ['minValue', Number(column.minValue ?? -922337203685477), 'MinValue',+ (actual, expected) => Number(actual) <= expected],+ ['maxValue', Number(column.maxValue ?? 922337203685477), 'MaxValue',+ (actual, expected) => Number(actual) >= expected],+ ['precision', Number(column.precision ?? 2), 'Precision'],+ ['precisionSource', Number(column.precisionSource ?? 2), 'PrecisionSource'],+ );+ } else if (type === 'datetime' || type === 'date') {+ constraints.push(+ ['format', type === 'date' ? 'DateOnly' : (column.format || 'DateAndTime'), 'Format'],+ ['dateTimeBehavior', column.behavior || 'UserLocal', 'DateTimeBehavior'],+ );+ } else if (type === 'boolean') {+ constraints.push(['defaultValue', Boolean(column.defaultValue), 'DefaultValue']);+ } else if (type === 'image') {+ constraints.push(+ ['maxHeight', Number(column.maxHeight ?? 1440), 'MaxHeight',+ (actual, expected) => Number(actual) >= expected],+ ['maxWidth', Number(column.maxWidth ?? 1440), 'MaxWidth',+ (actual, expected) => Number(actual) >= expected],+ );+ } else if (type === 'file') {+ constraints.push(+ ['maxSizeInKB', Number(column.maxSizeInKB ?? 32768), 'MaxSizeInKB',+ (actual, expected) => Number(actual) >= expected],+ );+ }+ return constraints;+}++function baseColumnCompatibility(column, liveColumn) {+ if (!liveColumn) return { compatible: false, reasons: ['column is absent'] };+ const reasons = [];+ const expectedType = dataverseType(column);+ const liveType = canonicalAttributeType(liveColumn.type, liveColumn.typeName);+ if (liveType !== expectedType) {+ reasons.push(`type mismatch: expected ${expectedType}, got ${liveType || '<missing>'}`);+ }+ const expectedTypeName = typeName(column);+ if (expectedTypeName) {+ if (!liveColumn.typeName) {+ reasons.push('type-name evidence is missing');+ } else if (liveColumn.typeName !== expectedTypeName) {+ reasons.push(+ `type-name mismatch: expected ${expectedTypeName}, got ${liveColumn.typeName}`,+ );+ }+ }+ const normalizedColumnType = normalizeColumnType(column.type);+ if (!hasOwn(liveColumn, 'sourceType')) {+ reasons.push('SourceType evidence is missing');+ } else if (liveColumn.sourceType === null+ && !NULL_SOURCE_TYPE_IS_ORDINARY_TYPES.has(normalizedColumnType)) {+ reasons.push('SourceType evidence is missing');+ } else if (!DERIVED_COLUMN_TYPES.has(normalizedColumnType)+ && Number(liveColumn.sourceType) !== 0) {+ reasons.push(`ordinary column has SourceType ${liveColumn.sourceType}`);+ }+ compareRequiredEvidence(+ reasons,+ liveColumn,+ 'requiredLevel',+ column.requiredLevel || 'None',+ { labelText: 'RequiredLevel' },+ );+ if (hasOwn(column, 'primaryName')) {+ compareRequiredEvidence(+ reasons,+ liveColumn,+ 'primaryName',+ Boolean(column.primaryName),+ {+ labelText: 'IsPrimaryName',+ compare: (actual, expected) => Boolean(actual) === expected,+ },+ );+ }+ for (const [field, expected, labelText, compare] of expectedColumnConstraints(column)) {+ compareRequiredEvidence(reasons, liveColumn, field, expected, {+ labelText,+ compare,+ });+ }+ return { compatible: reasons.length === 0, reasons };+}++function derivedExpected(tableName, column) {+ const kind = normalizeColumnType(column.type);+ if (kind === 'lookup') {+ return {+ table: tableName,+ logicalName: column.logicalName,+ kind: 'lookup',+ type: 'Lookup',+ sourceType: 0,+ lookupTarget: normalizeName(column.lookupTarget),+ };+ }+ if (kind === 'choice' || kind === 'multiselectchoice') {+ return {+ table: tableName,+ logicalName: column.logicalName,+ kind: 'choice',+ type: dataverseType(column),+ sourceType: 0,+ options: column.options,+ };+ }+ if (kind === 'boolean') {+ return {+ table: tableName,+ logicalName: column.logicalName,+ kind: 'boolean',+ type: 'Boolean',+ sourceType: 0,+ options: column.options,+ };+ }+ if (isComputedColumn(column)) {+ return {+ table: tableName,+ logicalName: column.logicalName,+ kind: 'computed',+ type: dataverseType(column),+ sourceType: Number(column.sourceType),+ sourceTypeMask: Number(column.sourceTypeMask),+ formulaDefinition: column.formulaDefinition,+ };+ }+ return null;+}++function columnCompatibility(tableName, column, liveColumn) {+ const base = baseColumnCompatibility(column, liveColumn);+ if (!base.compatible) return base;+ const expected = derivedExpected(tableName, column);+ if (!expected) return base;+ const compared = compareDerivedColumn(expected, {+ type: liveColumn.type,+ sourceType: liveColumn.sourceType,+ sourceTypeMask: liveColumn.sourceTypeMask,+ lookupTargets: liveColumn.lookupTargets,+ options: liveColumn.choices,+ formulaDefinition: liveColumn.formulaDefinition || liveColumn.formula,+ });+ return compared;+}++function columnPayload(column, effectiveLogicalName = column.logicalName) {+ const type = normalizeColumnType(column.type);+ const schemaName = column.adaptedSchemaName+ || (effectiveLogicalName === column.logicalName+ ? column.schemaName+ : effectiveLogicalName);+ const common = {+ SchemaName: schemaName,+ DisplayName: label(column.displayName || schemaName),+ RequiredLevel: requiredLevel(column.requiredLevel),+ };+ if (column.primaryName) common.IsPrimaryName = true;++ if (type === 'string' || type === 'text') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata',+ ...common,+ MaxLength: Number(column.maxLength || 200),+ FormatName: { Value: column.format || 'Text' },+ };+ }+ if (type === 'memo' || type === 'multiline') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.MemoAttributeMetadata',+ ...common,+ MaxLength: Number(column.maxLength || 10000),+ Format: column.format || 'TextArea',+ };+ }+ if (type === 'integer' || type === 'wholenumber') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.IntegerAttributeMetadata',+ ...common,+ MinValue: Number(column.minValue ?? -2147483648),+ MaxValue: Number(column.maxValue ?? 2147483647),+ Format: column.format || 'None',+ };+ }+ if (type === 'bigint') {+ const payload = {+ '@odata.type': 'Microsoft.Dynamics.CRM.BigIntAttributeMetadata',+ ...common,+ };+ if (hasOwn(column, 'minValue')) payload.MinValue = column.minValue;+ if (hasOwn(column, 'maxValue')) payload.MaxValue = column.maxValue;+ return payload;+ }+ if (type === 'decimal' || type === 'double' || type === 'float') {+ const metadataType = type === 'decimal' ? 'Decimal' : 'Double';+ return {+ '@odata.type': `Microsoft.Dynamics.CRM.${metadataType}AttributeMetadata`,+ ...common,+ MinValue: Number(column.minValue ?? -100000000000),+ MaxValue: Number(column.maxValue ?? 100000000000),+ Precision: Number(column.precision ?? 2),+ };+ }+ if (type === 'money' || type === 'currency') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.MoneyAttributeMetadata',+ ...common,+ MinValue: Number(column.minValue ?? -922337203685477),+ MaxValue: Number(column.maxValue ?? 922337203685477),+ Precision: Number(column.precision ?? 2),+ PrecisionSource: Number(column.precisionSource ?? 2),+ };+ }+ if (type === 'datetime' || type === 'date') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.DateTimeAttributeMetadata',+ ...common,+ Format: type === 'date' ? 'DateOnly' : (column.format || 'DateAndTime'),+ DateTimeBehavior: { Value: column.behavior || 'UserLocal' },+ };+ }+ if (type === 'boolean') {+ const options = normalizeOptions(column.options);+ const falseOption = options.find((option) => option.value === 0);+ const trueOption = options.find((option) => option.value === 1);+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.BooleanAttributeMetadata',+ ...common,+ DefaultValue: Boolean(column.defaultValue),+ OptionSet: {+ '@odata.type': 'Microsoft.Dynamics.CRM.BooleanOptionSetMetadata',+ TrueOption: { Value: 1, Label: label(trueOption.label) },+ FalseOption: { Value: 0, Label: label(falseOption.label) },+ },+ };+ }+ if (type === 'choice' || type === 'multiselectchoice') {+ const metadataType = type === 'choice'+ ? 'PicklistAttributeMetadata'+ : 'MultiSelectPicklistAttributeMetadata';+ return {+ '@odata.type': `Microsoft.Dynamics.CRM.${metadataType}`,+ ...common,+ OptionSet: {+ '@odata.type': 'Microsoft.Dynamics.CRM.OptionSetMetadata',+ IsGlobal: false,+ OptionSetType: 'Picklist',+ Options: normalizeOptions(column.options).map((option) => ({+ Value: option.value,+ Label: label(option.label),+ })),+ },+ };+ }+ if (type === 'image') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.ImageAttributeMetadata',+ ...common,+ MaxHeight: Number(column.maxHeight || 1440),+ MaxWidth: Number(column.maxWidth || 1440),+ };+ }+ if (type === 'file') {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.FileAttributeMetadata',+ ...common,+ MaxSizeInKB: Number(column.maxSizeInKB || 32768),+ };+ }+ throw new Error(`Unsupported ordinary column type: ${column.type}`);+}++function tablePayload(table, effectiveName, ordinaryColumns) {+ const primaryName = ordinaryColumns.find((column) => column.primaryName);+ if (!primaryName) throw new Error(`${table.logicalName} has no primary-name column`);+ const attributes = ordinaryColumns.map((column) => (+ columnPayload(column, column.effectiveLogicalName)+ ));+ const schemaNames = attributes.map((attribute) => normalizeName(attribute.SchemaName));+ if (new Set(schemaNames).size !== schemaNames.length) {+ throw new Error(`${table.logicalName} has duplicate inline column SchemaName values`);+ }+ if (attributes.filter((attribute) => attribute.IsPrimaryName).length !== 1) {+ throw new Error(`${table.logicalName} must have exactly one inline primary-name column`);+ }+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.EntityMetadata',+ SchemaName: table.adaptedSchemaName+ || (effectiveName === table.logicalName ? table.schemaName : effectiveName),+ DisplayName: label(table.displayName || effectiveName),+ DisplayCollectionName: label(+ table.displayCollectionName || `${table.displayName || effectiveName}s`,+ ),+ OwnershipType: table.ownershipType || 'UserOwned',+ HasActivities: Boolean(table.hasActivities),+ HasNotes: Boolean(table.hasNotes),+ IsAvailableOffline: table.isAvailableOffline !== false,+ ChangeTrackingEnabled: table.changeTrackingEnabled !== false,+ PrimaryNameAttribute: normalizeName(primaryName.effectiveLogicalName),+ Attributes: attributes,+ };+}++function plannedCascadeConfiguration(relationship) {+ return {+ Assign: relationship.cascadeConfiguration?.Assign || 'NoCascade',+ Delete: relationship.cascadeConfiguration?.Delete+ || relationship.deleteBehavior+ || 'RemoveLink',+ Merge: relationship.cascadeConfiguration?.Merge || 'NoCascade',+ Reparent: relationship.cascadeConfiguration?.Reparent || 'NoCascade',+ Share: relationship.cascadeConfiguration?.Share || 'NoCascade',+ Unshare: relationship.cascadeConfiguration?.Unshare || 'NoCascade',+ RollupView: relationship.cascadeConfiguration?.RollupView || 'NoCascade',+ };+}++function cascadeConfigurationMatches(actual, expected) {+ return actual+ && Object.entries(expected).every(([key, value]) => (+ hasOwn(actual, key) && actual[key] === value+ ));+}++function relationshipPayload(relationship, aliases) {+ if (relationship.kind === 'many-to-one') {+ const childTable = aliases.tables.get(normalizeName(+ relationship.childTable,+ )) || normalizeName(relationship.childTable);+ const parentTable = aliases.tables.get(normalizeName(+ relationship.parentTable,+ )) || normalizeName(relationship.parentTable);+ const lookupName = relationship.lookup.adaptedLogicalName || aliases.columns.get(+ `${childTable}:${normalizeName(relationship.lookup.logicalName)}`,+ ) || normalizeName(relationship.lookup.logicalName);+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata',+ SchemaName: relationship.adaptedSchemaName || relationship.schemaName,+ ReferencedEntity: parentTable,+ ReferencingEntity: childTable,+ Lookup: {+ '@odata.type': 'Microsoft.Dynamics.CRM.LookupAttributeMetadata',+ SchemaName: relationship.lookup.adaptedSchemaName+ || relationship.lookup.schemaName+ || lookupName,+ DisplayName: label(relationship.lookup.displayName || lookupName),+ RequiredLevel: requiredLevel(relationship.lookup.requiredLevel),+ },+ AssociatedMenuConfiguration: {+ Behavior: 'UseCollectionName',+ Group: 'Details',+ Order: 10000,+ },+ CascadeConfiguration: plannedCascadeConfiguration(relationship),+ };+ }++ const entity1 = aliases.tables.get(normalizeName(relationship.entity1))+ || normalizeName(relationship.entity1);+ const entity2 = aliases.tables.get(normalizeName(relationship.entity2))+ || normalizeName(relationship.entity2);+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata',+ SchemaName: relationship.adaptedSchemaName || relationship.schemaName,+ Entity1LogicalName: entity1,+ Entity2LogicalName: entity2,+ IntersectEntityName: relationship.adaptedIntersectTable || relationship.intersectTable,+ Entity1AssociatedMenuConfiguration: {+ Behavior: 'UseLabel',+ Group: 'Details',+ Label: label(relationship.entity2DisplayCollectionName || entity2),+ Order: 10000,+ },+ Entity2AssociatedMenuConfiguration: {+ Behavior: 'UseLabel',+ Group: 'Details',+ Label: label(relationship.entity1DisplayCollectionName || entity1),+ Order: 10000,+ },+ };+}++function keyPayload(key, aliases, effectiveTable) {+ return {+ '@odata.type': 'Microsoft.Dynamics.CRM.EntityKeyMetadata',+ SchemaName: key.adaptedSchemaName || key.schemaName,+ DisplayName: label(key.displayName || `${key.schemaName} Key`),+ KeyAttributes: key.columns.map((column) => (+ aliases.columns.get(`${effectiveTable}:${normalizeName(column)}`) || normalizeName(column)+ )),+ };+}++function makeDecision({+ itemId,+ itemType,+ requestedName,+ effectiveName,+ decision,+ operation,+ reason,+ table,+}) {+ if (!DECISIONS.has(decision)) throw new Error(`Invalid decision ${decision}`);+ return {+ itemId,+ itemType,+ table: table || null,+ requestedName,+ effectiveName,+ decision,+ operation,+ reason,+ };+}++function compatibleTableColumns(table, liveTable) {+ const liveByName = new Map(+ (liveTable?.columns || []).map((column) => [normalizeName(column.logicalName), column]),+ );+ return table.columns.map((column) => {+ const targetName = normalizeName(column.adaptedLogicalName || column.logicalName);+ const liveColumn = liveByName.get(targetName);+ return {+ column,+ targetName,+ liveColumn,+ comparison: liveColumn+ ? columnCompatibility(liveTable.logicalName, {+ ...column,+ logicalName: targetName,+ }, liveColumn)+ : null,+ };+ });+}++function tableCreateCompatibility(table, effectiveName, liveTable) {+ const reasons = [];+ const primaryName = table.columns.find((column) => column.primaryName);+ const expected = {+ schemaName: normalizeName(+ table.adaptedSchemaName+ || (effectiveName === table.logicalName ? table.schemaName : effectiveName),+ ),+ displayName: table.displayName || effectiveName,+ displayCollectionName: table.displayCollectionName+ || `${table.displayName || effectiveName}s`,+ ownershipType: table.ownershipType || 'UserOwned',+ hasActivities: Boolean(table.hasActivities),+ hasNotes: Boolean(table.hasNotes),+ isAvailableOffline: table.isAvailableOffline !== false,+ changeTrackingEnabled: table.changeTrackingEnabled !== false,+ primaryNameAttribute: normalizeName(+ primaryName?.adaptedLogicalName || primaryName?.logicalName,+ ),+ };+ const comparisons = [+ ['schemaName', expected.schemaName, (actual, planned) => normalizeName(actual) === planned],+ ['displayName', expected.displayName],+ ['displayCollectionName', expected.displayCollectionName],+ ['ownershipType', expected.ownershipType,+ (actual, planned) => normalizeName(actual) === normalizeName(planned)],+ ['hasActivities', expected.hasActivities],+ ['hasNotes', expected.hasNotes],+ ['isAvailableOffline', expected.isAvailableOffline],+ ['changeTrackingEnabled', expected.changeTrackingEnabled],+ ['primaryNameAttribute', expected.primaryNameAttribute,+ (actual, planned) => normalizeName(actual) === planned],+ ];+ for (const [field, planned, compare = (actual, value) => actual === value] of comparisons) {+ if (!hasOwn(liveTable, field)+ || liveTable[field] === null+ || liveTable[field] === undefined) {+ reasons.push(`${field} evidence is missing`);+ } else if (!compare(liveTable[field], planned)) {+ reasons.push(`${field} mismatch: expected ${planned}, got ${liveTable[field]}`);+ }+ }+ return { compatible: reasons.length === 0, reasons };+}++function relationshipExists(relationship, snapshotTable, aliases) {+ if (!snapshotTable) return { verified: false, exists: false, compatible: false };+ const expectedSchema = normalizeName(+ relationship.adaptedSchemaName || relationship.schemaName,+ );+ if (relationship.kind === 'many-to-one') {+ const expectedTarget = aliases.tables.get(normalizeName(relationship.parentTable))+ || normalizeName(relationship.parentTable);+ const expectedLookup = normalizeName(+ relationship.lookup.adaptedLogicalName || relationship.lookup.logicalName,+ );+ const candidates = snapshotTable.manyToOneRelationships || [];+ const existing = candidates.find((item) => (+ normalizeName(item.schemaName) === expectedSchema+ || normalizeName(item.lookupColumn) === expectedLookup+ ));+ if (!existing) return { verified: true, exists: false, compatible: false };+ return {+ verified: true,+ exists: true,+ compatible: normalizeName(existing.schemaName) === expectedSchema+ && normalizeName(existing.targetTable) === expectedTarget+ && normalizeName(existing.lookupColumn) === expectedLookup+ && cascadeConfigurationMatches(+ existing.cascadeConfiguration,+ plannedCascadeConfiguration(relationship),+ ),+ existing,+ };+ }+ const expectedIntersect = normalizeName(+ relationship.adaptedIntersectTable || relationship.intersectTable,+ );+ const existing = (snapshotTable.manyToManyRelationships || []).find((item) => (+ normalizeName(item.schemaName) === expectedSchema+ || normalizeName(item.intersectTable) === expectedIntersect+ ));+ if (!existing) return { verified: true, exists: false, compatible: false };+ const expected = new Set([+ aliases.tables.get(normalizeName(relationship.entity1))+ || normalizeName(relationship.entity1),+ aliases.tables.get(normalizeName(relationship.entity2))+ || normalizeName(relationship.entity2),+ ]);+ const actual = new Set([normalizeName(existing.entity1), normalizeName(existing.entity2)]);+ return {+ verified: true,+ exists: true,+ compatible: normalizeName(existing.schemaName) === expectedSchema+ && normalizeName(existing.intersectTable) === expectedIntersect+ && expected.size === actual.size+ && [...expected].every((name) => actual.has(name)),+ existing,+ };+}++function keyExists(key, snapshotTable, aliases, effectiveTable) {+ if (!snapshotTable) return { verified: false, exists: false, compatible: false };+ const expectedColumns = key.columns.map((column) => (+ aliases.columns.get(`${effectiveTable}:${normalizeName(column)}`) || normalizeName(column)+ )).sort();+ const expectedSchema = normalizeName(key.adaptedSchemaName || key.schemaName);+ const existing = (snapshotTable.alternateKeys || []).find((item) => (+ normalizeName(item.schemaName) === expectedSchema+ || JSON.stringify((item.columns || []).map(normalizeName).sort()) === JSON.stringify(expectedColumns)+ ));+ if (!existing) return { verified: true, exists: false, compatible: false };+ const actualColumns = (existing.columns || []).map(normalizeName).sort();+ return {+ verified: true,+ exists: true,+ compatible: normalizeName(existing.schemaName) === expectedSchema+ && JSON.stringify(actualColumns) === JSON.stringify(expectedColumns)+ && normalizeName(existing.status) !== 'failed',+ existing,+ };+}++function operation(index, id, phase, apiPath, body, solution) {+ return {+ index,+ id,+ phase,+ method: 'POST',+ apiPath,+ body,+ solution,+ };+}++function xmlEscape(value) {+ return String(value)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function publishCheckpointCore({+ context,+ planSha256,+ structuredSchemaSha256,+ tables,+ createdAt,+ rollForwards = [],+}) {+ const checkpoint = {+ schemaVersion: PUBLISH_CHECKPOINT_SCHEMA_VERSION,+ createdAt,+ binding: {+ environmentId: context.environmentId,+ environmentUrl: String(context.environmentUrl).replace(/\/+$/, ''),+ tenantId: context.tenantId || null,+ publisherPrefix: normalizeName(context.publisherPrefix),+ solutionUniqueName: context.solutionUniqueName,+ planSha256,+ structuredSchemaSha256,+ },+ tables: [...new Set(tables.map(normalizeName))]+ .sort((left, right) => left.localeCompare(right)),+ };+ if (rollForwards.length > 0) checkpoint.rollForwards = stableClone(rollForwards);+ return checkpoint;+}++function createPublishCheckpoint(options) {+ const checkpoint = publishCheckpointCore(options);+ checkpoint.integritySha256 = sha256(stableJson(checkpoint));+ return checkpoint;+}++function validatePublishCheckpoint(checkpoint, {+ context,+ planSha256,+ structuredSchemaSha256,+ allowedTables,+}) {+ const errors = [];+ if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) {+ return { valid: false, errors: ['publish checkpoint must be an object'] };+ }+ if (checkpoint.schemaVersion !== PUBLISH_CHECKPOINT_SCHEMA_VERSION) {+ errors.push(+ `publish checkpoint schemaVersion must equal ${PUBLISH_CHECKPOINT_SCHEMA_VERSION}`,+ );+ }+ const withoutIntegrity = { ...checkpoint };+ delete withoutIntegrity.integritySha256;+ if (checkpoint.integritySha256 !== sha256(stableJson(withoutIntegrity))) {+ errors.push('publish checkpoint integrity hash does not match');+ }+ const binding = checkpoint.binding || {};+ if (binding.environmentId !== context.environmentId) {+ errors.push('publish checkpoint environmentId mismatch');+ }+ if (normalizeUrl(binding.environmentUrl) !== normalizeUrl(context.environmentUrl)) {+ errors.push('publish checkpoint environmentUrl mismatch');+ }+ if (context.tenantId && normalizeName(binding.tenantId) !== normalizeName(context.tenantId)) {+ errors.push('publish checkpoint tenantId mismatch');+ }+ if (normalizeName(binding.publisherPrefix) !== normalizeName(context.publisherPrefix)) {+ errors.push('publish checkpoint publisherPrefix mismatch');+ }+ if (binding.solutionUniqueName !== context.solutionUniqueName) {+ errors.push('publish checkpoint solutionUniqueName mismatch');+ }+ if (binding.planSha256 !== planSha256) errors.push('publish checkpoint plan hash mismatch');+ if (binding.structuredSchemaSha256 !== structuredSchemaSha256) {+ errors.push('publish checkpoint structured schema hash mismatch');+ }+ if (!Array.isArray(checkpoint.tables) || checkpoint.tables.length === 0) {+ errors.push('publish checkpoint tables must be a non-empty array');+ } else {+ const normalizedTables = checkpoint.tables.map(normalizeName);+ if (new Set(normalizedTables).size !== normalizedTables.length) {+ errors.push('publish checkpoint tables must be unique');+ }+ for (const table of normalizedTables) {+ if (!/^[a-z][a-z0-9_]*$/i.test(table)) {+ errors.push(`publish checkpoint table ${table} is malformed`);+ } else if (allowedTables && !allowedTables.has(table)) {+ errors.push(`publish checkpoint table ${table} is outside the bound contract`);+ }+ }+ }+ if (typeof checkpoint.createdAt !== 'string'+ || Number.isNaN(Date.parse(checkpoint.createdAt))) {+ errors.push('publish checkpoint createdAt must be an ISO timestamp');+ }+ if (checkpoint.rollForwards !== undefined) {+ if (!Array.isArray(checkpoint.rollForwards)) {+ errors.push('publish checkpoint rollForwards must be an array');+ } else {+ for (const [index, rollForward] of checkpoint.rollForwards.entries()) {+ const prefix = `publish checkpoint rollForwards[${index}]`;+ if (!/^[a-f0-9]{64}$/i.test(String(rollForward?.previousIntegritySha256 || ''))) {+ errors.push(`${prefix}.previousIntegritySha256 is malformed`);+ }+ const previousCheckpoint = rollForward?.previousCheckpoint;+ if (!previousCheckpoint || typeof previousCheckpoint !== 'object') {+ errors.push(`${prefix}.previousCheckpoint must preserve the prior artifact`);+ } else {+ const previousWithoutIntegrity = { ...previousCheckpoint };+ delete previousWithoutIntegrity.integritySha256;+ if (previousCheckpoint.integritySha256+ !== sha256(stableJson(previousWithoutIntegrity))+ || previousCheckpoint.integritySha256+ !== rollForward.previousIntegritySha256) {+ errors.push(`${prefix}.previousCheckpoint integrity does not match`);+ }+ if (stableJson(previousCheckpoint.binding)+ !== stableJson(rollForward.previousBinding)+ || stableJson(previousCheckpoint.tables)+ !== stableJson(rollForward.previousTables)) {+ errors.push(`${prefix}.previousCheckpoint evidence does not match`);+ }+ }+ if (!Array.isArray(rollForward?.previousTables)+ || rollForward.previousTables.length === 0) {+ errors.push(`${prefix}.previousTables must preserve prior table evidence`);+ }+ if (!Array.isArray(rollForward?.tableMappings)) {+ errors.push(`${prefix}.tableMappings must be an array`);+ }+ if (!/^[a-f0-9]{64}$/i.test(String(+ rollForward?.collisionOperationFingerprint || '',+ ))) {+ errors.push(`${prefix}.collisionOperationFingerprint is malformed`);+ }+ }+ }+ }+ return { valid: errors.length === 0, errors };+}++function operationAffectedPublishTables(operation) {+ if (String(operation?.id || '').startsWith('create-table:')) {+ return [logicalNameFromSchemaName(operation.body?.SchemaName)];+ }+ if (String(operation?.id || '').startsWith('extend-column:')+ || String(operation?.id || '').startsWith('create-key:')) {+ const match = String(operation.apiPath || '').match(+ /EntityDefinitions\(LogicalName='([^']+)'\)/,+ );+ return match ? [normalizeName(match[1])] : [];+ }+ if (String(operation?.id || '').startsWith('create-relationship:')) {+ const table = operation.body?.ReferencingEntity || operation.body?.Entity1LogicalName;+ return table ? [normalizeName(table)] : [];+ }+ return [];+}++function revisedEquivalentOperation(previousOperation, previousManifest, normalized, context) {+ const expectedItemType = String(previousOperation?.id || '').startsWith('create-table:')+ ? 'table'+ : String(previousOperation?.id || '').startsWith('extend-column:')+ ? 'column'+ : String(previousOperation?.id || '').startsWith('create-relationship:')+ ? 'relationship'+ : String(previousOperation?.id || '').startsWith('create-key:')+ ? 'key'+ : null;+ const decision = (previousManifest.decisions || []).find(+ (item) => item.operation === previousOperation.id+ && item.itemType === expectedItemType,+ );+ if (!decision) return null;+ const table = normalized.tables.find(+ (item) => item.logicalName === normalizeName(+ decision.itemType === 'table' ? decision.requestedName : decision.table,+ ),+ );+ if (!table) return null;+ const aliases = { tables: new Map(), columns: new Map() };+ for (const candidate of normalized.tables) {+ if (candidate.plannedDecision === 'adapt') {+ aliases.tables.set(candidate.logicalName, normalizeName(candidate.adaptedLogicalName));+ }+ const effectiveTable = candidate.plannedDecision === 'adapt'+ ? normalizeName(candidate.adaptedLogicalName)+ : candidate.logicalName;+ for (const column of candidate.columns) {+ if (column.plannedDecision === 'adapt') {+ aliases.columns.set(+ `${effectiveTable}:${column.logicalName}`,+ normalizeName(column.adaptedLogicalName),+ );+ }+ }+ }+ const effectiveTable = aliases.tables.get(table.logicalName) || table.logicalName;++ if (decision.itemType === 'table') {+ if (!['create', 'adapt'].includes(table.plannedDecision)) return null;+ const ordinaryColumns = table.columns+ .filter((column) => (+ ['create', 'adapt'].includes(column.plannedDecision)+ && normalizeColumnType(column.type) !== 'lookup'+ && !isComputedColumn(column)+ ))+ .map((column) => ({+ ...column,+ effectiveLogicalName: normalizeName(column.adaptedLogicalName || column.logicalName),+ }));+ return operation(+ 0,+ `create-table:${effectiveTable}`,+ 'tableCreates',+ 'EntityDefinitions',+ tablePayload(table, effectiveTable, ordinaryColumns),+ context.solutionUniqueName,+ );+ }+ if (decision.itemType === 'column') {+ const column = table.columns.find(+ (item) => item.logicalName === normalizeName(decision.requestedName),+ );+ if (!column || !['create', 'adapt'].includes(column.plannedDecision)+ || normalizeColumnType(column.type) === 'lookup' || isComputedColumn(column)) {+ return null;+ }+ const effectiveColumn = normalizeName(+ column.adaptedLogicalName || column.logicalName,+ );+ return operation(+ 0,+ `extend-column:${effectiveTable}:${effectiveColumn}`,+ 'extensions',+ `EntityDefinitions(LogicalName='${effectiveTable}')/Attributes`,+ columnPayload(column, effectiveColumn),+ context.solutionUniqueName,+ );+ }+ if (decision.itemType === 'relationship') {+ const relationship = table.relationships.find(+ (item) => normalizeName(item.schemaName) === normalizeName(decision.requestedName),+ );+ if (!relationship || !['create', 'adapt'].includes(relationship.plannedDecision)) {+ return null;+ }+ const payload = relationshipPayload(relationship, aliases);+ return operation(+ 0,+ `create-relationship:${normalizeName(payload.SchemaName)}`,+ 'relationships',+ 'RelationshipDefinitions',+ payload,+ context.solutionUniqueName,+ );+ }+ if (decision.itemType === 'key') {+ const key = table.alternateKeys.find(+ (item) => normalizeName(item.schemaName) === normalizeName(decision.requestedName),+ );+ if (!key || !['create', 'adapt'].includes(key.plannedDecision)) return null;+ const payload = keyPayload(key, aliases, effectiveTable);+ return operation(+ 0,+ `create-key:${effectiveTable}:${normalizeName(payload.SchemaName)}`,+ 'alternateKeys',+ `EntityDefinitions(LogicalName='${effectiveTable}')/Keys`,+ payload,+ context.solutionUniqueName,+ );+ }+ return null;+}++function rollForwardPublishCheckpoint({+ checkpoint,+ previousManifest,+ journal,+ contract,+ approvalReceipt,+ contractBytes,+ planBytes,+ context,+ rolledAt = new Date().toISOString(),+}) {+ const contractValidation = validateContract(contract);+ if (!contractValidation.valid) {+ throw new Error(`Invalid revised schema contract: ${contractValidation.errors.join('; ')}`);+ }+ if (!contractBytes?.length || !planBytes?.length) {+ throw new Error('revised contract and plan bytes are required');+ }+ const normalized = normalizedContract(contract);+ const planSha256 = sha256(planBytes);+ const structuredSchemaSha256 = sha256(contractBytes);+ const approvalValidation = validateApprovalReceipt(approvalReceipt, {+ contract,+ planBytes,+ });+ if (!approvalValidation.valid) {+ throw new Error(+ `Invalid revised mobile plan approval receipt: ${approvalValidation.errors.join('; ')}`,+ );+ }+ if (normalized.approvedPlanSha256 !== planSha256) {+ throw new Error(+ 'revised structured schema approvedPlanSha256 does not match native-app-plan.md',+ );+ }+ if (normalized.approvedContractSha256+ !== approvalReceipt.approvedContractSha256+ || normalized.approvalReceiptSha256+ !== approvalReceipt.integritySha256) {+ throw new Error('revised structured schema approval binding does not match receipt');+ }+ if (normalizeName(normalized.publisherPrefix) !== normalizeName(context.publisherPrefix)) {+ throw new Error('revised publisherPrefix does not match execution context');+ }++ const priorCheckpointValidation = validatePublishCheckpoint(checkpoint, {+ context,+ planSha256: checkpoint?.binding?.planSha256,+ structuredSchemaSha256: checkpoint?.binding?.structuredSchemaSha256,+ });+ if (!priorCheckpointValidation.valid) {+ throw new Error(+ `Invalid prior publish checkpoint: ${priorCheckpointValidation.errors.join('; ')}`,+ );+ }+ if (!previousManifest || previousManifest.schemaVersion !== MANIFEST_SCHEMA_VERSION) {+ throw new Error('previous manifest schemaVersion is invalid');+ }+ const previousWithoutIntegrity = { ...previousManifest };+ delete previousWithoutIntegrity.integritySha256;+ if (previousManifest.integritySha256 !== sha256(stableJson(previousWithoutIntegrity))) {+ throw new Error('previous manifest integrity hash does not match');+ }+ if (stableJson(previousManifest.publishCheckpoint) !== stableJson(checkpoint)) {+ throw new Error('prior publish checkpoint does not match the previous manifest');+ }+ if (previousManifest.binding?.planSha256 !== checkpoint.binding.planSha256+ || previousManifest.binding?.structuredSchemaSha256+ !== checkpoint.binding.structuredSchemaSha256+ || previousManifest.binding?.environmentId !== context.environmentId+ || normalizeUrl(previousManifest.binding?.environmentUrl)+ !== normalizeUrl(context.environmentUrl)+ || previousManifest.binding?.solutionUniqueName !== context.solutionUniqueName) {+ throw new Error('previous manifest/checkpoint execution binding mismatch');+ }+ if (!journal || journal.schemaVersion !== 1+ || normalizeUrl(journal.binding?.environmentUrl) !== normalizeUrl(context.environmentUrl)+ || (journal.binding?.solution || null) !== (context.solutionUniqueName || null)+ || journal.inFlight?.failure?.collision !== true+ || journal.inFlight?.manifestHash !== previousManifest.integritySha256) {+ throw new Error('collision journal is missing or bound to different prior execution');+ }++ const previousOperations = (previousManifest.execution?.phases || [])+ .flatMap((phase) => phase.operations || []);+ const operationByFingerprint = new Map();+ for (const [position, operation] of previousOperations.entries()) {+ if (operation.index !== position) {+ throw new Error('previous manifest operation order is invalid');+ }+ const fingerprint = operationFingerprint(operation, context.solutionUniqueName);+ if (operationByFingerprint.has(fingerprint)) {+ throw new Error('previous manifest contains duplicate stable operation identities');+ }+ operationByFingerprint.set(fingerprint, operation);+ }+ const collisionOperation = operationByFingerprint.get(journal.inFlight.fingerprint);+ if (!collisionOperation+ || collisionOperation.id !== journal.inFlight.operationId) {+ throw new Error('collision journal operation is not present in the previous manifest');+ }++ const currentByRequestedName = new Map(normalized.tables.map((table) => [+ table.logicalName,+ table.plannedDecision === 'adapt'+ ? normalizeName(table.adaptedLogicalName)+ : table.logicalName,+ ]));+ const allowedTables = new Set(currentByRequestedName.values());+ const priorTables = checkpoint.tables.map(normalizeName);+ const excludedTables = priorTables.filter((table) => !allowedTables.has(table));+ const collisionTables = new Set(operationAffectedPublishTables(collisionOperation));+ const tableMappings = [];+ for (const excludedTable of excludedTables) {+ if (!collisionTables.has(excludedTable)) {+ throw new Error(+ `checkpoint table ${excludedTable} is outside the revised contract without `+ + 'collision evidence',+ );+ }+ const priorDecision = (previousManifest.decisions || []).find((decision) => (+ decision.itemType === 'table'+ && normalizeName(decision.effectiveName) === excludedTable+ ));+ const replacement = priorDecision+ ? currentByRequestedName.get(normalizeName(priorDecision.requestedName))+ : null;+ if (!replacement || !allowedTables.has(replacement) || replacement === excludedTable) {+ throw new Error(+ `collision table ${excludedTable} has no in-contract revised replacement`,+ );+ }+ tableMappings.push({+ requestedName: normalizeName(priorDecision.requestedName),+ from: excludedTable,+ to: replacement,+ });+ }++ const supersededCollisionFingerprints = new Set(+ (journal.recoveries || [])+ .filter((recovery) => (+ recovery.outcome === 'fresh-reconciliation-confirmed-superseded-collision'+ ))+ .map((recovery) => recovery.fingerprint),+ );+ for (const completedFingerprint of Object.keys(journal.completed || {})) {+ if (supersededCollisionFingerprints.has(completedFingerprint)) continue;+ const completedOperation = operationByFingerprint.get(completedFingerprint);+ if (!completedOperation) {+ throw new Error(+ `completed fingerprint ${completedFingerprint} is absent from the previous manifest`,+ );+ }+ const equivalentOperation = revisedEquivalentOperation(+ completedOperation,+ previousManifest,+ normalized,+ context,+ );+ if (!equivalentOperation+ || operationFingerprint(equivalentOperation, context.solutionUniqueName)+ !== completedFingerprint) {+ throw new Error(+ `completed metadata component ${completedOperation.id} was removed or changed `+ + 'in the revised structured contract',+ );+ }+ for (const table of operationAffectedPublishTables(completedOperation)) {+ if (!allowedTables.has(table)) {+ throw new Error(+ `completed metadata write for ${table} would be lost from the revised contract`,+ );+ }+ }+ }++ const activeTables = [+ ...priorTables.filter((table) => allowedTables.has(table)),+ ...tableMappings.map((mapping) => mapping.to),+ ];+ const rollForwards = [+ ...(checkpoint.rollForwards || []),+ {+ rolledAt,+ previousIntegritySha256: checkpoint.integritySha256,+ previousCheckpoint: stableClone(checkpoint),+ previousBinding: stableClone(checkpoint.binding),+ previousTables: [...priorTables],+ collisionOperationId: collisionOperation.id,+ collisionOperationFingerprint: journal.inFlight.fingerprint,+ tableMappings,+ },+ ];+ const rolled = createPublishCheckpoint({+ context,+ planSha256,+ structuredSchemaSha256,+ tables: activeTables,+ createdAt: checkpoint.createdAt,+ rollForwards,+ });+ const validation = validatePublishCheckpoint(rolled, {+ context,+ planSha256,+ structuredSchemaSha256,+ allowedTables,+ });+ if (!validation.valid) {+ throw new Error(`Rolled publish checkpoint is invalid: ${validation.errors.join('; ')}`);+ }+ return rolled;+}++function buildManifest({+ contract,+ approvalReceipt,+ reconciliation,+ planBytes,+ contractBytes,+ reconciliationBytes,+ context,+ publishCheckpoint = null,+ now = new Date().toISOString(),+ maxReconciliationAgeMs = DEFAULT_MAX_RECONCILIATION_AGE_MS,+}) {+ const contractValidation = validateContract(contract);+ if (!contractValidation.valid) {+ throw new Error(`Invalid schema contract: ${contractValidation.errors.join('; ')}`);+ }+ const normalized = normalizedContract(contract);+ const snapshot = reconciliation;+ const snapshotValidation = validateSnapshot(reconciliation, {+ environmentUrl: context.environmentUrl,+ tenantId: context.tenantId || undefined,+ });+ if (!snapshotValidation.valid) {+ throw new Error(+ `Invalid Dataverse execution reconciliation: ${snapshotValidation.errors.join('; ')}`,+ );+ }+ if (reconciliation.purpose !== 'execution-reconciliation'+ || reconciliation.reconciliation?.boundedExactNames !== true+ || reconciliation.reconciliation?.fullInventoryRead !== false) {+ throw new Error(+ 'execution reconciliation must be a fresh bounded exact-name artifact',+ );+ }+ const expectedScope = reconciliationScope(normalized);+ const actualExactTables = [...new Set(+ (reconciliation.inputs?.explicitTableNames || []).map(normalizeName),+ )].sort((left, right) => left.localeCompare(right));+ const actualProposedTables = [...new Set(+ (reconciliation.inputs?.proposedTableNames || []).map(normalizeName),+ )].sort((left, right) => left.localeCompare(right));+ if (stableJson(actualExactTables) !== stableJson(expectedScope.exactTables)+ || stableJson(actualProposedTables) !== stableJson(expectedScope.proposedTables)) {+ throw new Error(+ 'execution reconciliation scope does not exactly match the approved structured schema',+ );+ }+ if (normalizeName(normalized.publisherPrefix) !== normalizeName(context.publisherPrefix)) {+ throw new Error('publisherPrefix does not match the schema contract');+ }+ if (!context.environmentId) throw new Error('environmentId is required');+ if (!context.environmentUrl) throw new Error('environmentUrl is required');+ if (!context.solutionUniqueName) throw new Error('solutionUniqueName is required');+ if (!planBytes?.length) throw new Error('native-app-plan.md is required');+ if (!contractBytes?.length) throw new Error('schema contract bytes are required');+ if (!reconciliationBytes?.length) {+ throw new Error('execution reconciliation bytes are required');+ }+ const planHash = sha256(planBytes);+ const contractHash = sha256(contractBytes);+ const approvalValidation = validateApprovalReceipt(approvalReceipt, {+ contract,+ planBytes,+ });+ if (!approvalValidation.valid) {+ throw new Error(+ `Invalid mobile plan approval receipt: ${approvalValidation.errors.join('; ')}`,+ );+ }+ if (normalized.approvedPlanSha256 !== planHash) {+ throw new Error(+ 'structured schema approvedPlanSha256 does not match native-app-plan.md',+ );+ }+ if (normalized.approvedContractSha256+ !== approvalReceipt.approvedContractSha256) {+ throw new Error(+ 'structured schema approvedContractSha256 does not match approval receipt',+ );+ }+ if (normalized.approvalReceiptSha256+ !== approvalReceipt.integritySha256) {+ throw new Error(+ 'structured schema approvalReceiptSha256 does not match approval receipt',+ );+ }++ const nowMs = Date.parse(now);+ const snapshotMs = Date.parse(snapshot.generatedAt);+ if (!Number.isFinite(nowMs)) throw new Error('now must be an ISO timestamp');+ if (snapshotMs > nowMs + 5 * 60 * 1000) {+ throw new Error('execution reconciliation timestamp is in the future');+ }+ if (nowMs - snapshotMs > maxReconciliationAgeMs) {+ throw new Error(+ `execution reconciliation is stale: age ${nowMs - snapshotMs}ms exceeds `+ + `${maxReconciliationAgeMs}ms`,+ );+ }++ const indexes = snapshotIndexes(snapshot);+ const aliases = { tables: new Map(), columns: new Map() };+ for (const table of normalized.tables) {+ if (table.plannedDecision === 'adapt') {+ aliases.tables.set(table.logicalName, normalizeName(table.adaptedLogicalName));+ }+ }+ const allowedPublishTables = new Set(normalized.tables.map((table) => (+ aliases.tables.get(table.logicalName) || table.logicalName+ )));+ if (publishCheckpoint) {+ const checkpointValidation = validatePublishCheckpoint(publishCheckpoint, {+ context,+ planSha256: planHash,+ structuredSchemaSha256: contractHash,+ allowedTables: allowedPublishTables,+ });+ if (!checkpointValidation.valid) {+ throw new Error(+ `Invalid publish checkpoint: ${checkpointValidation.errors.join('; ')}`,+ );+ }+ }++ const decisions = [];+ const phaseOperations = Object.fromEntries(PHASE_ORDER.map((phase) => [phase, []]));+ const tableState = new Map();+ const publishTables = new Set((publishCheckpoint?.tables || []).map(normalizeName));+ let nextIndex = 0;++ for (const table of normalized.tables) {+ const requestedName = table.logicalName;+ const effectiveName = aliases.tables.get(requestedName) || requestedName;+ const live = presence(effectiveName, indexes);+ const tableId = contractItemId('table', requestedName);+ const requiredExisting = !isCustomName(effectiveName, context.publisherPrefix)+ || ['reuse', 'extend', 'defer'].includes(table.plannedDecision);++ if (table.plannedDecision === 'unverified') {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: table.reason || 'approved plan leaves this table unverified',+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: live.detail,+ });+ continue;+ }++ if (table.plannedDecision === 'defer') {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'defer',+ operation: 'none',+ reason: table.reason || 'approved plan defers this table',+ }));+ tableState.set(requestedName, { decision: 'defer', effectiveName, liveTable: live.detail });+ continue;+ }++ if (!live.inventory && !live.detail && !absenceProven(effectiveName, indexes)) {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: 'fresh reconciliation does not prove the target table present or absent',+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: null,+ });+ continue;+ }++ if (!live.inventory && !live.detail && absenceProven(effectiveName, indexes)) {+ if (requiredExisting && table.plannedDecision !== 'adapt') {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'defer',+ operation: 'none',+ reason: 'required-existing table is absent; destructive replacement is forbidden',+ }));+ tableState.set(requestedName, { decision: 'defer', effectiveName, liveTable: null });+ continue;+ }+ if (!isCustomName(effectiveName, context.publisherPrefix)) {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: 'new table name does not use the resolved publisher prefix',+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: null,+ });+ continue;+ }+ const unresolvedCreateColumns = table.columns.filter((column) => (+ column.plannedDecision === 'unverified'+ || (+ !['create', 'adapt', 'defer'].includes(column.plannedDecision)+ && !isComputedColumn(column)+ )+ ));+ if (unresolvedCreateColumns.length > 0) {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: `new table has non-create column decisions: ${unresolvedCreateColumns+ .map((column) => `${column.logicalName}=${column.plannedDecision}`)+ .join(', ')}`,+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: null,+ });+ continue;+ }+ const ordinaryColumns = table.columns+ .filter((column) => (+ ['create', 'adapt'].includes(column.plannedDecision)+ && normalizeColumnType(column.type) !== 'lookup'+ && !isComputedColumn(column)+ ))+ .map((column) => ({+ ...column,+ effectiveLogicalName: normalizeName(column.adaptedLogicalName || column.logicalName),+ }));+ const tableDecision = table.plannedDecision === 'adapt' ? 'adapt' : 'create';+ const tableOperation = operation(+ nextIndex++,+ `create-table:${effectiveName}`,+ 'tableCreates',+ 'EntityDefinitions',+ tablePayload(table, effectiveName, ordinaryColumns),+ context.solutionUniqueName,+ );+ phaseOperations.tableCreates.push(tableOperation);+ publishTables.add(effectiveName);+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: tableDecision,+ operation: tableOperation.id,+ reason: tableDecision === 'adapt'+ ? 'approved app-owned alias is absent and verified free'+ : 'new custom table is absent and verified free',+ }));+ tableState.set(requestedName, {+ decision: tableDecision,+ effectiveName,+ liveTable: null,+ created: true,+ });++ for (const column of table.columns) {+ const columnTarget = normalizeName(column.adaptedLogicalName || column.logicalName);+ if (column.plannedDecision === 'defer' || isComputedColumn(column)) {+ decisions.push(makeDecision({+ itemId: contractItemId('column', requestedName, column.logicalName),+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: isComputedColumn(column)+ ? 'calculated, rollup, and formula creation is outside the supported API boundary'+ : column.reason || 'approved plan defers this column',+ }));+ continue;+ }+ if (column.plannedDecision === 'adapt') {+ aliases.columns.set(`${effectiveName}:${column.logicalName}`, columnTarget);+ }+ decisions.push(makeDecision({+ itemId: contractItemId('column', requestedName, column.logicalName),+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: column.plannedDecision === 'adapt' ? 'adapt' : 'create',+ operation: normalizeColumnType(column.type) === 'lookup'+ ? 'relationship-phase'+ : tableOperation.id,+ reason: normalizeColumnType(column.type) === 'lookup'+ ? 'lookup is created by its relationship after both endpoint tables exist'+ : 'ordinary column is included inline in the table create',+ }));+ }+ continue;+ }++ if (!live.detail) {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: 'table presence is known but detailed columns/relationships/keys are unavailable',+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: null,+ });+ continue;+ }++ if (['create', 'adapt'].includes(table.plannedDecision)) {+ const tableComparison = tableCreateCompatibility(+ table,+ effectiveName,+ live.detail,+ );+ if (!tableComparison.compatible) {+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: 'unverified',+ operation: 'none',+ reason: `existing create/adapt target table behavior is incompatible: `+ + tableComparison.reasons.join('; '),+ }));+ tableState.set(requestedName, {+ decision: 'unverified',+ effectiveName,+ liveTable: live.detail,+ });+ continue;+ }+ }++ const comparisons = compatibleTableColumns(table, live.detail);+ const missing = comparisons.filter((item) => !item.liveColumn);+ const incompatible = comparisons.filter(+ (item) => item.liveColumn && !item.comparison.compatible,+ );+ const canExtend = Boolean(live.detail.customizable && live.detail.canCreateAttributes);+ const createColumns = [];+ let tableHasUnverified = false;+ let tableHasDeferred = false;++ for (const item of comparisons) {+ const column = item.column;+ const columnId = contractItemId('column', requestedName, column.logicalName);+ const columnTarget = item.targetName;+ if (column.plannedDecision === 'unverified') {+ tableHasUnverified = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'unverified',+ operation: 'none',+ reason: column.reason || 'approved plan leaves this column unverified',+ }));+ continue;+ }+ if (column.plannedDecision === 'defer') {+ tableHasDeferred = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: column.reason || 'approved plan defers this column',+ }));+ continue;+ }+ if (isComputedColumn(column)) {+ if (item.liveColumn && item.comparison.compatible) {+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'reuse',+ operation: 'none',+ reason: 'existing computed metadata exactly matches the approved contract',+ }));+ } else {+ tableHasDeferred = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: 'computed metadata cannot be created and does not exactly match for reuse',+ }));+ }+ continue;+ }+ if (item.liveColumn && item.comparison.compatible) {+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: column.plannedDecision === 'adapt' ? 'adapt' : 'reuse',+ operation: 'none',+ reason: column.plannedDecision === 'adapt'+ ? 'approved adapted column already exists with compatible metadata'+ : 'existing column metadata is compatible',+ }));+ if (column.plannedDecision === 'adapt') {+ aliases.columns.set(`${effectiveName}:${column.logicalName}`, columnTarget);+ }+ continue;+ }+ if (!item.liveColumn) {+ if (normalizeColumnType(column.type) === 'lookup') {+ if (+ ['create', 'adapt'].includes(column.plannedDecision)+ && canExtend+ && live.detail.canBeRelatedEntityInRelationship+ && isCustomName(columnTarget, context.publisherPrefix)+ ) {+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: column.plannedDecision,+ operation: 'relationship-phase',+ reason: 'lookup is absent and the child table permits relationship creation',+ }));+ if (column.plannedDecision === 'adapt') {+ aliases.columns.set(`${effectiveName}:${column.logicalName}`, columnTarget);+ }+ } else {+ tableHasDeferred = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: !['create', 'adapt'].includes(column.plannedDecision)+ ? `missing lookup was planned as ${column.plannedDecision}, not create/adapt`+ : 'child table cannot create lookup attributes/relationships',+ }));+ }+ } else if (+ ['create', 'adapt'].includes(table.plannedDecision)+ && normalizeColumnType(column.type) !== 'lookup'+ ) {+ tableHasUnverified = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'unverified',+ operation: 'none',+ reason: 'existing create/adapt target is missing an ordinary column that '+ + 'must have been included inline; extension would change the approved action',+ }));+ } else if (+ ['create', 'adapt'].includes(column.plannedDecision)+ && canExtend+ && isCustomName(columnTarget, context.publisherPrefix)+ ) {+ createColumns.push({ ...column, effectiveLogicalName: columnTarget });+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: column.plannedDecision === 'adapt' ? 'adapt' : 'create',+ operation: `extend-column:${effectiveName}:${columnTarget}`,+ reason: 'custom column is absent and the table permits extension',+ }));+ if (column.plannedDecision === 'adapt') {+ aliases.columns.set(`${effectiveName}:${column.logicalName}`, columnTarget);+ }+ } else {+ tableHasDeferred = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: !['create', 'adapt'].includes(column.plannedDecision)+ ? `missing column was planned as ${column.plannedDecision}, not create/adapt`+ : canExtend+ ? 'missing column is not owned by the resolved publisher'+ : 'target table cannot create attributes',+ }));+ }+ continue;+ }++ if (+ column.plannedDecision === 'adapt'+ && column.adaptedLogicalName+ && canExtend+ && absenceProven(columnTarget, indexes)+ ) {+ createColumns.push({ ...column, effectiveLogicalName: columnTarget });+ aliases.columns.set(`${effectiveName}:${column.logicalName}`, columnTarget);+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'adapt',+ operation: `extend-column:${effectiveName}:${columnTarget}`,+ reason: 'approved adapted column name is verified free beside incompatible metadata',+ }));+ } else if (column.plannedDecision === 'defer' || !canExtend) {+ tableHasDeferred = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'defer',+ operation: 'none',+ reason: `incompatible existing column: ${item.comparison.reasons.join('; ')}`,+ }));+ } else {+ tableHasUnverified = true;+ decisions.push(makeDecision({+ itemId: columnId,+ itemType: 'column',+ table: requestedName,+ requestedName: column.logicalName,+ effectiveName: columnTarget,+ decision: 'unverified',+ operation: 'none',+ reason: `incompatible column has no approved safe alias: ${item.comparison.reasons.join('; ')}`,+ }));+ }+ }++ for (const column of createColumns.sort((left, right) => (+ left.effectiveLogicalName.localeCompare(right.effectiveLogicalName)+ ))) {+ phaseOperations.extensions.push(operation(+ nextIndex++,+ `extend-column:${effectiveName}:${column.effectiveLogicalName}`,+ 'extensions',+ `EntityDefinitions(LogicalName='${effectiveName}')/Attributes`,+ columnPayload(column, column.effectiveLogicalName),+ context.solutionUniqueName,+ ));+ publishTables.add(effectiveName);+ }++ const tableDecision = tableHasUnverified+ ? 'unverified'+ : createColumns.length > 0+ ? 'extend'+ : table.plannedDecision === 'adapt'+ ? 'adapt'+ : 'reuse';+ decisions.push(makeDecision({+ itemId: tableId,+ itemType: 'table',+ requestedName,+ effectiveName,+ decision: tableDecision,+ operation: createColumns.length > 0 ? 'extensions-phase' : 'none',+ reason: tableHasUnverified+ ? 'one or more columns remain unverified'+ : createColumns.length > 0+ ? `${createColumns.length} missing ordinary column(s) will be extended`+ : tableHasDeferred+ ? 'compatible table reused; unsupported additions are explicitly deferred'+ : incompatible.length > 0+ ? 'existing table reused with approved adapted/deferred conflicts'+ : missing.length > 0+ ? 'existing table reused with relationship-only additions'+ : 'existing table and planned columns are compatible',+ }));+ tableState.set(requestedName, {+ decision: tableDecision,+ effectiveName,+ liveTable: live.detail,+ created: false,+ });+ }++ for (const table of normalized.tables) {+ const ownerState = tableState.get(table.logicalName);+ for (const relationship of table.relationships) {+ const relationshipId = contractItemId(+ 'relationship',+ table.logicalName,+ relationship.schemaName,+ );+ if (relationship.plannedDecision === 'unverified') {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: relationship.reason || 'approved plan leaves this relationship unverified',+ }));+ continue;+ }+ if (relationship.plannedDecision === 'defer') {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: relationship.reason || 'approved plan defers this relationship',+ }));+ continue;+ }+ const endpointNames = relationship.kind === 'many-to-one'+ ? [relationship.childTable, relationship.parentTable]+ : [relationship.entity1, relationship.entity2];+ const endpointStates = endpointNames.map((name) => tableState.get(normalizeName(name)));+ if (endpointStates.some((state) => !state || ['defer', 'unverified'].includes(state.decision))) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: endpointStates.some((state) => state?.decision === 'unverified' || !state)+ ? 'unverified'+ : 'defer',+ operation: 'none',+ reason: 'relationship endpoint is deferred or unverified',+ }));+ continue;+ }+ const childState = relationship.kind === 'many-to-one'+ ? tableState.get(normalizeName(relationship.childTable))+ : ownerState;+ const parentState = relationship.kind === 'many-to-one'+ ? tableState.get(normalizeName(relationship.parentTable))+ : null;+ const relationshipCapable = relationship.kind === 'many-to-one'+ ? Boolean(+ (+ childState?.created+ || (+ childState?.liveTable?.customizable+ && childState?.liveTable?.canCreateAttributes+ && childState?.liveTable?.canBeRelatedEntityInRelationship+ )+ )+ && (+ parentState?.created+ || parentState?.liveTable?.canBePrimaryEntityInRelationship+ )+ )+ : endpointStates.every((state) => (+ state.created+ || Boolean(+ state.liveTable?.customizable+ && state.liveTable?.canBeInManyToMany,+ )+ ));+ const existing = relationshipExists(+ relationship,+ childState?.liveTable,+ aliases,+ );+ if (existing.exists && existing.compatible) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: relationship.plannedDecision === 'adapt' ? 'adapt' : 'reuse',+ operation: 'none',+ reason: 'existing relationship metadata is compatible',+ }));+ continue;+ }+ if (existing.exists && !existing.compatible) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.schemaName,+ decision: relationship.plannedDecision === 'adapt'+ ? 'unverified'+ : 'defer',+ operation: 'none',+ reason: relationship.plannedDecision === 'adapt'+ ? 'adapted relationship identity exists but compatibility evidence mismatches'+ : 'same-name relationship is incompatible and has no approved alias',+ }));+ continue;+ }+ if (+ relationship.kind === 'many-to-many'+ && !existing.exists+ && ['create', 'adapt'].includes(relationship.plannedDecision)+ ) {+ const effectiveIntersect = normalizeName(+ relationship.adaptedIntersectTable || relationship.intersectTable,+ );+ const intersectCheck = indexes.proposedByName.get(effectiveIntersect);+ if (!intersectCheck || intersectCheck.status !== 'missing') {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: intersectCheck?.status === 'collision'+ ? `effective intersect name ${effectiveIntersect} collides in fresh reconciliation`+ : `effective intersect name ${effectiveIntersect} was not freshly verified free`,+ }));+ continue;+ }+ }+ if (!existing.verified && !childState?.created) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: 'relationship collection is not available in the fresh reconciliation',+ }));+ continue;+ }+ if (!existing.exists && !relationshipCapable) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: 'one or more existing relationship endpoints lack verified creation capability',+ }));+ continue;+ }+ if (!['create', 'adapt'].includes(relationship.plannedDecision)) {+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: relationship.adaptedSchemaName || relationship.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: `missing relationship was planned as ${relationship.plannedDecision}, not create/adapt`,+ }));+ continue;+ }+ const payload = relationshipPayload(relationship, aliases);+ const operationId = `create-relationship:${normalizeName(payload.SchemaName)}`;+ phaseOperations.relationships.push(operation(+ nextIndex++,+ operationId,+ 'relationships',+ 'RelationshipDefinitions',+ payload,+ context.solutionUniqueName,+ ));+ publishTables.add(+ relationship.kind === 'many-to-one'+ ? payload.ReferencingEntity+ : payload.Entity1LogicalName,+ );+ decisions.push(makeDecision({+ itemId: relationshipId,+ itemType: 'relationship',+ table: table.logicalName,+ requestedName: relationship.schemaName,+ effectiveName: normalizeName(payload.SchemaName),+ decision: relationship.plannedDecision === 'adapt' ? 'adapt' : 'create',+ operation: operationId,+ reason: 'relationship is absent after both endpoints are resolved',+ }));+ }+ }++ for (const table of normalized.tables) {+ const state = tableState.get(table.logicalName);+ for (const key of table.alternateKeys) {+ const keyId = contractItemId('key', table.logicalName, key.schemaName);+ if (key.plannedDecision === 'unverified') {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: key.reason || 'approved plan leaves this alternate key unverified',+ }));+ continue;+ }+ if (key.plannedDecision === 'defer' || state?.decision === 'defer') {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: key.reason || 'key or target table is deferred',+ }));+ continue;+ }+ if (!state || state.decision === 'unverified') {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: 'target table is unverified',+ }));+ continue;+ }+ const existing = keyExists(key, state.liveTable, aliases, state.effectiveName);+ if (existing.exists && existing.compatible) {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: key.plannedDecision === 'adapt' ? 'adapt' : 'reuse',+ operation: 'none',+ reason: 'existing alternate key is active or pending with compatible columns',+ }));+ continue;+ }+ if (existing.exists && !existing.compatible) {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: 'same-name or same-column alternate key is failed or incompatible',+ }));+ continue;+ }+ if (!existing.verified && !state.created) {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'unverified',+ operation: 'none',+ reason: 'alternate-key collection is unavailable in the fresh reconciliation',+ }));+ continue;+ }+ if (!['create', 'adapt'].includes(key.plannedDecision)) {+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: key.adaptedSchemaName || key.schemaName,+ decision: 'defer',+ operation: 'none',+ reason: `missing alternate key was planned as ${key.plannedDecision}, not create/adapt`,+ }));+ continue;+ }+ const payload = keyPayload(key, aliases, state.effectiveName);+ const operationId = `create-key:${state.effectiveName}:${normalizeName(payload.SchemaName)}`;+ phaseOperations.alternateKeys.push(operation(+ nextIndex++,+ operationId,+ 'alternateKeys',+ `EntityDefinitions(LogicalName='${state.effectiveName}')/Keys`,+ payload,+ context.solutionUniqueName,+ ));+ publishTables.add(state.effectiveName);+ decisions.push(makeDecision({+ itemId: keyId,+ itemType: 'key',+ table: table.logicalName,+ requestedName: key.schemaName,+ effectiveName: normalizeName(payload.SchemaName),+ decision: key.plannedDecision === 'adapt' ? 'adapt' : 'create',+ operation: operationId,+ reason: 'alternate key is absent after its table and columns are resolved',+ }));+ }+ }++ if (publishTables.size > 0) {+ const entities = [...publishTables].sort((left, right) => left.localeCompare(right));+ phaseOperations.publish.push(operation(+ nextIndex++,+ 'publish-customizations',+ 'publish',+ 'PublishXml',+ {+ ParameterXml: `<importexportxml><entities>${entities+ .map((entityName) => `<entity>${xmlEscape(entityName)}</entity>`)+ .join('')}</entities></importexportxml>`,+ },+ null,+ ));+ }++ const classifiedItemIds = new Set(decisions.map((decision) => decision.itemId));+ for (const table of normalized.tables) {+ const state = tableState.get(table.logicalName);+ for (const column of table.columns) {+ const itemId = contractItemId('column', table.logicalName, column.logicalName);+ if (classifiedItemIds.has(itemId)) continue;+ const decision = state?.decision === 'defer' ? 'defer' : 'unverified';+ decisions.push(makeDecision({+ itemId,+ itemType: 'column',+ table: table.logicalName,+ requestedName: column.logicalName,+ effectiveName: normalizeName(column.adaptedLogicalName || column.logicalName),+ decision,+ operation: 'none',+ reason: decision === 'defer'+ ? 'containing table is deferred'+ : 'containing table metadata is unverified',+ }));+ classifiedItemIds.add(itemId);+ }+ }++ decisions.sort((left, right) => left.itemId.localeCompare(right.itemId));+ const contractIds = new Set();+ for (const table of normalized.tables) {+ contractIds.add(contractItemId('table', table.logicalName));+ for (const column of table.columns) {+ contractIds.add(contractItemId('column', table.logicalName, column.logicalName));+ }+ for (const relationship of table.relationships) {+ contractIds.add(contractItemId('relationship', table.logicalName, relationship.schemaName));+ }+ for (const key of table.alternateKeys) {+ contractIds.add(contractItemId('key', table.logicalName, key.schemaName));+ }+ }+ const decisionIds = new Set(decisions.map((decision) => decision.itemId));+ const missingDecisions = [...contractIds].filter((itemId) => !decisionIds.has(itemId));+ const duplicateDecisionCount = decisions.length - decisionIds.size;+ if (missingDecisions.length > 0 || duplicateDecisionCount > 0) {+ throw new Error(+ `Decision coverage failure: missing=${missingDecisions.join(',') || 'none'}, `+ + `duplicates=${duplicateDecisionCount}`,+ );+ }++ const approvedDecisionById = new Map();+ for (const table of normalized.tables) {+ approvedDecisionById.set(+ contractItemId('table', table.logicalName),+ table.plannedDecision,+ );+ for (const column of table.columns) {+ approvedDecisionById.set(+ contractItemId('column', table.logicalName, column.logicalName),+ column.plannedDecision,+ );+ }+ for (const relationship of table.relationships) {+ approvedDecisionById.set(+ contractItemId('relationship', table.logicalName, relationship.schemaName),+ relationship.plannedDecision,+ );+ }+ for (const key of table.alternateKeys) {+ approvedDecisionById.set(+ contractItemId('key', table.logicalName, key.schemaName),+ key.plannedDecision,+ );+ }+ }+ for (const decision of decisions) {+ const observedOutcome = decision.decision;+ const approvedDecision = approvedDecisionById.get(decision.itemId);+ decision.decision = approvedDecision;+ decision.observedOutcome = observedOutcome;+ decision.verificationStatus = approvedDecision === 'unverified'+ || observedOutcome === 'unverified'+ ? 'unverified'+ : observedOutcome === 'defer' && approvedDecision !== 'defer'+ ? 'conflict'+ : 'verified';+ }++ const unverified = decisions.filter(+ (decision) => decision.verificationStatus !== 'verified',+ );+ const unverifiedFacts = decisions.filter(+ (decision) => decision.verificationStatus === 'unverified',+ );+ const deferred = decisions.filter((decision) => decision.decision === 'defer');+ const conflicts = decisions.filter((decision) => decision.verificationStatus === 'conflict');+ const decisionById = new Map(decisions.map((decision) => [decision.itemId, decision]));+ const serviceRequiredTables = normalized.tables+ .filter((table) => table.serviceRequired)+ .map((table) => {+ const tableDecision = decisionById.get(contractItemId('table', table.logicalName));+ return {+ requestedName: table.logicalName,+ logicalName: aliases.tables.get(table.logicalName) || table.logicalName,+ decision: table.plannedDecision,+ verificationStatus: tableDecision?.verificationStatus || 'unverified',+ };+ })+ .filter((table) => table.decision !== 'defer')+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName));+ for (const table of normalized.tables) {+ for (const relationship of table.relationships) {+ if (relationship.kind !== 'many-to-many' || !relationship.serviceRequired) continue;+ const relationshipDecision = decisionById.get(contractItemId(+ 'relationship',+ table.logicalName,+ relationship.schemaName,+ ));+ if (!relationshipDecision+ || relationshipDecision.decision === 'defer') continue;+ serviceRequiredTables.push({+ requestedName: relationship.intersectTable,+ logicalName: normalizeName(+ relationship.adaptedIntersectTable || relationship.intersectTable,+ ),+ decision: relationshipDecision.decision,+ verificationStatus: relationshipDecision.verificationStatus,+ });+ }+ }+ const uniqueServiceRequiredTables = [...new Map(+ serviceRequiredTables+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName))+ .map((table) => [table.logicalName, table]),+ ).values()];+ const approvedServiceDependencies = new Map(+ approvalReceipt.serviceRequiredTables.map((item) => [+ normalizeName(item.logicalName),+ item.consumers,+ ]),+ );+ const manifestServiceNames = uniqueServiceRequiredTables+ .map((item) => normalizeName(item.logicalName))+ .sort((left, right) => left.localeCompare(right));+ const approvedServiceNames = [...approvedServiceDependencies.keys()]+ .sort((left, right) => left.localeCompare(right));+ if (stableJson(manifestServiceNames) !== stableJson(approvedServiceNames)) {+ throw new Error(+ 'manifest serviceRequiredTables do not exactly match approved screen/service dependencies',+ );+ }+ for (const item of uniqueServiceRequiredTables) {+ item.consumers = approvedServiceDependencies.get(normalizeName(item.logicalName));+ }+ let orderedIndex = 0;+ for (const phase of PHASE_ORDER) {+ for (const item of phaseOperations[phase]) item.index = orderedIndex++;+ }+ const operations = PHASE_ORDER.flatMap((phase) => phaseOperations[phase]);+ const nextPublishCheckpoint = publishTables.size > 0+ && (unverified.length === 0 || publishCheckpoint)+ ? createPublishCheckpoint({+ context,+ planSha256: planHash,+ structuredSchemaSha256: contractHash,+ tables: [...publishTables],+ createdAt: publishCheckpoint?.createdAt || now,+ rollForwards: publishCheckpoint?.rollForwards || [],+ })+ : null;+ const manifest = {+ schemaVersion: MANIFEST_SCHEMA_VERSION,+ preparedAt: now,+ executable: unverified.length === 0,+ binding: {+ environmentId: context.environmentId,+ environmentUrl: String(context.environmentUrl).replace(/\/+$/, ''),+ tenantId: context.tenantId || null,+ publisherPrefix: normalizeName(context.publisherPrefix),+ solutionUniqueName: context.solutionUniqueName,+ planSha256: planHash,+ approvedContractSha256: approvalReceipt.approvedContractSha256,+ approvalReceiptSha256: approvalReceipt.integritySha256,+ structuredSchemaSha256: contractHash,+ reconciliationSha256: sha256(reconciliationBytes),+ reconciliationGeneratedAt: reconciliation.generatedAt,+ maxReconciliationAgeMs,+ },+ summary: {+ decisionCount: decisions.length,+ metadataOperationCount: operations.length,+ metadataWriteCount: operations.filter((item) => item.method === 'POST').length,+ unresolvedCount: unverified.length,+ unverifiedCount: unverifiedFacts.length,+ conflictCount: conflicts.length,+ deferredCount: deferred.length,+ serviceRequiredTableCount: uniqueServiceRequiredTables.length,+ },+ decisions,+ aliases: {+ tables: Object.fromEntries([...aliases.tables].sort()),+ columns: Object.fromEntries([...aliases.columns].sort()),+ },+ service: {+ requiredTables: uniqueServiceRequiredTables,+ generationMode: 'sequential-outside-batch-metadata',+ },+ publishCheckpoint: nextPublishCheckpoint,+ execution: {+ executor: 'BATCH-METADATA',+ odataBatch: false,+ parallelWrites: false,+ journal: {+ required: true,+ schemaVersion: 1,+ atomicPerOperation: true,+ uncertainResumeRequiresFreshReconciliation: true,+ },+ phases: PHASE_ORDER.map((name) => ({+ name,+ operations: phaseOperations[name],+ })),+ },+ verification: {+ unresolvedItemIds: unverified.map((decision) => decision.itemId),+ conflictItemIds: conflicts.map((decision) => decision.itemId),+ deferredItemIds: deferred.map((decision) => decision.itemId),+ reconciliationScope: expectedScope,+ },+ };+ manifest.integritySha256 = sha256(stableJson(manifest));+ return manifest;+}++function validateManifest(manifest, {+ planBytes,+ contractBytes,+ reconciliationBytes,+ contract,+ approvalReceipt,+ reconciliation,+ context,+ publishCheckpoint = null,+ now = new Date().toISOString(),+ maxReconciliationAgeMs = DEFAULT_MAX_RECONCILIATION_AGE_MS,+ requireExecutable = false,+}) {+ const errors = [];+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {+ return { valid: false, errors: ['manifest must be an object'] };+ }+ if (manifest.schemaVersion !== MANIFEST_SCHEMA_VERSION) {+ errors.push(`manifest.schemaVersion must equal ${MANIFEST_SCHEMA_VERSION}`);+ }+ const integrity = manifest.integritySha256;+ const withoutIntegrity = { ...manifest };+ delete withoutIntegrity.integritySha256;+ if (!integrity || integrity !== sha256(stableJson(withoutIntegrity))) {+ errors.push('manifest integrity hash does not match');+ }+ const binding = manifest.binding || {};+ if (binding.maxReconciliationAgeMs !== maxReconciliationAgeMs) {+ errors.push('maxReconciliationAgeMs mismatch');+ }+ if (context) {+ if (binding.environmentId !== context.environmentId) errors.push('environmentId mismatch');+ if (normalizeUrl(binding.environmentUrl) !== normalizeUrl(context.environmentUrl)) {+ errors.push('environmentUrl mismatch');+ }+ if (context.tenantId+ && normalizeName(binding.tenantId) !== normalizeName(context.tenantId)) {+ errors.push('tenantId mismatch');+ }+ if (normalizeName(binding.publisherPrefix) !== normalizeName(context.publisherPrefix)) {+ errors.push('publisherPrefix mismatch');+ }+ if (binding.solutionUniqueName !== context.solutionUniqueName) {+ errors.push('solutionUniqueName mismatch');+ }+ }+ if (planBytes && binding.planSha256 !== sha256(planBytes)) errors.push('plan hash mismatch');+ if (approvalReceipt) {+ const approvalValidation = validateApprovalReceipt(approvalReceipt, {+ contract,+ planBytes,+ });+ if (!approvalValidation.valid) {+ errors.push(...approvalValidation.errors.map(+ (error) => `mobile plan approval receipt: ${error}`,+ ));+ }+ if (binding.approvedContractSha256+ !== approvalReceipt.approvedContractSha256) {+ errors.push('approved contract hash mismatch');+ }+ if (binding.approvalReceiptSha256+ !== approvalReceipt.integritySha256) {+ errors.push('mobile plan approval receipt hash mismatch');+ }+ } else {+ errors.push('mobile plan approval receipt is required for execution validation');+ }+ if (contractBytes && binding.structuredSchemaSha256 !== sha256(contractBytes)) {+ errors.push('structured schema hash mismatch');+ }+ if (reconciliationBytes+ && binding.reconciliationSha256 !== sha256(reconciliationBytes)) {+ errors.push('execution reconciliation hash mismatch');+ }+ if (reconciliation) {+ if (binding.reconciliationGeneratedAt !== reconciliation.generatedAt) {+ errors.push('execution reconciliation timestamp mismatch');+ }+ const snapshotValidation = validateSnapshot(reconciliation, {+ environmentUrl: context?.environmentUrl,+ tenantId: context?.tenantId || undefined,+ });+ if (!snapshotValidation.valid) {+ errors.push(...snapshotValidation.errors.map(+ (error) => `execution reconciliation: ${error}`,+ ));+ }+ if (reconciliation.purpose !== 'execution-reconciliation'+ || reconciliation.reconciliation?.boundedExactNames !== true+ || reconciliation.reconciliation?.fullInventoryRead !== false) {+ errors.push('execution reconciliation is not a bounded exact-name artifact');+ }+ const age = Date.parse(now) - Date.parse(reconciliation.generatedAt);+ if (!Number.isFinite(age) || age < -5 * 60 * 1000) {+ errors.push('execution reconciliation freshness cannot be established');+ } else if (age > maxReconciliationAgeMs) {+ errors.push('execution reconciliation is stale');+ }+ }+ if (contract) {+ const contractValidation = validateContract(contract);+ if (!contractValidation.valid) {+ errors.push(...contractValidation.errors.map((error) => `contract: ${error}`));+ } else {+ const expectedIds = new Set();+ for (const table of normalizedContract(contract).tables) {+ expectedIds.add(contractItemId('table', table.logicalName));+ for (const column of table.columns) {+ expectedIds.add(contractItemId('column', table.logicalName, column.logicalName));+ }+ for (const relationship of table.relationships) {+ expectedIds.add(contractItemId(+ 'relationship',+ table.logicalName,+ relationship.schemaName,+ ));+ }+ for (const key of table.alternateKeys) {+ expectedIds.add(contractItemId('key', table.logicalName, key.schemaName));+ }+ }+ const actualIds = (manifest.decisions || []).map((decision) => decision.itemId);+ if (new Set(actualIds).size !== actualIds.length) {+ errors.push('manifest decision itemIds must be unique');+ }+ const actualIdSet = new Set(actualIds);+ if (expectedIds.size !== actualIdSet.size+ || [...expectedIds].some((itemId) => !actualIdSet.has(itemId))) {+ errors.push('manifest decision coverage does not match the contract');+ }+ }+ }++ const phases = manifest.execution?.phases;+ if (!Array.isArray(phases)+ || phases.map((phase) => phase.name).join(',') !== PHASE_ORDER.join(',')) {+ errors.push('manifest phase order is invalid');+ } else {+ const operations = phases.flatMap((phase) => (+ (phase.operations || []).map((item) => ({ ...item, enclosingPhase: phase.name }))+ ));+ for (const [index, item] of operations.entries()) {+ if (item.index !== index) errors.push(`operation index ${item.index} is out of order`);+ if (item.phase !== item.enclosingPhase) {+ errors.push(`operation ${item.id} phase does not match its container`);+ }+ if (item.method !== 'POST') errors.push(`operation ${item.id} is not a POST`);+ if (['DELETE', 'PATCH', 'PUT'].includes(item.method)) {+ errors.push(`operation ${item.id} is destructive or mutating in-place`);+ }+ }+ if (manifest.summary?.metadataOperationCount !== operations.length) {+ errors.push('metadataOperationCount does not match operations');+ }+ }+ const unverified = (manifest.decisions || [])+ .filter((decision) => decision.verificationStatus !== 'verified');+ if (!Array.isArray(manifest.decisions)+ || manifest.decisions.some((decision) => !DECISIONS.has(decision.decision))) {+ errors.push('manifest decisions must use the reconciliation taxonomy');+ }+ if ((manifest.decisions || []).some(+ (decision) => !['verified', 'unverified', 'conflict'].includes(+ decision.verificationStatus,+ ),+ )) {+ errors.push('manifest decisions must include a mechanical verificationStatus');+ }+ if (manifest.summary?.decisionCount !== (manifest.decisions || []).length) {+ errors.push('decisionCount does not match decisions');+ }+ if (+ unverified.length > 0+ && (+ !Array.isArray(manifest.verification?.reconciliationScope?.exactTables)+ || manifest.verification.reconciliationScope.exactTables.length === 0+ )+ ) {+ errors.push('unresolved decisions require an explicit reconciliation scope');+ }+ if (manifest.executable !== (unverified.length === 0)) {+ errors.push('manifest executable flag does not match unverified decisions');+ }+ if (requireExecutable && !manifest.executable) {+ errors.push('manifest is not executable; approved schema revision is required');+ }+ if (contract && approvalReceipt && reconciliation && context && planBytes+ && contractBytes && reconciliationBytes) {+ try {+ const expectedManifest = buildManifest({+ contract,+ approvalReceipt,+ reconciliation,+ planBytes,+ contractBytes,+ reconciliationBytes,+ context,+ publishCheckpoint,+ now: manifest.preparedAt,+ maxReconciliationAgeMs,+ });+ if (stableJson(expectedManifest) !== stableJson(manifest)) {+ errors.push(+ 'manifest semantic content does not match deterministic '+ + 'structured-schema/reconciliation rebuild',+ );+ }+ } catch (error) {+ errors.push(`manifest semantic rebuild failed: ${error.message}`);+ }+ } else {+ errors.push(+ 'manifest semantic validation requires bound structured schema, '+ + 'mobile plan approval receipt, execution reconciliation, plan, and context',+ );+ }+ return { valid: errors.length === 0, errors };+}++function readBytes(file) {+ return fs.readFileSync(path.resolve(file));+}++function readJson(file) {+ return JSON.parse(readBytes(file).toString('utf8'));+}++function contextFromArgs(args) {+ return {+ environmentId: args['environment-id'],+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'] || null,+ publisherPrefix: args['publisher-prefix'],+ solutionUniqueName: args.solution,+ };+}++function usage() {+ return [+ 'Build:',+ ' node build-dataverse-operation-manifest.js --contract <json> --approval-receipt <json> --reconciliation <json> --plan <md> --output <json> \\',+ ' --environment-id <id> --env-url <url> [--tenant-id <id>] --publisher-prefix <prefix> --solution <unique-name> \\',+ ' [--publish-checkpoint <json>]',+ 'Normalize a planner sidecar:',+ ' node build-dataverse-operation-manifest.js --normalize-contract <json> --output <json>',+ 'Bind a normalized sidecar to the fully approved plan:',+ ' node build-dataverse-operation-manifest.js --bind-plan <json> --approval-receipt <json> --plan <md> --output <json>',+ 'Roll a collision checkpoint into a revised approved contract:',+ ' node build-dataverse-operation-manifest.js --roll-forward-checkpoint <json> --previous-manifest <json> \\',+ ' --journal <json> --contract <json> --approval-receipt <json> --plan <md> --output <json> --environment-id <id> \\',+ ' --env-url <url> [--tenant-id <id>] --publisher-prefix <prefix> --solution <unique-name>',+ 'Write fresh reconciliation scope:',+ ' node build-dataverse-operation-manifest.js --reconciliation-scope <json> --output <json>',+ 'Validate before execution:',+ ' node build-dataverse-operation-manifest.js --validate <manifest> --contract <json> --approval-receipt <json> --reconciliation <json> --plan <md> \\',+ ' --environment-id <id> --env-url <url> [--tenant-id <id>] --publisher-prefix <prefix> --solution <unique-name> \\',+ ' [--publish-checkpoint <json>] --require-executable',+ ].join('\n');+}++function main() {+ const args = parseArgs(process.argv);+ try {+ if (args['normalize-contract']) {+ if (!args.output) throw new Error('--output is required');+ const contract = readJson(args['normalize-contract']);+ const validation = validateContract(contract);+ if (!validation.valid) {+ throw new Error(`Invalid schema contract: ${validation.errors.join('; ')}`);+ }+ const normalized = normalizedContract(contract);+ atomicWriteJson(path.resolve(args.output), normalized);+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'normalize-contract',+ output: path.resolve(args.output),+ tables: normalized.tables.length,+ })}\n`);+ return;+ }+ if (args['bind-plan']) {+ if (!args.output || !args.plan || !args['approval-receipt']) {+ throw new Error('--plan, --approval-receipt, and --output are required');+ }+ const bound = bindContractToPlan(+ readJson(args['bind-plan']),+ readBytes(args.plan),+ readJson(args['approval-receipt']),+ );+ atomicWriteJson(path.resolve(args.output), bound);+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'bind-plan',+ output: path.resolve(args.output),+ approvedPlanSha256: bound.approvedPlanSha256,+ approvedContractSha256: bound.approvedContractSha256,+ })}\n`);+ return;+ }+ if (args['reconciliation-scope']) {+ if (!args.output) throw new Error('--output is required');+ const scope = reconciliationScope(readJson(args['reconciliation-scope']));+ atomicWriteJson(path.resolve(args.output), scope);+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'reconciliation-scope',+ output: path.resolve(args.output),+ exactTables: scope.exactTables.length,+ proposedTables: scope.proposedTables.length,+ })}\n`);+ return;+ }+ if (args['roll-forward-checkpoint']) {+ const requiredRollForward = [+ 'previous-manifest',+ 'journal',+ 'contract',+ 'approval-receipt',+ 'plan',+ 'output',+ 'environment-id',+ 'env-url',+ 'publisher-prefix',+ 'solution',+ ];+ const missingRollForward = requiredRollForward.filter((key) => !args[key]);+ if (missingRollForward.length > 0) {+ throw new Error(+ `Missing roll-forward args: ${missingRollForward.join(', ')}`,+ );+ }+ const contractBytes = readBytes(args.contract);+ const planBytes = readBytes(args.plan);+ const rolled = rollForwardPublishCheckpoint({+ checkpoint: readJson(args['roll-forward-checkpoint']),+ previousManifest: readJson(args['previous-manifest']),+ journal: readJson(args.journal),+ contract: JSON.parse(contractBytes.toString('utf8')),+ approvalReceipt: readJson(args['approval-receipt']),+ contractBytes,+ planBytes,+ context: contextFromArgs(args),+ rolledAt: args.now || new Date().toISOString(),+ });+ atomicWriteJson(path.resolve(args.output), rolled);+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'roll-forward-checkpoint',+ output: path.resolve(args.output),+ tables: rolled.tables.length,+ rollForwards: rolled.rollForwards.length,+ })}\n`);+ return;+ }++ const required = ['contract', 'approval-receipt', 'reconciliation', 'plan',+ 'environment-id', 'env-url',+ 'publisher-prefix', 'solution'];+ const missing = required.filter((key) => !args[key]);+ if (missing.length > 0) throw new Error(`Missing required args: ${missing.join(', ')}`);+ const contractBytes = readBytes(args.contract);+ const reconciliationBytes = readBytes(args.reconciliation);+ const planBytes = readBytes(args.plan);+ const contract = JSON.parse(contractBytes.toString('utf8'));+ const approvalReceipt = readJson(args['approval-receipt']);+ const reconciliation = JSON.parse(reconciliationBytes.toString('utf8'));+ const context = contextFromArgs(args);+ const now = args.now || new Date().toISOString();+ const maxReconciliationAgeMs = args['max-reconciliation-age-ms']+ ? Number(args['max-reconciliation-age-ms'])+ : DEFAULT_MAX_RECONCILIATION_AGE_MS;+ if (!Number.isFinite(maxReconciliationAgeMs) || maxReconciliationAgeMs <= 0) {+ throw new Error('--max-reconciliation-age-ms must be a positive number');+ }+ const publishCheckpoint = args['publish-checkpoint']+ && fs.existsSync(path.resolve(args['publish-checkpoint']))+ ? readJson(args['publish-checkpoint'])+ : null;++ if (args.validate) {+ const manifest = readJson(args.validate);+ if (manifest.publishCheckpoint+ && (!args['publish-checkpoint'] || !publishCheckpoint)) {+ throw new Error(+ 'Manifest validation failed: persisted publish checkpoint is required',+ );+ }+ const validation = validateManifest(manifest, {+ planBytes,+ contractBytes,+ reconciliationBytes,+ contract,+ approvalReceipt,+ reconciliation,+ context,+ publishCheckpoint,+ now,+ maxReconciliationAgeMs,+ requireExecutable: Boolean(args['require-executable']),+ });+ if (!validation.valid) {+ throw new Error(`Manifest validation failed: ${validation.errors.join('; ')}`);+ }+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'validate',+ executable: manifest.executable,+ operations: manifest.summary.metadataOperationCount,+ })}\n`);+ return;+ }++ if (!args.output) throw new Error('--output is required');+ const manifest = buildManifest({+ contract,+ approvalReceipt,+ reconciliation,+ planBytes,+ contractBytes,+ reconciliationBytes,+ context,+ publishCheckpoint,+ now,+ maxReconciliationAgeMs,+ });+ if (manifest.publishCheckpoint && !args['publish-checkpoint']) {+ throw new Error(+ '--publish-checkpoint is required when the manifest contains a publish operation',+ );+ }+ if (args['publish-checkpoint'] && manifest.publishCheckpoint) {+ atomicWriteJson(path.resolve(args['publish-checkpoint']), manifest.publishCheckpoint);+ }+ atomicWriteJson(path.resolve(args.output), manifest);+ process.stdout.write(`${JSON.stringify({+ status: 'ok',+ mode: 'build',+ output: path.resolve(args.output),+ executable: manifest.executable,+ operations: manifest.summary.metadataOperationCount,+ publishPending: Boolean(manifest.publishCheckpoint),+ unresolved: manifest.summary.unresolvedCount,+ unverified: manifest.summary.unverifiedCount,+ conflicts: manifest.summary.conflictCount,+ deferred: manifest.summary.deferredCount,+ })}\n`);+ } catch (error) {+ process.stderr.write(`${error.message}\n\n${usage()}\n`);+ process.exitCode = 1;+ }+}++if (require.main === module) main();++module.exports = {+ APPROVAL_RECEIPT_SCHEMA_VERSION,+ CONTRACT_SCHEMA_VERSION,+ DEFAULT_MAX_RECONCILIATION_AGE_MS,+ MANIFEST_SCHEMA_VERSION,+ PHASE_ORDER,+ atomicWriteJson,+ bindContractToPlan,+ buildManifest,+ contractApprovalContent,+ createPublishCheckpoint,+ declaredServiceRequiredTableNames,+ normalizeColumnType,+ normalizedContract,+ parseArgs,+ reconciliationScope,+ rollForwardPublishCheckpoint,+ sha256,+ stableJson,+ validateContract,+ validateApprovalReceipt,+ validateManifest,+ validatePublishCheckpoint,+};diff --git a/plugins/mobile-apps/scripts/check-routes.js b/plugins/mobile-apps/scripts/check-routes.jsindex fe817bbea..6aecc0842 100644--- a/plugins/mobile-apps/scripts/check-routes.js+++ b/plugins/mobile-apps/scripts/check-routes.js@@ -67,7 +67,7 @@ function findTsxFiles(dir) {// app/(app)/inspections/index.tsx → /inspectionsfunction fileToRoute(filePath, appRoot) {- const rel = path.relative(appRoot, filePath);+ const rel = path.relative(appRoot, filePath).replace(/\\/g, '/');const noExt = rel.replace(/\.tsx$/, '');if (/(^|\/)_layout$/.test(noExt)) return null; // layouts aren't screensif (/(^|\/)\+not-found$/.test(noExt)) return null; // not-found boundary@@ -243,9 +243,31 @@ function main() {}const files = findTsxFiles(appRoot);+ const screenFiles = files.filter(file => path.basename(file) !== '_layout.tsx');+ const fileFolderCollisionFindings = [];+ for (const file of screenFiles) {+ const relative = path.relative(appRoot, file).replace(/\\/g, '/');+ const base = relative.replace(/\.tsx$/, '');+ const children = screenFiles.filter((other) => {+ const otherRelative = path.relative(appRoot, other).replace(/\\/g, '/');+ return otherRelative.startsWith(`${base}/`);+ });+ const hasIndex = children.some(+ (child) => path.relative(appRoot, child).replace(/\\/g, '/') === `${base}/index.tsx`,+ );+ if (children.length > 0 && !hasIndex) {+ fileFolderCollisionFindings.push({+ route: fileToRoute(file, appRoot),+ file,+ childFiles: children,+ kind: 'file-folder-route-collision',+ });+ }+ }// Build dest registry: { route: { file, declaredKeys, declaredRaw } }const dests = {};+ const duplicateRouteFindings = [];// Collect senders: array of { fromFile, route, params }const allSenders = [];@@ -255,11 +277,20 @@ function main() {if (route) {const declared = parseLocalSearchParams(content);- dests[route] = {- file,- declaredKeys: declared ? declared.keys : null,- declaredRaw: declared ? declared.raw : null,- };+ if (dests[route]) {+ duplicateRouteFindings.push({+ route,+ file,+ otherFile: dests[route].file,+ kind: 'duplicate-route',+ });+ } else {+ dests[route] = {+ file,+ declaredKeys: declared ? declared.keys : null,+ declaredRaw: declared ? declared.raw : null,+ };+ }}const senders = parseSenders(content);@@ -289,11 +320,12 @@ function main() {}// Diff: for each dest, what's received but not declared?- const findings = [];+ const findings = [...fileFolderCollisionFindings, ...duplicateRouteFindings];for (const r of destRouteList) {const d = dests[r];const r2 = received[r];if (r2.sources.length === 0) continue; // unreachable destination — different bug class+ if (Object.keys(r2.params).length === 0) continue; // navigation without params needs no declarationif (!d.declaredKeys) {// Destination receives params but has NO useLocalSearchParams call.// That's a real issue if the screen uses any of those params.@@ -340,10 +372,24 @@ function main() {process.exit(0);}- console.error(`✗ check-routes: ${findings.length} destination(s) missing param declarations.\n`);+ console.error(`✗ check-routes: ${findings.length} route contract issue(s).\n`);for (const f of findings) {console.error(` Route: ${f.route}`);console.error(` File: ${path.relative(cwd, f.file)}`);+ if (f.kind === 'file-folder-route-collision') {+ console.error(` Issue: Route file conflicts with a same-name child folder.`);+ console.error(` Child: ${f.childFiles.map(child => path.relative(cwd, child)).join(', ')}`);+ console.error(` Fix: Move ${path.basename(f.file)} to ${path.basename(f.file, '.tsx')}/index.tsx.`);+ console.error('');+ continue;+ }+ if (f.kind === 'duplicate-route') {+ console.error(` Issue: Duplicate Expo route.`);+ console.error(` Other: ${path.relative(cwd, f.otherFile)}`);+ console.error(` Fix: If the route owns child screens, use <route>/index.tsx and remove the sibling <route>.tsx file.`);+ console.error('');+ continue;+ }if (f.kind === 'no-declaration') {console.error(` Issue: No useLocalSearchParams<>() call, but ${Object.keys(f.receivedParams).length} param(s) are sent here.`);} else {diff --git a/plugins/mobile-apps/scripts/create-calculated-column.js b/plugins/mobile-apps/scripts/create-calculated-column.jsindex a1c9f0a6c..48c31e6ed 100755--- a/plugins/mobile-apps/scripts/create-calculated-column.js+++ b/plugins/mobile-apps/scripts/create-calculated-column.js@@ -1,409 +1,59 @@#!/usr/bin/env node--// Creates a Dataverse calculated column on a parent table that resolves a value-// from a related entity via an N:1 dotted-path navigation chain.-//-// Companion to /add-dataverse Step 5c and /setup-datamodel Phase 5.-// See `shared/references/data-performance.md` § Cross-entity Reads for the-// runtime constraint that motivates this helper (the SDK has no $expand).-//-// Usage:-// node create-calculated-column.js <envUrl> \-// --table <primary_entity_logical_name> \-// --column <prefix>_<resolved_field>_calc \-// --type string|datetime|decimal|integer|boolean \-// --formula "<navigation>.<...>.<resolved_field>" \-// [--display "Display Name"] \-// [--solution <solution-unique-name>] \-// [--formula-xml '<full workflow xml>']-//-// Exit codes:-// 0 — created successfully-// 1 — bad args, auth failure, network failure, or HTTP 4xx/5xx from Dataverse-//-// Output (JSON to stdout, single line):-// Success: { "status": 204, "table": "...", "column": "...", "type": "..." }-// Failure: { "status": <code>, "table": "...", "column": "...", "error": "..." }--const { getAuthToken, makeRequest } = require('./lib/validation-helpers');--// ─── arg parsing ────────────────────────────────────────────────────────────--function parseArgs() {- const argv = process.argv.slice(2);- if (argv.length < 1 || argv[0].startsWith('--')) {- usage('envUrl is required as the first positional argument');- }-- const out = {- envUrl: argv[0].replace(/\/+$/, ''),- table: null,- column: null,- type: null,- formula: null,- formulaXml: null,- display: null,- solution: null,- };-- for (let i = 1; i < argv.length; i++) {- const flag = argv[i];- const next = argv[i + 1];- switch (flag) {- case '--table': out.table = next; i++; break;- case '--column': out.column = next; i++; break;- case '--type': out.type = (next || '').toLowerCase(); i++; break;- case '--formula': out.formula = next; i++; break;- case '--formula-xml': out.formulaXml = next; i++; break;- case '--display': out.display = next; i++; break;- case '--solution': out.solution = next; i++; break;- default:- usage(`Unknown flag: ${flag}`);- }- }-- if (!out.table) usage('--table is required');- if (!out.column) usage('--column is required');- if (!out.type) usage('--type is required (string|datetime|decimal|integer|boolean)');- if (!out.formula && !out.formulaXml) {- usage('--formula (dotted path) or --formula-xml (full workflow XML) is required');- }-- if (!/^[a-z0-9_]+$/.test(out.column)) {- usage(`--column must be lowercase alphanumeric + underscores: got "${out.column}"`);- }- if (!/^(string|datetime|decimal|integer|boolean)$/.test(out.type)) {- usage(`--type must be one of string|datetime|decimal|integer|boolean: got "${out.type}"`);- }-- // Default display name: strip _calc suffix, title-case the rest- if (!out.display) {- const base = out.column.replace(/^[a-z0-9]+_/, '').replace(/_calc$/i, '');- out.display = base- .split('_')- .filter(Boolean)- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))- .join(' ') || out.column;- }-- return out;-}--function usage(msg) {- process.stderr.write(`Error: ${msg}\n\n`);- process.stderr.write(- 'Usage:\n' +- ' node create-calculated-column.js <envUrl> \\\n' +- ' --table <table> --column <col> --type string|datetime|decimal|integer|boolean \\\n' +- ' --formula "<nav.path.field>" [--display "..."] [--solution <name>] [--formula-xml <xml>]\n'- );- process.exit(1);-}--// ─── payload construction ───────────────────────────────────────────────────--const TYPE_MAP = {- string: { odataType: 'Microsoft.Dynamics.CRM.StringAttributeMetadata', attrType: 'String', extra: { MaxLength: 200, FormatName: { Value: 'Text' } } },- datetime: { odataType: 'Microsoft.Dynamics.CRM.DateTimeAttributeMetadata', attrType: 'DateTime', extra: { Format: 'DateAndTime', DateTimeBehavior: { Value: 'UserLocal' } } },- decimal: { odataType: 'Microsoft.Dynamics.CRM.DecimalAttributeMetadata', attrType: 'Decimal', extra: { MinValue: -100000000000, MaxValue: 100000000000, Precision: 2 } },- integer: { odataType: 'Microsoft.Dynamics.CRM.IntegerAttributeMetadata', attrType: 'Integer', extra: { MinValue: -2147483648, MaxValue: 2147483647, Format: 'None' } },- boolean: { odataType: 'Microsoft.Dynamics.CRM.BooleanAttributeMetadata', attrType: 'Boolean', extra: {- DefaultValue: false,- OptionSet: {- TrueOption: { Value: 1, Label: { LocalizedLabels: [{ Label: 'Yes', LanguageCode: 1033 }] } },- FalseOption: { Value: 0, Label: { LocalizedLabels: [{ Label: 'No', LanguageCode: 1033 }] } },- },- } },-};--// Build the calculated-column payload. SourceType: 1 = Calculated.-function buildPayload({ column, type, display, formulaXml }) {- const t = TYPE_MAP[type];- if (!t) throw new Error(`unsupported type: ${type}`);-- // Schema name = column with the publisher prefix kept lowercase but the- // remainder PascalCase (Dataverse convention for calc columns).- const schemaName = toSchemaName(column);-+'use strict';++/**+ * Safety guard for legacy callers.+ *+ * Dataverse exposes FormulaDefinition in metadata, but Microsoft does not+ * support defining calculated, rollup, or formula expressions through code.+ * Legacy calculated columns require internal workflow XAML that has no public+ * authoring contract. Formula columns use a different serialized definition,+ * but that definition must also be created through the Power Apps editor.+ *+ * This helper therefore fails before authentication or mutation. Callers must+ * use a supported runtime read path, or require the formula column to be+ * created in Power Apps and then validate/reuse it as an existing dependency.+ */++const DOCUMENTATION_URL =+ 'https://learn.microsoft.com/power-apps/developer/data-platform/specialized-columns';++function parseArgs(argv) {+ const args = { environmentUrl: argv[2] || null };+ for (let index = 3; index < argv.length; index += 1) {+ const flag = argv[index];+ if (!flag.startsWith('--')) continue;+ const value = argv[index + 1];+ args[flag.slice(2)] = value && !value.startsWith('--') ? value : true;+ if (args[flag.slice(2)] !== true) index += 1;+ }+ return args;+}++function blockedResult(args) {return {- '@odata.type': t.odataType,- AttributeType: t.attrType,- AttributeTypeName: { Value: `${t.attrType}Type` },- SchemaName: schemaName,- LogicalName: column,- DisplayName: { LocalizedLabels: [{ Label: display, LanguageCode: 1033 }] },- Description: {- LocalizedLabels: [- { Label: 'Calculated read-only column auto-derived from screen plan (cross-entity read).', LanguageCode: 1033 },- ],- },- RequiredLevel: { Value: 'None' },- SourceType: 1,- SourceTypeMask: 1,- FormulaDefinition: formulaXml,- IsValidForCreate: false,- IsValidForUpdate: false,- ...t.extra,+ status: 'BLOCKED',+ code: 'UNSUPPORTED_FORMULA_DEFINITION_API',+ table: args.table || null,+ column: args.column || null,+ error:+ 'Dataverse does not support defining calculated, rollup, or formula expressions through code. '+ + 'Create the computed column in the Power Apps editor, then rerun reconciliation to validate '+ + 'and reuse it, or use a supported formatted-lookup/chained-fetch runtime read path.',+ documentation: DOCUMENTATION_URL,};}-// Dataverse schema-name convention for calc columns: keep the publisher prefix-// lowercase, PascalCase the remainder, drop any trailing _calc → _calc kept as-is.-function toSchemaName(logical) {- const m = logical.match(/^([a-z0-9]+)_(.+)$/);- if (!m) return logical;- const [, prefix, rest] = m;- const parts = rest.split('_');- const pascal = parts- .map((p, idx) => (idx === parts.length - 1 && p === 'calc' ? 'calc' : p.charAt(0).toUpperCase() + p.slice(1)))- .join('');- return `${prefix}_${pascal}`;+function main() {+ const result = blockedResult(parseArgs(process.argv));+ process.stdout.write(`${JSON.stringify(result)}\n`);+ process.exitCode = 2;}-// ─── formula → workflow XML ─────────────────────────────────────────────────-//-// Dataverse calculated-column formulas are stored as workflow-style XML, NOT as-// a plain dotted-path string. v0 of this helper supports the most common shape:-// an N:1 navigation chain that ends in a primitive read.-//-// For complex formulas (conditionals, arithmetic, string concat), the caller-// MUST pass the full workflow XML via --formula-xml and skip the dotted-path-// translation.-//-// Reference: the canonical workflow XML produced by the maker portal for a-// simple lookup-field calc column. We emit a minimal-but-valid variant.--function dottedPathToWorkflowXml({ table, column, formula, type }) {- const t = TYPE_MAP[type];- if (!t) throw new Error(`unsupported type for formula synthesis: ${type}`);- const segments = formula.split('.').map((s) => s.trim()).filter(Boolean);- if (segments.length < 2) {- throw new Error(- `--formula must traverse at least one navigation hop. Got "${formula}". ` +- 'For a non-related field, use a regular (non-calc) column.'- );- }- // Last segment = target attribute; everything before = navigation chain.- const targetAttr = segments[segments.length - 1];- const navChain = segments.slice(0, -1);-- // Build the GetEntityProperty chain in reverse: innermost reads from the- // first hop's related entity, outermost wraps the final target attribute.- // Dataverse's calculated-column engine accepts a flat single-Read activity- // for an N-hop chain by referencing the dotted attribute name directly on- // the first navigation property — this is the "shortcut" form supported on- // modern envs. Older orgs may require a nested Read tree; we emit the flat- // form first and surface a 400 with a clear message if it's rejected.-- const dottedTail = navChain.length === 1- ? targetAttr- : `${navChain.slice(1).join('.')}.${targetAttr}`;-- // XML-escape attribute values- const xe = (s) => String(s).replace(/[<>&"']/g, (c) => ({- '<': '<', '>': '>', '&': '&', '"': '"', "'": ''',- }[c]));+if (require.main === module) main();- return [- '<?xml version="1.0" encoding="utf-16"?>',- '<Workflow ',- ' xmlns:mxsw="clr-namespace:Microsoft.Xrm.Sdk.Workflow;assembly=Microsoft.Xrm.Sdk.Workflow" ',- ' xmlns:s="http://schemas.microsoft.com/winfx/2006/xaml" ',- ' xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">',- ' <mxsw:GetEntityProperty.Target>',- ` <s:Reference>${xe(`${table}.${navChain[0]}`)}</s:Reference>`,- ' </mxsw:GetEntityProperty.Target>',- ` <mxsw:GetEntityProperty Attribute="${xe(dottedTail)}" EntityName="${xe(navChain[0])}" TargetType="${xe(t.attrType)}" />`,- ' <mxsw:SetEntityProperty.Target>',- ` <s:Reference>${xe(table)}</s:Reference>`,- ' </mxsw:SetEntityProperty.Target>',- ` <mxsw:SetEntityProperty Attribute="${xe(column)}" EntityName="${xe(table)}" TargetType="${xe(t.attrType)}" />`,- '</Workflow>',- ].join('\n');-}--// ─── HTTP ───────────────────────────────────────────────────────────────────--async function postAttribute({ envUrl, table, payload, token, solution }) {- const url = `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${encodeURIComponent(table)}')/Attributes`;- const headers = {- Authorization: `Bearer ${token}`,- Accept: 'application/json',- 'Content-Type': 'application/json',- };- if (solution) headers['MSCRM.SolutionUniqueName'] = solution;-- const res = await makeRequest({- url,- method: 'POST',- headers,- body: JSON.stringify(payload),- includeHeaders: true,- timeout: 30000,- });- return res;-}--// ─── main ───────────────────────────────────────────────────────────────────--async function main() {- const args = parseArgs();- let token = await getAuthToken(args.envUrl);- if (!token) {- process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');- process.exit(1);- }-- let formulaXml;- try {- formulaXml = args.formulaXml- ? args.formulaXml- : dottedPathToWorkflowXml({- table: args.table,- column: args.column,- formula: args.formula,- type: args.type,- });- } catch (e) {- console.log(JSON.stringify({- status: 0,- table: args.table,- column: args.column,- error: `formula synthesis failed: ${e.message}`,- }));- process.exit(1);- }-- const payload = buildPayload({- column: args.column,- type: args.type,- display: args.display,- formulaXml,- });-- // Up to 3 attempts on 401 (token refresh) or 429 (rate-limit backoff).- let lastRes = null;- for (let attempt = 0; attempt < 3; attempt++) {- const res = await postAttribute({- envUrl: args.envUrl,- table: args.table,- payload,- token,- solution: args.solution,- });- lastRes = res;-- if (res.error) {- // Network-level failure — retry once- if (attempt < 2) continue;- break;- }-- // Treat 2xx as success (POST to /Attributes returns 204 No Content normally)- if (res.statusCode >= 200 && res.statusCode < 300) {- console.log(JSON.stringify({- status: res.statusCode,- table: args.table,- column: args.column,- type: args.type,- display: args.display,- solution: args.solution || null,- }));- process.exit(0);- }-- // Token refresh on 401- if (res.statusCode === 401 && attempt < 2) {- const fresh = await getAuthToken(args.envUrl);- if (!fresh) break;- // mutate token via closure for next iteration- // (simpler than rewriting the loop body)- // eslint-disable-next-line no-func-assign, no-unused-vars- // re-assign by shadowing- // Note: token is const above; re-bind via a let variable here.- // Restart loop with fresh token.- // Using a small inline trampoline to keep the change minimal.- return retryWithFreshToken(args, fresh, formulaXml);- }-- // 429 backoff (15s)- if (res.statusCode === 429 && attempt < 2) {- await new Promise((r) => setTimeout(r, 15000));- continue;- }-- // Other 4xx/5xx — don't retry, surface error- break;- }-- // Failure path- let errMsg = lastRes?.error || `HTTP ${lastRes?.statusCode}`;- if (lastRes?.body) {- try {- const parsed = JSON.parse(lastRes.body);- const dvErr = parsed?.error?.message;- if (dvErr) errMsg = `${errMsg}: ${dvErr}`;- } catch {- errMsg = `${errMsg}: ${lastRes.body.slice(0, 500)}`;- }- }- console.log(JSON.stringify({- status: lastRes?.statusCode || 0,- table: args.table,- column: args.column,- error: errMsg,- }));- process.exit(1);-}--// Token-refresh trampoline — replays the POST once with a fresh token.-async function retryWithFreshToken(args, freshToken, formulaXml) {- const payload = buildPayload({- column: args.column,- type: args.type,- display: args.display,- formulaXml,- });- const res = await postAttribute({- envUrl: args.envUrl,- table: args.table,- payload,- token: freshToken,- solution: args.solution,- });-- if (res.statusCode >= 200 && res.statusCode < 300) {- console.log(JSON.stringify({- status: res.statusCode,- table: args.table,- column: args.column,- type: args.type,- display: args.display,- solution: args.solution || null,- }));- process.exit(0);- }-- let errMsg = res.error || `HTTP ${res.statusCode}`;- if (res.body) {- try {- const parsed = JSON.parse(res.body);- const dvErr = parsed?.error?.message;- if (dvErr) errMsg = `${errMsg}: ${dvErr}`;- } catch {- errMsg = `${errMsg}: ${res.body.slice(0, 500)}`;- }- }- console.log(JSON.stringify({- status: res.statusCode || 0,- table: args.table,- column: args.column,- error: errMsg,- }));- process.exit(1);-}--main().catch((e) => {- process.stderr.write(`Unhandled error: ${e.stack || e.message}\n`);- process.exit(1);-});+module.exports = {+ DOCUMENTATION_URL,+ blockedResult,+ parseArgs,+};diff --git a/plugins/mobile-apps/scripts/create-dataverse-snapshot.js b/plugins/mobile-apps/scripts/create-dataverse-snapshot.jsnew file mode 100644index 000000000..26f476370--- /dev/null+++ b/plugins/mobile-apps/scripts/create-dataverse-snapshot.js@@ -0,0 +1,1967 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { createDataverseRequestExecutor } = require('./dataverse-request');++const ENTITY_SELECT = [+ 'LogicalName',+ 'SchemaName',+ 'DisplayName',+ 'DisplayCollectionName',+ 'Description',+ 'EntitySetName',+ 'PrimaryIdAttribute',+ 'PrimaryNameAttribute',+ 'OwnershipType',+ 'HasActivities',+ 'HasNotes',+ 'IsAvailableOffline',+ 'ChangeTrackingEnabled',+ 'IsCustomEntity',+ 'IsManaged',+ 'IsCustomizable',+ 'CanCreateAttributes',+ 'CanBePrimaryEntityInRelationship',+ 'CanBeRelatedEntityInRelationship',+ 'CanBeInManyToMany',+].join(',');++const ATTRIBUTE_SELECT = [+ 'MetadataId',+ 'LogicalName',+ 'SchemaName',+ 'AttributeType',+ 'AttributeTypeName',+ 'RequiredLevel',+ 'IsCustomAttribute',+ 'IsManaged',+ 'IsCustomizable',+ 'IsPrimaryId',+ 'IsPrimaryName',+ 'IsValidForCreate',+ 'IsValidForRead',+ 'IsValidForUpdate',+ 'SourceType',+ 'AttributeOf',+ 'IsLogical',+].join(',');++const CHOICE_TYPE_BY_ATTRIBUTE = {+ Boolean: 'BooleanAttributeMetadata',+ Picklist: 'PicklistAttributeMetadata',+ State: 'StateAttributeMetadata',+ Status: 'StatusAttributeMetadata',+};++const FORMULA_TYPE_BY_ATTRIBUTE = {+ BigInt: 'BigIntAttributeMetadata',+ Boolean: 'BooleanAttributeMetadata',+ DateTime: 'DateTimeAttributeMetadata',+ Decimal: 'DecimalAttributeMetadata',+ Double: 'DoubleAttributeMetadata',+ Integer: 'IntegerAttributeMetadata',+ Money: 'MoneyAttributeMetadata',+ Picklist: 'PicklistAttributeMetadata',+ String: 'StringAttributeMetadata',+};++const ORDINARY_METADATA_FIELDS_BY_TYPE = {+ BigIntAttributeMetadata: ['MinValue', 'MaxValue'],+ BooleanAttributeMetadata: ['DefaultValue'],+ DateTimeAttributeMetadata: ['Format', 'DateTimeBehavior'],+ DecimalAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],+ DoubleAttributeMetadata: ['MinValue', 'MaxValue', 'Precision'],+ FileAttributeMetadata: ['MaxSizeInKB'],+ ImageAttributeMetadata: ['MaxHeight', 'MaxWidth', 'MaxSizeInKB'],+ IntegerAttributeMetadata: ['MinValue', 'MaxValue', 'Format'],+ MemoAttributeMetadata: ['MaxLength', 'Format'],+ MoneyAttributeMetadata: ['MinValue', 'MaxValue', 'Precision', 'PrecisionSource'],+ StringAttributeMetadata: ['MaxLength', 'Format', 'FormatName'],+};++const CONCEPT_ALIASES = {+ associate: ['systemuser'],+ associates: ['systemuser'],+ customer: ['contact', 'account'],+ customers: ['contact', 'account'],+ manager: ['systemuser'],+ managers: ['systemuser'],+ organization: ['account'],+ organizations: ['account'],+ people: ['contact'],+ person: ['contact'],+ store: ['stocklocation'],+ stores: ['stocklocation'],+ user: ['systemuser'],+ users: ['systemuser'],+};++const GENERIC_CONCEPT_TOKENS = new Set([+ 'and',+ 'data',+ 'record',+ 'records',+ 'report',+ 'reports',+ 'table',+ 'tables',+ 'workflow',+ 'workflows',+]);++const MAX_TABLES_PER_CONCEPT = 3;+const MAX_ADVISORY_DETAIL_TABLES = 40;+const MAX_EXACT_NAME_TABLES = 50;++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ const key = argv[index];+ if (!key.startsWith('--')) continue;+ const value = argv[index + 1];+ if (index + 1 < argv.length && !String(value).startsWith('--')) {+ args[key.slice(2)] = value;+ index += 1;+ } else {+ args[key.slice(2)] = true;+ }+ }+ return args;+}++function parseList(value) {+ return [...new Set(String(value || '')+ .split(',')+ .map((item) => item.trim())+ .filter(Boolean))];+}++function atomicWriteFile(file, content, fileSystem = fs) {+ fileSystem.mkdirSync(path.dirname(file), { recursive: true });+ const temporary = `${file}.tmp-${process.pid}-${Date.now()}`;+ try {+ fileSystem.writeFileSync(temporary, content, 'utf8');+ fileSystem.renameSync(temporary, file);+ } finally {+ if (fileSystem.existsSync(temporary)) fileSystem.rmSync(temporary, { force: true });+ }+}++function atomicWriteJson(file, value, fileSystem = fs) {+ atomicWriteFile(file, `${JSON.stringify(value, null, 2)}\n`, fileSystem);+}++function normalizeUrl(value) {+ return String(value || '').replace(/\/+$/, '').toLowerCase();+}++function odataString(value) {+ return String(value).replace(/'/g, "''");+}++function normalizeNextLink(nextLink) {+ const marker = '/api/data/v9.2/';+ const markerIndex = nextLink ? nextLink.indexOf(marker) : -1;+ return nextLink && markerIndex >= 0 ? nextLink.slice(markerIndex + marker.length) : nextLink;+}++async function requestCollection(request, apiPath, label, { optional = false } = {}) {+ const values = [];+ let next = apiPath;+ while (next) {+ const response = await request('GET', normalizeNextLink(next));+ if (response.status < 200 || response.status >= 300) {+ if (optional && [400, 404].includes(response.status)) return [];+ const detail = response.error || JSON.stringify(response.data || {}) || 'unknown error';+ const error = new Error(`${label} failed (${response.status}): ${detail}`);+ error.status = response.status;+ error.metadataError = detail;+ throw error;+ }+ values.push(...(response.data?.value || []));+ next = response.data?.['@odata.nextLink'] || null;+ }+ return values;+}++function logicalNameOf(entity) {+ return String(entity?.LogicalName || entity?.logicalName || '');+}++function uniqueLogicalNames(values) {+ const names = new Map();+ for (const value of values || []) {+ const logicalName = String(value || '').trim();+ if (!logicalName) continue;+ const key = logicalName.toLowerCase();+ if (!names.has(key)) names.set(key, logicalName);+ }+ return [...names.values()].sort((left, right) => left.localeCompare(right));+}++function mergeEntitiesByLogicalName(entities, additions) {+ const merged = new Map();+ for (const entity of [...(entities || []), ...(additions || [])]) {+ const logicalName = logicalNameOf(entity);+ if (!logicalName) continue;+ merged.set(logicalName.toLowerCase(), entity);+ }+ return [...merged.values()].sort(+ (left, right) => logicalNameOf(left).localeCompare(logicalNameOf(right)),+ );+}++async function resolveExactNameEntities(request, entities, requestedNames) {+ const requestedTables = uniqueLogicalNames(requestedNames);+ const existingNames = new Set(+ (entities || []).map((entity) => logicalNameOf(entity).toLowerCase()).filter(Boolean),+ );+ const queriedTables = requestedTables.filter(+ (logicalName) => !existingNames.has(logicalName.toLowerCase()),+ );+ if (queriedTables.length > MAX_EXACT_NAME_TABLES) {+ throw new Error(+ `Exact-name metadata query exceeds ${MAX_EXACT_NAME_TABLES} tables: `+ + queriedTables.join(', '),+ );+ }++ let discovered = [];+ if (queriedTables.length > 0) {+ const filter = queriedTables+ .map((logicalName) => `LogicalName eq '${odataString(logicalName)}'`)+ .join(' or ');+ const apiPath = `EntityDefinitions?$select=${ENTITY_SELECT}&$filter=${filter}&LabelLanguages=1033`;+ if (apiPath.length > 8000) {+ throw new Error('Exact-name metadata query exceeds the bounded URL budget');+ }+ const response = await request('GET', apiPath);+ if (response.status < 200 || response.status >= 300) {+ throw new Error(+ `Exact-name table metadata failed (${response.status}): `+ + `${response.error || JSON.stringify(response.data || {})}`,+ );+ }+ if (response.data?.['@odata.nextLink']) {+ throw new Error('Exact-name table metadata exceeded one bounded response page');+ }+ const requestedKeys = new Set(queriedTables.map((name) => name.toLowerCase()));+ discovered = (response.data?.value || []).filter(+ (entity) => requestedKeys.has(logicalNameOf(entity).toLowerCase()),+ );+ }++ const mergedEntities = mergeEntitiesByLogicalName(entities, discovered);+ const availableNames = new Map(+ mergedEntities.map((entity) => [logicalNameOf(entity).toLowerCase(), logicalNameOf(entity)]),+ );+ return {+ entities: mergedEntities,+ requestedTables,+ queriedTables,+ discoveredTables: uniqueLogicalNames(discovered.map(logicalNameOf)),+ availableTables: requestedTables+ .filter((logicalName) => availableNames.has(logicalName.toLowerCase()))+ .map((logicalName) => availableNames.get(logicalName.toLowerCase())),+ unavailableTables: requestedTables.filter(+ (logicalName) => !availableNames.has(logicalName.toLowerCase()),+ ),+ };+}++function labelText(label) {+ return label?.UserLocalizedLabel?.Label+ || label?.LocalizedLabels?.find((item) => item.LanguageCode === 1033)?.Label+ || label?.LocalizedLabels?.[0]?.Label+ || '';+}++function singularizeToken(token) {+ if (token.length > 4 && token.endsWith('ies')) return `${token.slice(0, -3)}y`;+ if (token === 'statuses') return 'status';+ if (token.length > 5 && /(ches|shes|xes|zes|sses)$/.test(token)) return token.slice(0, -2);+ if (token.length > 3 && token.endsWith('s') && !token.endsWith('ss')) return token.slice(0, -1);+ return token;+}++function normalizedTokens(value) {+ return String(value || '')+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean)+ .map(singularizeToken);+}++function compact(value) {+ return normalizedTokens(value).join('');+}++function entitySearchParts(entity) {+ return [+ entity.LogicalName,+ entity.SchemaName,+ entity.EntitySetName,+ labelText(entity.DisplayName),+ labelText(entity.DisplayCollectionName),+ labelText(entity.Description),+ ].filter(Boolean);+}++function publisherPrefix(logicalName) {+ const match = String(logicalName || '').toLowerCase().match(/^([a-z][a-z0-9]*)_/);+ return match?.[1] || '';+}++function isVersionedName(logicalName) {+ const value = String(logicalName || '')+ .toLowerCase()+ .replace(/^[a-z][a-z0-9]*_/, '');+ return /(?:^|_)(?:v\d+[a-z0-9]*|m\d+[a-z0-9]*|old|legacy|test|backup|copy)(?:_|$)/.test(value)+ || /v\d+[a-z0-9]*$/.test(value);+}++function conceptDescriptor(value) {+ const raw = String(value || '').trim().toLowerCase();+ const aliases = CONCEPT_ALIASES[raw] || [];+ const tokens = normalizedTokens(raw);+ const aliasTokens = aliases.flatMap(normalizedTokens);+ return {+ raw,+ compactValues: [...new Set([compact(raw), ...aliases.map(compact)].filter((item) => item.length >= 3))],+ matchTokens: [...new Set([...tokens, ...aliasTokens])]+ .filter((token) => token.length >= 3 && !GENERIC_CONCEPT_TOKENS.has(token)),+ };+}++function scoreEntityForConcept(entity, descriptor) {+ const parts = entitySearchParts(entity);+ const compactParts = parts.map(compact);+ const tokenSet = new Set(parts.flatMap(normalizedTokens));+ let score = 0;+ const reasons = [];++ for (const value of descriptor.compactValues) {+ if (compactParts.some((part) => part === value)) {+ score = Math.max(score, 1000);+ reasons.push(`exact:${value}`);+ } else if (compactParts.some((part) => part.endsWith(value))) {+ score = Math.max(score, 900);+ reasons.push(`suffix:${value}`);+ } else if (compactParts.some((part) => part.includes(value))) {+ score = Math.max(score, 750);+ reasons.push(`contains:${value}`);+ }+ }++ for (const token of descriptor.matchTokens) {+ if (tokenSet.has(token)) {+ score = Math.max(score, 500);+ reasons.push(`token:${token}`);+ } else if (compactParts.some((part) => part.includes(token))) {+ score = Math.max(score, 400);+ reasons.push(`partial-token:${token}`);+ }+ }++ if (score === 0) return { score: 0, reasons: [] };+ if (isVersionedName(entity.LogicalName)) {+ score -= 300;+ reasons.push('version-penalty');+ }+ score -= Math.min(String(entity.LogicalName || '').length, 100) / 100;+ return { score, reasons: [...new Set(reasons)] };+}++function compareCandidates(left, right, preferredFamily = null) {+ if (preferredFamily !== null) {+ const leftPreferred = left.publisherFamily === preferredFamily ? 1 : 0;+ const rightPreferred = right.publisherFamily === preferredFamily ? 1 : 0;+ if (leftPreferred !== rightPreferred) return rightPreferred - leftPreferred;+ }+ if (left.score !== right.score) return right.score - left.score;+ if (left.versioned !== right.versioned) return Number(left.versioned) - Number(right.versioned);+ const lengthDifference = left.logicalName.length - right.logicalName.length;+ if (lengthDifference !== 0) return lengthDifference;+ return left.logicalName.localeCompare(right.logicalName);+}++function rankCandidatesByConcept(entities, concepts) {+ const preliminary = concepts.map((concept) => {+ const descriptor = conceptDescriptor(concept);+ const candidates = entities+ .map((entity) => {+ const scored = scoreEntityForConcept(entity, descriptor);+ return {+ entity,+ logicalName: entity.LogicalName,+ publisherFamily: publisherPrefix(entity.LogicalName),+ versioned: isVersionedName(entity.LogicalName),+ score: scored.score,+ reasons: scored.reasons,+ };+ })+ .filter((candidate) => candidate.score > 0);+ return { concept, descriptor, candidates };+ });++ const familyCoverage = new Map();+ for (const entry of preliminary) {+ for (const family of new Set(entry.candidates.map((candidate) => candidate.publisherFamily))) {+ familyCoverage.set(family, (familyCoverage.get(family) || 0) + 1);+ }+ }++ return preliminary.map((entry) => {+ const familyFacts = new Map();+ for (const candidate of entry.candidates) {+ const facts = familyFacts.get(candidate.publisherFamily) || {+ family: candidate.publisherFamily,+ maxScore: Number.NEGATIVE_INFINITY,+ unversionedCount: 0,+ };+ facts.maxScore = Math.max(facts.maxScore, candidate.score);+ if (!candidate.versioned) facts.unversionedCount += 1;+ familyFacts.set(candidate.publisherFamily, facts);+ }+ const preferredFamily = [...familyFacts.values()]+ .sort((left, right) => {+ const scoreDifference = right.maxScore - left.maxScore;+ if (Math.abs(scoreDifference) > 10) return scoreDifference;+ return (familyCoverage.get(right.family) || 0) - (familyCoverage.get(left.family) || 0)+ || right.unversionedCount - left.unversionedCount+ || scoreDifference+ || left.family.length - right.family.length+ || left.family.localeCompare(right.family);+ })[0]?.family ?? '';+ const candidates = entry.candidates+ .sort((left, right) => compareCandidates(left, right, preferredFamily))+ .map((candidate, index) => ({+ rank: index + 1,+ logicalName: candidate.logicalName,+ displayName: labelText(candidate.entity.DisplayName),+ publisherFamily: candidate.publisherFamily,+ versioned: candidate.versioned,+ score: Number(candidate.score.toFixed(2)),+ reasons: candidate.reasons,+ }));+ return {+ concept: entry.concept,+ normalizedTokens: entry.descriptor.matchTokens,+ preferredPublisherFamily: preferredFamily,+ candidates,+ };+ });+}++function selectDetailedCandidates(entities, tableNames, concepts) {+ const explicitNames = new Set(tableNames.map((value) => value.toLowerCase()));+ const rankings = rankCandidatesByConcept(entities, concepts);+ const selectedReasons = new Map();+ const unresolvedConcepts = [];+ let exactCoveredConcepts = 0;++ for (const entity of entities) {+ if (!explicitNames.has(String(entity.LogicalName).toLowerCase())) continue;+ selectedReasons.set(entity.LogicalName, new Set(['explicit-table']));+ }++ for (const ranking of rankings) {+ if (ranking.candidates.length === 0) continue;+ const exactCoverage = ranking.candidates.find((candidate) => (+ explicitNames.has(candidate.logicalName.toLowerCase())+ && (+ candidate.rank === 1+ || candidate.reasons.some((reason) => (+ reason.startsWith('exact:')+ || reason.startsWith('suffix:')+ ))+ )+ ));+ if (exactCoverage) {+ selectedReasons.get(exactCoverage.logicalName)+ .add(`concept:${ranking.concept}:exact-covered`);+ exactCoveredConcepts += 1;+ continue;+ }++ const bestScore = ranking.candidates[0].score;+ const familyToken = ranking.normalizedTokens[0];+ let preferred = ranking.candidates.filter((candidate) => (+ candidate.publisherFamily === ranking.preferredPublisherFamily+ && !candidate.versioned+ && (+ candidate.score >= bestScore - 300+ || (familyToken && candidate.reasons.some((reason) => reason === `token:${familyToken}`))+ )+ ));+ if (preferred.length === 0) {+ preferred = ranking.candidates.filter((candidate) => !candidate.versioned);+ }+ if (preferred.length === 0) preferred = ranking.candidates;+ unresolvedConcepts.push({+ concept: ranking.concept,+ candidates: preferred+ .filter((candidate) => !explicitNames.has(candidate.logicalName.toLowerCase()))+ .slice(0, MAX_TABLES_PER_CONCEPT),+ });+ }++ const advisoryCandidates = new Map();+ function selectAdvisory(candidate, concept) {+ const current = advisoryCandidates.get(candidate.logicalName) || {+ ...candidate,+ concepts: new Set(),+ };+ current.concepts.add(concept);+ advisoryCandidates.set(candidate.logicalName, current);+ }++ // Quality floor: every unresolved concept gets its best available candidate,+ // even when there are more than 40 distinct concepts.+ for (const entry of unresolvedConcepts) {+ if (entry.candidates[0]) selectAdvisory(entry.candidates[0], entry.concept);+ }+ const advisoryLimit = Math.max(+ MAX_ADVISORY_DETAIL_TABLES,+ advisoryCandidates.size,+ );+ const remainingCandidates = unresolvedConcepts+ .flatMap((entry) => entry.candidates.slice(1).map((candidate) => ({+ ...candidate,+ concept: entry.concept,+ })))+ .sort((left, right) => (+ right.score - left.score+ || left.rank - right.rank+ || left.concept.localeCompare(right.concept)+ || left.logicalName.localeCompare(right.logicalName)+ ));+ for (const candidate of remainingCandidates) {+ if (advisoryCandidates.has(candidate.logicalName)) {+ selectAdvisory(candidate, candidate.concept);+ continue;+ }+ if (advisoryCandidates.size >= advisoryLimit) break;+ selectAdvisory(candidate, candidate.concept);+ }+ for (const candidate of advisoryCandidates.values()) {+ const reasons = new Set([...candidate.concepts].map((concept) => `concept:${concept}`));+ selectedReasons.set(candidate.logicalName, reasons);+ }++ const entityByName = new Map(entities.map((entity) => [entity.LogicalName, entity]));+ const selectedEntities = [...selectedReasons.keys()]+ .sort((left, right) => left.localeCompare(right))+ .map((logicalName) => entityByName.get(logicalName))+ .filter(Boolean);+ const selectedNames = new Set(selectedEntities.map((entity) => entity.LogicalName));+ const candidateRanking = rankings.map((ranking) => ({+ ...ranking,+ candidates: ranking.candidates.map((candidate) => ({+ ...candidate,+ detailed: false,+ detailStatus: selectedNames.has(candidate.logicalName) ? 'pending' : 'inventory-only',+ detailFailure: null,+ selectionEvidence: [...(selectedReasons.get(candidate.logicalName) || [])],+ })),+ }));++ return {+ candidateRanking,+ selectedEntities,+ selectedEvidence: selectedEntities.map((entity) => ({+ logicalName: entity.LogicalName,+ reasons: [...selectedReasons.get(entity.LogicalName)].sort(),+ })),+ detailSelectionSummary: {+ requiredCandidates: selectedEntities.filter((entity) => (+ selectedReasons.get(entity.LogicalName).has('explicit-table')+ )).length,+ advisoryCandidates: advisoryCandidates.size,+ exactCoveredConcepts,+ unresolvedConcepts: unresolvedConcepts.length,+ advisoryLimit,+ },+ };+}++function normalizeDetailLoadFailure(entity, reasons, error) {+ const status = Number(error?.status);+ return {+ logicalName: entity.LogicalName,+ selectionReasons: [...reasons].sort(),+ status: Number.isInteger(status) && status >= 100 && status <= 599 ? status : null,+ error: String(error?.metadataError || error?.message || error || 'unknown error'),+ required: false,+ };+}++function applyDetailLoadOutcomes(candidateRanking, selectedEvidence, tables, failures) {+ const loadedNames = new Set(tables.map((table) => table.logicalName.toLowerCase()));+ const failureByName = new Map(+ failures.map((failure) => [failure.logicalName.toLowerCase(), failure]),+ );+ return {+ candidateRanking: candidateRanking.map((ranking) => ({+ ...ranking,+ candidates: ranking.candidates.map((candidate) => {+ const key = candidate.logicalName.toLowerCase();+ const failure = failureByName.get(key) || null;+ const detailed = loadedNames.has(key);+ return {+ ...candidate,+ detailed,+ detailStatus: detailed+ ? 'loaded'+ : failure+ ? 'unavailable'+ : candidate.selectionEvidence?.length+ ? 'pending'+ : 'inventory-only',+ detailFailure: failure,+ };+ }),+ })),+ selectedCandidateEvidence: selectedEvidence.map((item) => {+ const key = item.logicalName.toLowerCase();+ const failure = failureByName.get(key) || null;+ return {+ ...item,+ required: item.reasons.includes('explicit-table')+ || item.reasons.includes('explicit-expansion'),+ detailStatus: loadedNames.has(key) ? 'loaded' : failure ? 'unavailable' : 'pending',+ detailFailure: failure,+ };+ }),+ };+}++function selectDetailedEntities(entities, tableNames, concepts) {+ return selectDetailedCandidates(entities, tableNames, concepts).selectedEntities;+}++function normalizeChoiceOptions(metadata) {+ const optionSet = metadata.OptionSet || metadata.GlobalOptionSet;+ const options = optionSet?.Options || [+ optionSet?.FalseOption,+ optionSet?.TrueOption,+ ].filter(Boolean);+ return (options || []).map((option) => ({+ value: option.Value,+ label: labelText(option.Label),+ }));+}++function choiceMetadataType(attribute) {+ if (attribute.AttributeType === 'Virtual'+ && attribute.AttributeTypeName?.Value === 'MultiSelectPicklistType') {+ return 'MultiSelectPicklistAttributeMetadata';+ }+ return CHOICE_TYPE_BY_ATTRIBUTE[attribute.AttributeType] || null;+}++function ordinaryMetadataType(attribute) {+ const typeName = attribute.AttributeTypeName?.Value;+ if (typeName === 'FileType') return 'FileAttributeMetadata';+ if (typeName === 'ImageType') return 'ImageAttributeMetadata';+ const candidate = `${attribute.AttributeType || ''}AttributeMetadata`;+ return hasOwn(ORDINARY_METADATA_FIELDS_BY_TYPE, candidate) ? candidate : null;+}++function canonicalAttributeType(attributeType, attributeTypeName) {+ const type = String(attributeType || '');+ const typeName = typeof attributeTypeName === 'object'+ ? attributeTypeName?.Value+ : attributeTypeName;+ if (type === 'Virtual' && typeName === 'FileType') return 'File';+ if (type === 'Virtual' && typeName === 'ImageType') return 'Image';+ return type;+}++function hasOwn(object, key) {+ return Object.prototype.hasOwnProperty.call(object || {}, key);+}++function lowerCamel(value) {+ return `${value[0].toLowerCase()}${value.slice(1)}`;+}++function normalizeTypedConstraint(value) {+ return value && typeof value === 'object' && hasOwn(value, 'Value')+ ? value.Value+ : value;+}++function managedValue(value) {+ return typeof value === 'object' && value !== null && 'Value' in value+ ? Boolean(value.Value)+ : Boolean(value);+}++function normalizeIntegerMetadata(value) {+ if (value === null || value === undefined || value === '') return null;+ const normalized = Number(value);+ return Number.isInteger(normalized) ? normalized : null;+}++function relationshipCount(table) {+ return (table.manyToOneRelationships?.length || 0)+ + (table.oneToManyRelationships?.length || 0)+ + (table.manyToManyRelationships?.length || 0);+}++async function loadDetailedEntity(request, entity) {+ const logicalName = entity.LogicalName;+ const root = `EntityDefinitions(LogicalName='${odataString(logicalName)}')`;+ const attributes = await requestCollection(+ request,+ `${root}/Attributes?$select=${ATTRIBUTE_SELECT}`,+ `${logicalName} attributes`,+ );+ const manyToOneRelationships = await requestCollection(+ request,+ `${root}/ManyToOneRelationships?$select=SchemaName,ReferencingAttribute,ReferencedEntity,ReferencedAttribute,IsManaged,CascadeConfiguration`,+ `${logicalName} many-to-one relationships`,+ );+ const oneToManyRelationships = await requestCollection(+ request,+ `${root}/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute,ReferencedAttribute,IsManaged,CascadeConfiguration`,+ `${logicalName} one-to-many relationships`,+ );+ const manyToManyRelationships = await requestCollection(+ request,+ `${root}/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity1IntersectAttribute,Entity2LogicalName,Entity2IntersectAttribute,IntersectEntityName,IsManaged`,+ `${logicalName} many-to-many relationships`,+ );+ const keys = await requestCollection(+ request,+ `${root}/Keys?$select=LogicalName,SchemaName,KeyAttributes,EntityKeyIndexStatus,IsManaged`,+ `${logicalName} alternate keys`,+ );++ const choices = new Map();+ const choiceTypes = [...new Set(attributes+ .map(choiceMetadataType)+ .filter(Boolean))];+ for (const type of choiceTypes) {+ const metadata = await requestCollection(+ request,+ `${root}/Attributes/Microsoft.Dynamics.CRM.${type}?$select=LogicalName&$expand=OptionSet,GlobalOptionSet`,+ `${logicalName} ${type}`,+ );+ for (const item of metadata) {+ choices.set(item.LogicalName, {+ options: normalizeChoiceOptions(item),+ });+ }+ }++ const lookups = new Map();+ if (attributes.some((attribute) => attribute.AttributeType === 'Lookup')) {+ const lookupMetadata = await requestCollection(+ request,+ `${root}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`,+ `${logicalName} lookup metadata`,+ );+ for (const item of lookupMetadata) lookups.set(item.LogicalName, item.Targets || []);+ }++ const ordinaryConstraints = new Map();+ const ordinaryTypes = [...new Set(attributes.map(ordinaryMetadataType).filter(Boolean))];+ for (const type of ordinaryTypes) {+ const fields = ORDINARY_METADATA_FIELDS_BY_TYPE[type];+ const metadata = await requestCollection(+ request,+ `${root}/Attributes/Microsoft.Dynamics.CRM.${type}?$select=LogicalName,${fields.join(',')}`,+ `${logicalName} ${type} ordinary metadata`,+ );+ for (const item of metadata) {+ const constraints = {};+ for (const field of fields) {+ if (hasOwn(item, field)) {+ constraints[lowerCamel(field)] = normalizeTypedConstraint(item[field]);+ }+ }+ ordinaryConstraints.set(item.LogicalName, constraints);+ }+ }++ const computedMetadata = new Map();+ for (const attribute of attributes.filter(+ (item) => [1, 2, 3].includes(normalizeIntegerMetadata(item.SourceType)),+ )) {+ if (!attribute.MetadataId) {+ computedMetadata.set(attribute.LogicalName, {+ sourceType: normalizeIntegerMetadata(attribute.SourceType),+ sourceTypeMask: normalizeIntegerMetadata(attribute.SourceTypeMask),+ formulaDefinition: null,+ metadataStatus: 'unavailable',+ unavailableReason: 'MetadataId unavailable for typed computed metadata lookup',+ });+ continue;+ }+ const type = FORMULA_TYPE_BY_ATTRIBUTE[attribute.AttributeType];+ if (!type) {+ computedMetadata.set(attribute.LogicalName, {+ sourceType: normalizeIntegerMetadata(attribute.SourceType),+ sourceTypeMask: normalizeIntegerMetadata(attribute.SourceTypeMask),+ formulaDefinition: null,+ metadataStatus: 'unavailable',+ unavailableReason: `unsupported attribute type ${attribute.AttributeType || '<missing>'}`,+ });+ continue;+ }+ const response = await request(+ 'GET',+ `${root}/Attributes(${attribute.MetadataId})/Microsoft.Dynamics.CRM.${type}?$select=LogicalName,SourceType,SourceTypeMask,FormulaDefinition`,+ );+ if (response.status >= 200 && response.status < 300) {+ const hasFormulaDefinition = Object.prototype.hasOwnProperty.call(+ response.data || {},+ 'FormulaDefinition',+ );+ const sourceType = normalizeIntegerMetadata(+ response.data?.SourceType ?? attribute.SourceType,+ );+ const sourceTypeMask = normalizeIntegerMetadata(+ response.data?.SourceTypeMask ?? attribute.SourceTypeMask,+ );+ const baseSourceType = normalizeIntegerMetadata(attribute.SourceType);+ const compatible = sourceType !== null+ && sourceType === baseSourceType+ && sourceTypeMask !== null+ && hasFormulaDefinition+ && typeof response.data.FormulaDefinition === 'string'+ && response.data.FormulaDefinition.trim().length > 0+ && (sourceTypeMask & 32) === 0;+ computedMetadata.set(attribute.LogicalName, {+ sourceType,+ sourceTypeMask,+ formulaDefinition: hasFormulaDefinition ? response.data.FormulaDefinition : null,+ metadataStatus: compatible ? 'available' : 'unavailable',+ unavailableReason: compatible+ ? null+ : [+ sourceType === null ? 'SourceType unavailable or malformed' : null,+ sourceType !== null && sourceType !== baseSourceType+ ? `SourceType mismatch: base ${baseSourceType}, typed ${sourceType}`+ : null,+ sourceTypeMask === null ? 'SourceTypeMask unavailable or malformed' : null,+ sourceTypeMask !== null && (sourceTypeMask & 32) !== 0+ ? 'SourceTypeMask contains the Invalid bit'+ : null,+ !hasFormulaDefinition || typeof response.data.FormulaDefinition !== 'string'+ || response.data.FormulaDefinition.trim().length === 0+ ? 'FormulaDefinition unavailable'+ : null,+ ].filter(Boolean).join('; '),+ });+ } else if (response.status === 404) {+ computedMetadata.set(attribute.LogicalName, {+ sourceType: normalizeIntegerMetadata(attribute.SourceType),+ sourceTypeMask: normalizeIntegerMetadata(attribute.SourceTypeMask),+ formulaDefinition: null,+ metadataStatus: 'unavailable',+ unavailableReason: 'typed computed metadata endpoint returned 404',+ });+ } else {+ const detail = response.error || JSON.stringify(response.data || {}) || 'unknown error';+ const error = new Error(+ `${logicalName} ${attribute.LogicalName} computed metadata failed (${response.status}): `+ + detail,+ );+ error.status = response.status;+ error.metadataError = detail;+ throw error;+ }+ }++ const table = {+ logicalName,+ schemaName: entity.SchemaName,+ displayName: labelText(entity.DisplayName),+ displayCollectionName: labelText(entity.DisplayCollectionName),+ description: labelText(entity.Description),+ entitySetName: entity.EntitySetName,+ primaryIdAttribute: entity.PrimaryIdAttribute,+ primaryNameAttribute: entity.PrimaryNameAttribute,+ ownershipType: entity.OwnershipType ?? null,+ hasActivities: hasOwn(entity, 'HasActivities') ? Boolean(entity.HasActivities) : null,+ hasNotes: hasOwn(entity, 'HasNotes') ? Boolean(entity.HasNotes) : null,+ isAvailableOffline: hasOwn(entity, 'IsAvailableOffline')+ ? Boolean(entity.IsAvailableOffline)+ : null,+ changeTrackingEnabled: hasOwn(entity, 'ChangeTrackingEnabled')+ ? Boolean(entity.ChangeTrackingEnabled)+ : null,+ customEntity: Boolean(entity.IsCustomEntity),+ managed: Boolean(entity.IsManaged),+ customizable: managedValue(entity.IsCustomizable),+ canCreateAttributes: managedValue(entity.CanCreateAttributes),+ canBePrimaryEntityInRelationship: managedValue(+ entity.CanBePrimaryEntityInRelationship,+ ),+ canBeRelatedEntityInRelationship: managedValue(+ entity.CanBeRelatedEntityInRelationship,+ ),+ canBeInManyToMany: managedValue(entity.CanBeInManyToMany),+ columns: attributes.map((attribute) => {+ const computed = computedMetadata.get(attribute.LogicalName) || null;+ return {+ logicalName: attribute.LogicalName,+ schemaName: attribute.SchemaName,+ type: canonicalAttributeType(+ attribute.AttributeType,+ attribute.AttributeTypeName,+ ),+ typeName: attribute.AttributeTypeName?.Value || null,+ ...(ordinaryConstraints.get(attribute.LogicalName) || {}),+ requiredLevel: attribute.RequiredLevel?.Value || attribute.RequiredLevel || null,+ customAttribute: Boolean(attribute.IsCustomAttribute),+ managed: Boolean(attribute.IsManaged),+ customizable: managedValue(attribute.IsCustomizable),+ primaryId: Boolean(attribute.IsPrimaryId),+ primaryName: Boolean(attribute.IsPrimaryName),+ validForCreate: Boolean(attribute.IsValidForCreate),+ validForRead: Boolean(attribute.IsValidForRead),+ validForUpdate: Boolean(attribute.IsValidForUpdate),+ sourceType: normalizeIntegerMetadata(attribute.SourceType),+ sourceTypeMask: normalizeIntegerMetadata(attribute.SourceTypeMask),+ attributeOf: attribute.AttributeOf || null,+ logical: Boolean(attribute.IsLogical),+ lookupTargets: lookups.get(attribute.LogicalName) || [],+ choices: choices.get(attribute.LogicalName)?.options || [],+ formula: computed?.formulaDefinition || null,+ formulaDefinition: computed?.formulaDefinition || null,+ computed: computed+ ? {+ ...computed,+ formula: computed.formulaDefinition,+ attributeOf: attribute.AttributeOf || null,+ }+ : null,+ };+ }),+ manyToOneRelationships: manyToOneRelationships.map((relationship) => ({+ schemaName: relationship.SchemaName,+ lookupColumn: relationship.ReferencingAttribute,+ targetTable: relationship.ReferencedEntity,+ targetColumn: relationship.ReferencedAttribute,+ managed: Boolean(relationship.IsManaged),+ cascadeConfiguration: relationship.CascadeConfiguration+ ? { ...relationship.CascadeConfiguration }+ : null,+ })),+ oneToManyRelationships: oneToManyRelationships.map((relationship) => ({+ schemaName: relationship.SchemaName,+ childTable: relationship.ReferencingEntity,+ childLookupColumn: relationship.ReferencingAttribute,+ parentColumn: relationship.ReferencedAttribute,+ managed: Boolean(relationship.IsManaged),+ cascadeConfiguration: relationship.CascadeConfiguration+ ? { ...relationship.CascadeConfiguration }+ : null,+ })),+ manyToManyRelationships: manyToManyRelationships.map((relationship) => ({+ schemaName: relationship.SchemaName,+ entity1: relationship.Entity1LogicalName,+ entity1IntersectAttribute: relationship.Entity1IntersectAttribute,+ entity2: relationship.Entity2LogicalName,+ entity2IntersectAttribute: relationship.Entity2IntersectAttribute,+ intersectTable: relationship.IntersectEntityName,+ managed: Boolean(relationship.IsManaged),+ })),+ alternateKeys: keys.map((key) => ({+ logicalName: key.LogicalName,+ schemaName: key.SchemaName,+ columns: key.KeyAttributes || [],+ status: key.EntityKeyIndexStatus || null,+ managed: Boolean(key.IsManaged),+ })),+ };+ table.facts = {+ columnCount: table.columns.length,+ relationshipCount: relationshipCount(table),+ keyCount: table.alternateKeys.length,+ };+ return table;+}++function normalizeInventoryEntity(entity) {+ if (entity.logicalName) return { ...entity };+ return {+ logicalName: entity.LogicalName,+ schemaName: entity.SchemaName,+ displayName: labelText(entity.DisplayName),+ displayCollectionName: labelText(entity.DisplayCollectionName),+ description: labelText(entity.Description),+ entitySetName: entity.EntitySetName,+ primaryIdAttribute: entity.PrimaryIdAttribute,+ primaryNameAttribute: entity.PrimaryNameAttribute,+ ownershipType: entity.OwnershipType ?? null,+ hasActivities: hasOwn(entity, 'HasActivities') ? Boolean(entity.HasActivities) : null,+ hasNotes: hasOwn(entity, 'HasNotes') ? Boolean(entity.HasNotes) : null,+ isAvailableOffline: hasOwn(entity, 'IsAvailableOffline')+ ? Boolean(entity.IsAvailableOffline)+ : null,+ changeTrackingEnabled: hasOwn(entity, 'ChangeTrackingEnabled')+ ? Boolean(entity.ChangeTrackingEnabled)+ : null,+ customEntity: Boolean(entity.IsCustomEntity),+ managed: Boolean(entity.IsManaged),+ customizable: managedValue(entity.IsCustomizable),+ canCreateAttributes: managedValue(entity.CanCreateAttributes),+ canBePrimaryEntityInRelationship: managedValue(+ entity.CanBePrimaryEntityInRelationship,+ ),+ canBeRelatedEntityInRelationship: managedValue(+ entity.CanBeRelatedEntityInRelationship,+ ),+ canBeInManyToMany: managedValue(entity.CanBeInManyToMany),+ };+}++function analyzeProposedNames(entities, proposedTableNames) {+ const byLogicalName = new Map(+ entities.map((entity) => [+ String(entity.LogicalName || entity.logicalName).toLowerCase(),+ normalizeInventoryEntity(entity),+ ]),+ );+ const checked = [...new Set(proposedTableNames)]+ .sort((left, right) => left.localeCompare(right))+ .map((logicalName) => {+ const existing = byLogicalName.get(logicalName.toLowerCase()) || null;+ return {+ logicalName,+ status: existing ? 'collision' : 'missing',+ existing,+ };+ });+ return {+ checked,+ collisions: checked.filter((item) => item.status === 'collision'),+ missing: checked.filter((item) => item.status === 'missing').map((item) => item.logicalName),+ };+}++function validateSnapshot(snapshot, expected = {}) {+ const errors = [];+ const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);+ const requireStringArray = (value, label) => {+ if (!Array.isArray(value)+ || value.some((item) => typeof item !== 'string' || !item.trim())) {+ errors.push(`${label} must be a string array`);+ return false;+ }+ return true;+ };+ if (!snapshot || typeof snapshot !== 'object') errors.push('snapshot must be an object');+ if ((snapshot?.version || 0) < 3) errors.push('snapshot version must be 3 or newer');+ if (!snapshot?.environmentUrl) errors.push('environmentUrl is required');+ if (!snapshot?.tenantId) errors.push('tenantId is required');+ if (typeof snapshot?.generatedAt !== 'string'+ || !snapshot.generatedAt.trim()+ || Number.isNaN(Date.parse(snapshot.generatedAt))) {+ errors.push('generatedAt must be an ISO timestamp');+ }+ if (!Array.isArray(snapshot?.inventory)) errors.push('inventory must be an array');+ if (!Array.isArray(snapshot?.tables)) errors.push('tables must be an array');+ if (!Array.isArray(snapshot?.candidateRanking)) errors.push('candidateRanking must be an array');+ if (!isObject(snapshot?.inventoryFacts)) {+ errors.push('inventoryFacts must be an object');+ } else {+ for (const key of [+ 'customizableTables',+ 'exactNameTables',+ 'requiredExactNameTables',+ 'proposedCollisionTables',+ 'totalTables',+ ]) {+ if (!Number.isInteger(snapshot.inventoryFacts[key])+ || snapshot.inventoryFacts[key] < 0) {+ errors.push(`inventoryFacts.${key} must be a non-negative integer`);+ }+ }+ if (Number.isInteger(snapshot.inventoryFacts.totalTables)+ && Array.isArray(snapshot.inventory)+ && snapshot.inventoryFacts.totalTables !== snapshot.inventory.length) {+ errors.push('inventoryFacts.totalTables must equal inventory length');+ }+ }+ if (!isObject(snapshot?.proposedNameChecks)) {+ errors.push('proposedNameChecks must be an object');+ } else {+ const checkedValid = Array.isArray(snapshot.proposedNameChecks.checked);+ const collisionsValid = Array.isArray(snapshot.proposedNameChecks.collisions);+ const missingValid = requireStringArray(+ snapshot.proposedNameChecks.missing,+ 'proposedNameChecks.missing',+ );+ if (!checkedValid) errors.push('proposedNameChecks.checked must be an array');+ if (!collisionsValid) errors.push('proposedNameChecks.collisions must be an array');+ if (checkedValid) {+ const checkedNames = new Set();+ const collisionNames = new Set();+ const missingNames = new Set(+ missingValid+ ? snapshot.proposedNameChecks.missing.map((name) => name.toLowerCase())+ : [],+ );+ for (const [index, item] of snapshot.proposedNameChecks.checked.entries()) {+ if (!isObject(item)+ || typeof item.logicalName !== 'string'+ || !item.logicalName.trim()+ || !['collision', 'missing'].includes(item.status)) {+ errors.push(`proposedNameChecks.checked[${index}] is malformed`);+ continue;+ }+ const key = item.logicalName.toLowerCase();+ if (checkedNames.has(key)) {+ errors.push(`proposedNameChecks.checked[${index}].logicalName must be unique`);+ }+ checkedNames.add(key);+ if (item.status === 'collision') collisionNames.add(key);+ }+ if (collisionsValid) {+ const listedCollisionNames = new Set();+ for (const [index, item] of snapshot.proposedNameChecks.collisions.entries()) {+ if (!isObject(item)+ || typeof item.logicalName !== 'string'+ || !item.logicalName.trim()+ || item.status !== 'collision') {+ errors.push(`proposedNameChecks.collisions[${index}] is malformed`);+ continue;+ }+ listedCollisionNames.add(item.logicalName.toLowerCase());+ }+ if (listedCollisionNames.size !== collisionNames.size+ || [...collisionNames].some((name) => !listedCollisionNames.has(name))) {+ errors.push('proposedNameChecks.collisions must match checked collision entries');+ }+ }+ if (missingValid+ && (missingNames.size !== snapshot.proposedNameChecks.checked.filter(+ (item) => item?.status === 'missing',+ ).length+ || snapshot.proposedNameChecks.checked.some(+ (item) => item?.status === 'missing'+ && !missingNames.has(item.logicalName.toLowerCase()),+ ))) {+ errors.push('proposedNameChecks.missing must match checked missing entries');+ }+ }+ }+ if (!isObject(snapshot?.exactNameResolution)) {+ errors.push('exactNameResolution must be an object');+ } else {+ const requestedValid = requireStringArray(+ snapshot.exactNameResolution.requestedTables,+ 'exactNameResolution.requestedTables',+ );+ const loadedValid = requireStringArray(+ snapshot.exactNameResolution.loadedTables,+ 'exactNameResolution.loadedTables',+ );+ const unavailableValid = requireStringArray(+ snapshot.exactNameResolution.unavailableTables,+ 'exactNameResolution.unavailableTables',+ );+ if (requestedValid && loadedValid && unavailableValid) {+ const requested = new Set(+ snapshot.exactNameResolution.requestedTables.map((name) => name.toLowerCase()),+ );+ const resolved = [+ ...snapshot.exactNameResolution.loadedTables,+ ...snapshot.exactNameResolution.unavailableTables,+ ].map((name) => name.toLowerCase());+ if (new Set(resolved).size !== resolved.length+ || resolved.length !== requested.size+ || resolved.some((name) => !requested.has(name))) {+ errors.push('exactNameResolution loaded and unavailable tables must partition requestedTables');+ }+ }+ }+ if (!Array.isArray(snapshot?.detailLoadFailures)) {+ errors.push('detailLoadFailures must be an array');+ } else {+ const failureNames = new Set();+ for (const [index, failure] of snapshot.detailLoadFailures.entries()) {+ const prefix = `detailLoadFailures[${index}]`;+ if (!failure || typeof failure !== 'object' || Array.isArray(failure)) {+ errors.push(`${prefix} must be an object`);+ continue;+ }+ if (typeof failure.logicalName !== 'string' || !failure.logicalName.trim()) {+ errors.push(`${prefix}.logicalName must be a non-empty string`);+ } else {+ const key = failure.logicalName.toLowerCase();+ if (failureNames.has(key)) errors.push(`${prefix}.logicalName must be unique`);+ failureNames.add(key);+ }+ if (!Array.isArray(failure.selectionReasons)+ || failure.selectionReasons.length === 0+ || failure.selectionReasons.some(+ (reason) => typeof reason !== 'string' || !reason.trim(),+ )) {+ errors.push(`${prefix}.selectionReasons must be a non-empty string array`);+ }+ if (failure.status !== null+ && (!Number.isInteger(failure.status)+ || failure.status < 100+ || failure.status > 599)) {+ errors.push(`${prefix}.status must be null or an HTTP status integer`);+ }+ if (typeof failure.error !== 'string' || !failure.error.trim()) {+ errors.push(`${prefix}.error must be a non-empty string`);+ }+ if (failure.required !== false) {+ errors.push(`${prefix}.required must be false`);+ }+ if (failure.selectionReasons?.some(+ (reason) => reason === 'explicit-table' || reason === 'explicit-expansion',+ )) {+ errors.push(`${prefix}.selectionReasons must be advisory`);+ }+ }+ }+ if (snapshot?.detailLoadSummary === undefined) {+ errors.push('detailLoadSummary must be an object');+ } else {+ const summary = snapshot.detailLoadSummary;+ if (!summary || typeof summary !== 'object' || Array.isArray(summary)) {+ errors.push('detailLoadSummary must be an object');+ } else {+ for (const key of ['attemptedCandidates', 'loadedCandidates', 'failedCandidates']) {+ if (!Number.isInteger(summary[key]) || summary[key] < 0) {+ errors.push(`detailLoadSummary.${key} must be a non-negative integer`);+ }+ }+ if (Number.isInteger(summary.attemptedCandidates)+ && Number.isInteger(summary.loadedCandidates)+ && Number.isInteger(summary.failedCandidates)+ && summary.attemptedCandidates+ !== summary.loadedCandidates + summary.failedCandidates) {+ errors.push('detailLoadSummary attempted count must equal loaded plus failed');+ }+ if (Number.isInteger(summary.loadedCandidates)+ && Array.isArray(snapshot?.tables)+ && summary.loadedCandidates !== snapshot.tables.length) {+ errors.push('detailLoadSummary.loadedCandidates must equal tables length');+ }+ if (Number.isInteger(summary.failedCandidates)+ && Array.isArray(snapshot?.detailLoadFailures)+ && summary.failedCandidates !== snapshot.detailLoadFailures.length) {+ errors.push('detailLoadSummary.failedCandidates must equal detailLoadFailures length');+ }+ }+ }+ for (const key of [+ 'inventoryRetrievalMs',+ 'candidateSelectionMs',+ 'detailLoadingMs',+ 'totalDurationMs',+ ]) {+ if (!Number.isFinite(snapshot?.timings?.[key]) || snapshot.timings[key] < 0) {+ errors.push(`timings.${key} must be a non-negative number`);+ }+ }+ if (expected.environmentUrl+ && normalizeUrl(snapshot?.environmentUrl) !== normalizeUrl(expected.environmentUrl)) {+ errors.push('environmentUrl does not match');+ }+ if (expected.tenantId+ && String(snapshot?.tenantId).toLowerCase() !== String(expected.tenantId).toLowerCase()) {+ errors.push('tenantId does not match');+ }+ return { valid: errors.length === 0, errors };+}++async function createSnapshot({+ environmentUrl,+ tenantId,+ tableNames = [],+ proposedTableNames = [],+ concepts = [],+ request,+ nowMs = () => Date.now(),+ nowIso = () => new Date().toISOString(),+ onProgress = () => {},+}) {+ if (!environmentUrl) throw new Error('environmentUrl is required');+ if (typeof request !== 'function') throw new Error('request is required');++ const totalStartedAt = nowMs();+ const customizableEntities = await requestCollection(+ request,+ [+ 'EntityDefinitions?',+ `$select=${ENTITY_SELECT}`,+ '&$filter=IsCustomizable/Value eq true',+ '&LabelLanguages=1033',+ ].join(''),+ 'Customizable-table inventory',+ );+ const requiredNames = uniqueLogicalNames(tableNames);+ const proposedNames = uniqueLogicalNames(proposedTableNames);+ // Required exact-name discovery and proposed-name collision checks share one+ // bounded query, but only required names participate in detail loading.+ const allExactCheckNames = uniqueLogicalNames([...requiredNames, ...proposedNames]);+ const exactResolution = await resolveExactNameEntities(+ request,+ customizableEntities,+ allExactCheckNames,+ );+ const entities = exactResolution.entities;+ const availableEntityNames = new Set(+ entities.map((entity) => logicalNameOf(entity).toLowerCase()),+ );+ const requiredNameKeys = new Set(requiredNames.map((name) => name.toLowerCase()));+ const proposedNameKeys = new Set(proposedNames.map((name) => name.toLowerCase()));+ const requiredDiscoveredTables = exactResolution.discoveredTables.filter(+ (name) => requiredNameKeys.has(name.toLowerCase()),+ );+ const proposedCollisionTables = exactResolution.discoveredTables.filter(+ (name) => proposedNameKeys.has(name.toLowerCase())+ && !requiredNameKeys.has(name.toLowerCase()),+ );+ const requiredUnavailableTables = requiredNames.filter(+ (name) => !availableEntityNames.has(name.toLowerCase()),+ );+ const proposedNameChecks = analyzeProposedNames(entities, proposedNames);+ const inventoryCompletedAt = nowMs();+ onProgress({+ milestoneId: 'inventory-loaded',+ inventoryTables: entities.length,+ customizableInventoryTables: customizableEntities.length,+ exactNameTables: exactResolution.discoveredTables.length,+ requiredExactNameTables: requiredDiscoveredTables.length,+ requiredExactNameUnavailable: requiredUnavailableTables.length,+ exactNameUnavailable: requiredUnavailableTables.length,+ proposedNameCollisions: proposedNameChecks.collisions.length,+ proposedNameMissing: proposedNameChecks.missing.length,+ elapsedMs: inventoryCompletedAt - totalStartedAt,+ });++ const selection = selectDetailedCandidates(entities, requiredNames, concepts);+ const selectionCompletedAt = nowMs();+ onProgress({+ milestoneId: 'candidates-selected',+ concepts: concepts.length,+ attemptedDetailedCandidates: selection.selectedEntities.length,+ detailedCandidates: selection.selectedEntities.length,+ requiredDetailedCandidates: selection.detailSelectionSummary.requiredCandidates,+ advisoryDetailedCandidates: selection.detailSelectionSummary.advisoryCandidates,+ exactCoveredConcepts: selection.detailSelectionSummary.exactCoveredConcepts,+ unresolvedConcepts: selection.detailSelectionSummary.unresolvedConcepts,+ advisoryLimit: selection.detailSelectionSummary.advisoryLimit,+ proposedCollisions: proposedNameChecks.collisions.length,+ proposedMissing: proposedNameChecks.missing.length,+ elapsedMs: selectionCompletedAt - totalStartedAt,+ });++ const tables = [];+ const detailLoadFailures = [];+ const selectedEvidenceByName = new Map(+ selection.selectedEvidence.map((item) => [item.logicalName.toLowerCase(), item]),+ );+ const requiredNameSet = new Set(requiredNames.map((name) => name.toLowerCase()));+ for (const entity of selection.selectedEntities) {+ try {+ tables.push(await loadDetailedEntity(request, entity));+ } catch (error) {+ if (requiredNameSet.has(entity.LogicalName.toLowerCase())) throw error;+ const evidence = selectedEvidenceByName.get(entity.LogicalName.toLowerCase());+ detailLoadFailures.push(normalizeDetailLoadFailure(+ entity,+ evidence?.reasons || [],+ error,+ ));+ }+ }+ const detailCompletedAt = nowMs();+ onProgress({+ milestoneId: 'details-loaded',+ attemptedDetailedCandidates: selection.selectedEntities.length,+ loadedDetailedCandidates: tables.length,+ failedDetailedCandidates: detailLoadFailures.length,+ detailedTables: tables.length,+ columns: tables.reduce((total, table) => total + table.facts.columnCount, 0),+ relationships: tables.reduce((total, table) => total + table.facts.relationshipCount, 0),+ elapsedMs: detailCompletedAt - totalStartedAt,+ });+ const totalCompletedAt = nowMs();+ const detailedNames = new Map(+ tables.map((table) => [table.logicalName.toLowerCase(), table.logicalName]),+ );+ const detailOutcomes = applyDetailLoadOutcomes(+ selection.candidateRanking,+ selection.selectedEvidence,+ tables,+ detailLoadFailures,+ );++ return {+ version: 3,+ purpose: 'foreground-planning',+ environmentUrl: environmentUrl.replace(/\/+$/, ''),+ tenantId: tenantId || null,+ generatedAt: nowIso(),+ inputs: {+ concepts: [...concepts],+ explicitTableNames: [...tableNames],+ proposedTableNames: [...proposedTableNames],+ },+ inventory: entities+ .map(normalizeInventoryEntity)+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ inventoryFacts: {+ customizableTables: customizableEntities.length,+ exactNameTables: exactResolution.discoveredTables.length,+ requiredExactNameTables: requiredDiscoveredTables.length,+ proposedCollisionTables: proposedCollisionTables.length,+ totalTables: entities.length,+ },+ candidateRanking: detailOutcomes.candidateRanking,+ selectedCandidateEvidence: detailOutcomes.selectedCandidateEvidence,+ tables,+ detailLoadFailures,+ detailLoadSummary: {+ attemptedCandidates: selection.selectedEntities.length,+ loadedCandidates: tables.length,+ failedCandidates: detailLoadFailures.length,+ ...selection.detailSelectionSummary,+ },+ proposedNameChecks,+ missingProposedTables: proposedNameChecks.missing,+ exactNameResolution: {+ requestedTables: requiredNames,+ loadedTables: requiredNames+ .filter((logicalName) => detailedNames.has(logicalName.toLowerCase()))+ .map((logicalName) => detailedNames.get(logicalName.toLowerCase())),+ unavailableTables: requiredUnavailableTables,+ },+ timings: {+ inventoryRetrievalMs: inventoryCompletedAt - totalStartedAt,+ candidateSelectionMs: selectionCompletedAt - inventoryCompletedAt,+ detailLoadingMs: detailCompletedAt - selectionCompletedAt,+ totalDurationMs: totalCompletedAt - totalStartedAt,+ },+ };+}++async function createReconciliationSnapshot({+ environmentUrl,+ tenantId,+ tableNames = [],+ proposedTableNames = [],+ request,+ nowMs = () => Date.now(),+ nowIso = () => new Date().toISOString(),+ onProgress = () => {},+}) {+ if (!environmentUrl) throw new Error('environmentUrl is required');+ if (typeof request !== 'function') throw new Error('request is required');+ const requiredNames = uniqueLogicalNames(tableNames);+ const proposedNames = uniqueLogicalNames(proposedTableNames);+ if (requiredNames.length === 0) {+ throw new Error('fresh reconciliation requires at least one exact approved table');+ }++ const totalStartedAt = nowMs();+ const exactResolution = await resolveExactNameEntities(+ request,+ [],+ uniqueLogicalNames([...requiredNames, ...proposedNames]),+ );+ const inventoryCompletedAt = nowMs();+ const inventoryByName = new Map(exactResolution.entities.map(+ (entity) => [logicalNameOf(entity).toLowerCase(), entity],+ ));+ const unavailableTables = requiredNames.filter(+ (logicalName) => !inventoryByName.has(logicalName.toLowerCase()),+ );+ const entitiesToLoad = requiredNames+ .map((logicalName) => inventoryByName.get(logicalName.toLowerCase()))+ .filter(Boolean);+ const proposedNameChecks = analyzeProposedNames(+ exactResolution.entities,+ proposedNames,+ );+ onProgress({+ milestoneId: 'reconciliation-exact-names-loaded',+ requestedTables: requiredNames.length,+ existingTables: entitiesToLoad.length,+ unavailableTables: unavailableTables.length,+ proposedCollisions: proposedNameChecks.collisions.length,+ proposedMissing: proposedNameChecks.missing.length,+ elapsedMs: inventoryCompletedAt - totalStartedAt,+ });++ const tables = [];+ for (const entity of entitiesToLoad) {+ tables.push(await loadDetailedEntity(request, entity));+ }+ const detailCompletedAt = nowMs();+ onProgress({+ milestoneId: 'reconciliation-details-loaded',+ loadedTables: tables.length,+ columns: tables.reduce((total, table) => total + table.facts.columnCount, 0),+ relationships: tables.reduce((total, table) => total + table.facts.relationshipCount, 0),+ keys: tables.reduce((total, table) => total + table.facts.keyCount, 0),+ elapsedMs: detailCompletedAt - totalStartedAt,+ });+ const detailedByName = new Map(+ tables.map((table) => [table.logicalName.toLowerCase(), table.logicalName]),+ );+ const selectedCandidateEvidence = tables.map((table) => ({+ logicalName: table.logicalName,+ reasons: ['fresh-exact-reconciliation'],+ required: true,+ detailStatus: 'loaded',+ detailFailure: null,+ }));++ return {+ version: 3,+ purpose: 'execution-reconciliation',+ environmentUrl: environmentUrl.replace(/\/+$/, ''),+ tenantId: tenantId || null,+ generatedAt: nowIso(),+ inputs: {+ concepts: [],+ explicitTableNames: requiredNames,+ proposedTableNames: proposedNames,+ },+ inventory: exactResolution.entities+ .map(normalizeInventoryEntity)+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ inventoryFacts: {+ customizableTables: exactResolution.entities.filter(+ (entity) => managedValue(entity.IsCustomizable),+ ).length,+ exactNameTables: exactResolution.discoveredTables.length,+ requiredExactNameTables: entitiesToLoad.length,+ proposedCollisionTables: proposedNameChecks.collisions.length,+ totalTables: exactResolution.entities.length,+ },+ candidateRanking: [],+ selectedCandidateEvidence,+ tables,+ detailLoadFailures: [],+ detailLoadSummary: {+ attemptedCandidates: entitiesToLoad.length,+ loadedCandidates: tables.length,+ failedCandidates: 0,+ requiredCandidates: requiredNames.length,+ advisoryCandidates: 0,+ exactCoveredConcepts: 0,+ unresolvedConcepts: 0,+ advisoryLimit: 0,+ },+ proposedNameChecks,+ missingProposedTables: proposedNameChecks.missing,+ exactNameResolution: {+ requestedTables: requiredNames,+ loadedTables: requiredNames+ .filter((logicalName) => detailedByName.has(logicalName.toLowerCase()))+ .map((logicalName) => detailedByName.get(logicalName.toLowerCase())),+ unavailableTables,+ },+ timings: {+ inventoryRetrievalMs: inventoryCompletedAt - totalStartedAt,+ candidateSelectionMs: 0,+ detailLoadingMs: detailCompletedAt - inventoryCompletedAt,+ totalDurationMs: detailCompletedAt - totalStartedAt,+ },+ reconciliation: {+ boundedExactNames: true,+ fullInventoryRead: false,+ tables: requiredNames,+ proposedNames,+ },+ };+}++function inventoryEntityToRaw(entity) {+ return {+ LogicalName: entity.logicalName,+ SchemaName: entity.schemaName,+ DisplayName: { UserLocalizedLabel: { Label: entity.displayName || '' } },+ DisplayCollectionName: {+ UserLocalizedLabel: { Label: entity.displayCollectionName || '' },+ },+ Description: { UserLocalizedLabel: { Label: entity.description || '' } },+ EntitySetName: entity.entitySetName,+ PrimaryIdAttribute: entity.primaryIdAttribute,+ PrimaryNameAttribute: entity.primaryNameAttribute,+ OwnershipType: entity.ownershipType,+ HasActivities: entity.hasActivities,+ HasNotes: entity.hasNotes,+ IsAvailableOffline: entity.isAvailableOffline,+ ChangeTrackingEnabled: entity.changeTrackingEnabled,+ IsCustomEntity: entity.customEntity,+ IsManaged: entity.managed,+ IsCustomizable: { Value: entity.customizable },+ CanCreateAttributes: { Value: entity.canCreateAttributes },+ CanBePrimaryEntityInRelationship: {+ Value: entity.canBePrimaryEntityInRelationship,+ },+ CanBeRelatedEntityInRelationship: {+ Value: entity.canBeRelatedEntityInRelationship,+ },+ CanBeInManyToMany: { Value: entity.canBeInManyToMany },+ };+}++async function expandSnapshot({+ snapshot,+ tableNames = [],+ proposedTableNames = [],+ request,+ nowMs = () => Date.now(),+ nowIso = () => new Date().toISOString(),+ onProgress = () => {},+}) {+ const validation = validateSnapshot(snapshot);+ if (!validation.valid) {+ throw new Error(`Cannot expand invalid snapshot: ${validation.errors.join('; ')}`);+ }+ if (typeof request !== 'function') throw new Error('request is required');++ const totalStartedAt = nowMs();+ const requestedNames = uniqueLogicalNames(tableNames);+ const proposedNames = uniqueLogicalNames(proposedTableNames);+ const exactCheckNames = uniqueLogicalNames([...requestedNames, ...proposedNames]);+ const baseRawInventory = snapshot.inventory.map(inventoryEntityToRaw);+ const exactResolution = await resolveExactNameEntities(+ request,+ baseRawInventory,+ exactCheckNames,+ );+ const inventoryCompletedAt = nowMs();+ const rawInventory = exactResolution.entities;+ const inventoryByName = new Map(+ rawInventory.map((entity) => [logicalNameOf(entity).toLowerCase(), entity]),+ );+ const existingDetailed = new Map(+ snapshot.tables.map((table) => [table.logicalName.toLowerCase(), table]),+ );+ const entitiesToLoad = requestedNames+ .filter((logicalName) => !existingDetailed.has(logicalName.toLowerCase()))+ .map((logicalName) => inventoryByName.get(logicalName.toLowerCase()))+ .filter(Boolean)+ .map((entity) => (entity.logicalName ? inventoryEntityToRaw(entity) : entity));+ const unavailableRequestedTables = requestedNames+ .filter((logicalName) => !inventoryByName.has(logicalName.toLowerCase()));+ const allProposedNames = [...new Set([+ ...(snapshot.inputs?.proposedTableNames || []),+ ...proposedNames,+ ])];+ const proposedNameChecks = analyzeProposedNames(rawInventory, allProposedNames);+ const requestedNameKeys = new Set(requestedNames.map((name) => name.toLowerCase()));+ const proposedNameKeys = new Set(proposedNames.map((name) => name.toLowerCase()));+ const requiredDiscoveredTables = exactResolution.discoveredTables.filter(+ (name) => requestedNameKeys.has(name.toLowerCase()),+ );+ const proposedCollisionTables = exactResolution.discoveredTables.filter(+ (name) => proposedNameKeys.has(name.toLowerCase())+ && !requestedNameKeys.has(name.toLowerCase()),+ );+ const selectionCompletedAt = nowMs();+ onProgress({+ milestoneId: 'expansion-selected',+ requestedTables: requestedNames.length,+ exactNameQueries: exactResolution.queriedTables.length > 0 ? 1 : 0,+ requiredExactNameDiscovered: requiredDiscoveredTables.length,+ requiredExactNameUnavailable: unavailableRequestedTables.length,+ exactNameDiscovered: requiredDiscoveredTables.length,+ exactNameUnavailable: unavailableRequestedTables.length,+ proposedNameCollisions: proposedNameChecks.collisions.length,+ proposedNameMissing: proposedNameChecks.missing.length,+ attemptedDetailedCandidates: entitiesToLoad.length,+ tablesToLoad: entitiesToLoad.length,+ inventoryTables: rawInventory.length,+ elapsedMs: selectionCompletedAt - totalStartedAt,+ });++ const loadedTables = [];+ for (const entity of entitiesToLoad) loadedTables.push(await loadDetailedEntity(request, entity));+ const detailCompletedAt = nowMs();+ onProgress({+ milestoneId: 'expansion-loaded',+ attemptedDetailedCandidates: entitiesToLoad.length,+ loadedDetailedCandidates: loadedTables.length,+ failedDetailedCandidates: 0,+ newlyLoadedTables: loadedTables.length,+ elapsedMs: detailCompletedAt - totalStartedAt,+ });+ const totalCompletedAt = nowMs();++ const detailedNames = new Set([+ ...snapshot.tables.map((table) => table.logicalName),+ ...loadedTables.map((table) => table.logicalName),+ ].map((logicalName) => logicalName.toLowerCase()));+ const expandedEvidence = new Map((snapshot.selectedCandidateEvidence || []).map((item) => [+ item.logicalName.toLowerCase(),+ { logicalName: item.logicalName, reasons: new Set(item.reasons) },+ ]));+ for (const logicalName of requestedNames) {+ if (!detailedNames.has(logicalName.toLowerCase())) continue;+ const key = logicalName.toLowerCase();+ const evidence = expandedEvidence.get(key) || {+ logicalName,+ reasons: new Set(),+ };+ evidence.reasons.add('explicit-expansion');+ expandedEvidence.set(key, evidence);+ }+ const loadedRequestedTables = requestedNames+ .filter((logicalName) => detailedNames.has(logicalName.toLowerCase()));+ const previousExactNames = snapshot.inputs?.explicitTableNames+ || snapshot.exactNameResolution?.requestedTables+ || [];+ const allExactNames = uniqueLogicalNames([...previousExactNames, ...requestedNames]);+ const allExactAvailable = new Map(+ rawInventory.map((entity) => [logicalNameOf(entity).toLowerCase(), logicalNameOf(entity)]),+ );+ const allDetailedNames = new Map(+ [...snapshot.tables, ...loadedTables]+ .map((table) => [table.logicalName.toLowerCase(), table.logicalName]),+ );+ const remainingDetailLoadFailures = (snapshot.detailLoadFailures || []).filter(+ (failure) => !allDetailedNames.has(failure.logicalName.toLowerCase()),+ );+ const expandedSelectedEvidence = [...expandedEvidence.values()]+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName))+ .map((item) => ({+ logicalName: item.logicalName,+ reasons: [...item.reasons].sort(),+ }));+ const detailOutcomes = applyDetailLoadOutcomes(+ snapshot.candidateRanking,+ expandedSelectedEvidence,+ [...snapshot.tables, ...loadedTables],+ remainingDetailLoadFailures,+ );++ return {+ ...snapshot,+ generatedAt: nowIso(),+ inputs: {+ concepts: [...(snapshot.inputs?.concepts || [])],+ explicitTableNames: [...new Set([+ ...(snapshot.inputs?.explicitTableNames || []),+ ...requestedNames,+ ])],+ proposedTableNames: allProposedNames,+ },+ inventory: rawInventory+ .map(normalizeInventoryEntity)+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ inventoryFacts: {+ customizableTables: snapshot.inventoryFacts?.customizableTables+ ?? snapshot.inventory.filter((entity) => entity.customizable).length,+ exactNameTables: rawInventory.filter(+ (entity) => !baseRawInventory.some(+ (base) => logicalNameOf(base).toLowerCase() === logicalNameOf(entity).toLowerCase(),+ ),+ ).length + (snapshot.inventoryFacts?.exactNameTables || 0),+ requiredExactNameTables: requiredDiscoveredTables.length+ + (snapshot.inventoryFacts?.requiredExactNameTables || 0),+ proposedCollisionTables: proposedCollisionTables.length+ + (snapshot.inventoryFacts?.proposedCollisionTables || 0),+ totalTables: rawInventory.length,+ },+ candidateRanking: detailOutcomes.candidateRanking.map((ranking) => ({+ ...ranking,+ candidates: ranking.candidates.map((candidate) => {+ const evidence = expandedEvidence.get(candidate.logicalName.toLowerCase());+ return {+ ...candidate,+ selectionEvidence: evidence+ ? [...evidence.reasons].sort()+ : candidate.selectionEvidence || [],+ };+ }),+ })),+ selectedCandidateEvidence: detailOutcomes.selectedCandidateEvidence,+ tables: [...snapshot.tables, ...loadedTables]+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ detailLoadFailures: remainingDetailLoadFailures,+ detailLoadSummary: {+ attemptedCandidates: snapshot.tables.length+ + loadedTables.length+ + remainingDetailLoadFailures.length,+ loadedCandidates: snapshot.tables.length + loadedTables.length,+ failedCandidates: remainingDetailLoadFailures.length,+ requiredCandidates: allExactNames.length,+ advisoryCandidates: snapshot.detailLoadSummary?.advisoryCandidates || 0,+ exactCoveredConcepts: snapshot.detailLoadSummary?.exactCoveredConcepts || 0,+ unresolvedConcepts: snapshot.detailLoadSummary?.unresolvedConcepts || 0,+ advisoryLimit: snapshot.detailLoadSummary?.advisoryLimit+ || MAX_ADVISORY_DETAIL_TABLES,+ },+ proposedNameChecks,+ missingProposedTables: proposedNameChecks.missing,+ exactNameResolution: {+ requestedTables: allExactNames,+ loadedTables: allExactNames+ .filter((logicalName) => allDetailedNames.has(logicalName.toLowerCase()))+ .map((logicalName) => allDetailedNames.get(logicalName.toLowerCase())),+ unavailableTables: allExactNames.filter(+ (logicalName) => !allExactAvailable.has(logicalName.toLowerCase()),+ ),+ },+ timings: {+ inventoryRetrievalMs: inventoryCompletedAt - totalStartedAt,+ candidateSelectionMs: selectionCompletedAt - inventoryCompletedAt,+ detailLoadingMs: detailCompletedAt - selectionCompletedAt,+ totalDurationMs: totalCompletedAt - totalStartedAt,+ },+ expansion: {+ baseGeneratedAt: snapshot.generatedAt,+ inventoryReused: true,+ requestedTables: requestedNames,+ loadedTables: loadedRequestedTables,+ newlyLoadedTables: loadedTables.map((table) => table.logicalName),+ unavailableTables: unavailableRequestedTables,+ attemptedDetailedCandidates: entitiesToLoad.length,+ loadedDetailedCandidates: loadedTables.length,+ failedDetailedCandidates: 0,+ },+ };+}++function createCliRequest(args, createExecutor = createDataverseRequestExecutor) {+ return createExecutor({+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'],+ solution: args.solution || null,+ });+}++async function main() {+ const args = parseArgs(process.argv);+ if (!args['env-url'] || !args['tenant-id'] || !args.output) {+ process.stderr.write(+ 'Usage: node create-dataverse-snapshot.js --env-url <url> --tenant-id <id> --output <json> '+ + '[--tables <logical-name,...>] [--proposed-tables <logical-name,...>] '+ + '[--concepts <domain-term,...>] [--solution <unique-name>] '+ + '[--base-snapshot <existing-json>] [--reconcile-exact]\n',+ );+ process.exit(1);+ }+ const progress = (event) => {+ process.stderr.write(`DATAVERSE_SNAPSHOT_PROGRESS ${JSON.stringify(event)}\n`);+ };+ const request = createCliRequest(args);+ const baseSnapshot = args['base-snapshot']+ ? JSON.parse(fs.readFileSync(path.resolve(args['base-snapshot']), 'utf8'))+ : null;+ if (baseSnapshot && args['reconcile-exact']) {+ throw new Error('--base-snapshot and --reconcile-exact are mutually exclusive');+ }+ if (baseSnapshot) {+ const validation = validateSnapshot(baseSnapshot, {+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'],+ });+ if (!validation.valid) {+ throw new Error(`Base snapshot mismatch: ${validation.errors.join('; ')}`);+ }+ }+ const snapshot = args['reconcile-exact']+ ? await createReconciliationSnapshot({+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'],+ tableNames: parseList(args.tables),+ proposedTableNames: parseList(args['proposed-tables']),+ request,+ onProgress: progress,+ })+ : baseSnapshot+ ? await expandSnapshot({+ snapshot: baseSnapshot,+ tableNames: parseList(args.tables),+ proposedTableNames: parseList(args['proposed-tables']),+ request,+ onProgress: progress,+ })+ : await createSnapshot({+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'],+ tableNames: parseList(args.tables),+ proposedTableNames: parseList(args['proposed-tables']),+ concepts: parseList(args.concepts),+ request,+ onProgress: progress,+ });+ const output = path.resolve(args.output);+ atomicWriteJson(output, snapshot);+ console.log(JSON.stringify({+ status: 'DONE',+ output,+ inventoryTables: snapshot.inventory.length,+ rankedConcepts: snapshot.candidateRanking.length,+ detailedTables: snapshot.tables.length,+ detailedCandidates: {+ attempted: snapshot.detailLoadSummary?.attemptedCandidates || 0,+ loaded: snapshot.detailLoadSummary?.loadedCandidates || 0,+ failed: snapshot.detailLoadSummary?.failedCandidates || 0,+ required: snapshot.detailLoadSummary?.requiredCandidates || 0,+ advisory: snapshot.detailLoadSummary?.advisoryCandidates || 0,+ exactCoveredConcepts: snapshot.detailLoadSummary?.exactCoveredConcepts || 0,+ advisoryLimit: snapshot.detailLoadSummary?.advisoryLimit+ || MAX_ADVISORY_DETAIL_TABLES,+ },+ proposedCollisions: snapshot.proposedNameChecks.collisions.length,+ proposedMissing: snapshot.proposedNameChecks.missing.length,+ exactNameResolution: snapshot.exactNameResolution,+ expansion: snapshot.expansion || null,+ timings: snapshot.timings,+ }, null, 2));+}++if (require.main === module) {+ main().catch((error) => {+ process.stderr.write(`${error.message}\n`);+ process.exit(1);+ });+}++module.exports = {+ analyzeProposedNames,+ atomicWriteFile,+ atomicWriteJson,+ canonicalAttributeType,+ compact,+ choiceMetadataType,+ conceptDescriptor,+ createCliRequest,+ createReconciliationSnapshot,+ createSnapshot,+ expandSnapshot,+ inventoryEntityToRaw,+ isVersionedName,+ labelText,+ loadDetailedEntity,+ normalizeNextLink,+ normalizeIntegerMetadata,+ normalizedTokens,+ odataString,+ parseArgs,+ parseList,+ publisherPrefix,+ rankCandidatesByConcept,+ relationshipCount,+ resolveExactNameEntities,+ requestCollection,+ selectDetailedCandidates,+ selectDetailedEntities,+ singularizeToken,+ validateSnapshot,+};diff --git a/plugins/mobile-apps/scripts/dataverse-request.js b/plugins/mobile-apps/scripts/dataverse-request.jsindex 55aea7603..f47fff22f 100644--- a/plugins/mobile-apps/scripts/dataverse-request.js+++ b/plugins/mobile-apps/scripts/dataverse-request.js@@ -5,7 +5,7 @@//// Arguments:// envUrl - Dataverse environment URL (e.g., https://org123.crm.dynamics.com)-// method - HTTP method: GET, POST, PATCH, DELETE — OR — BATCH-RECORDS (see below)+// method - HTTP method: GET, POST, PUT, PATCH, DELETE, BATCH-RECORDS, or BATCH-METADATA// apiPath - API path after /api/data/v9.2/ (e.g., "EntityDefinitions?$filter=...")// For BATCH-RECORDS mode, this is treated as a label (e.g. "Tier 0") for logging only.//@@ -13,9 +13,10 @@// --body <json> Request body as JSON string// --include-headers Include response headers in output (for OData-EntityId etc.)// --solution <name> Sets MSCRM.SolutionUniqueName header (target metadata at a solution)+// --tenant-id <id> Uses the resolved environment tenant without shell-global state//// BATCH-RECORDS mode (record-level inserts only — NEVER use for metadata writes):-// node dataverse-request.js <envUrl> BATCH-RECORDS <label> --operations '<json>' [--concurrency 5] [--solution <name>]+// node dataverse-request.js <envUrl> BATCH-RECORDS <label> --operations '<json>' [--concurrency 5] [--solution <name>] [--tenant-id <id>]//// --operations '<json>' Required. JSON array of operations:// [{ "index": 0, "entitySet": "cr3e9_jobsites", "body": { ... } }, ...]@@ -28,6 +29,19 @@// DO NOT USE FOR: EntityDefinitions / Attributes / RelationshipDefinitions POSTs — those serialize via the// metadata lock server-side; parallel calls return 429 / MetadataLockHeldException.//+// BATCH-METADATA mode (strictly sequential metadata operations in one process):+// node dataverse-request.js <envUrl> BATCH-METADATA <label> --operations '<json>' --tenant-id <id>+// [--journal <path> --manifest-hash <sha256> --reconciliation-hash <sha256>+// --manifest-file <validated-manifest.json>+// --manifest-operations '<complete-json-array>']+// [--continue-on-error]+//+// Operations:+// [{ "index": 0, "method": "POST", "apiPath": "EntityDefinitions", "body": { ... } }, ...]+//+// This is NOT an OData $batch and never runs writes concurrently. It reuses one+// token and Node process while preserving operation order and metadata-lock safety.+//// Output (JSON to stdout):// Success: { "status": 200, "data": { ... } }// With headers: { "status": 200, "data": { ... }, "headers": { ... } }@@ -37,14 +51,45 @@// 0 - Request completed (check status field for HTTP result)// 1 - Fatal error (no token, invalid args, network failure after retries)+const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');const { getAuthToken, makeRequest } = require('./lib/validation-helpers');+function retryAfterDelayMs(retryAfter, fallbackMs, nowMs = Date.now()) {+ const safeFallback = Number.isFinite(fallbackMs) && fallbackMs >= 0+ ? fallbackMs+ : 30000;+ if (retryAfter == null || String(retryAfter).trim() === '') return safeFallback;+ const normalized = String(retryAfter).trim();+ if (/^\d+(?:\.\d+)?$/.test(normalized)) {+ const delaySeconds = Number(normalized);+ return Number.isFinite(delaySeconds) && delaySeconds >= 0+ ? Math.ceil(delaySeconds * 1000)+ : safeFallback;+ }+ const retryAt = Date.parse(normalized);+ return Number.isFinite(retryAt)+ ? Math.max(0, retryAt - nowMs)+ : safeFallback;+}++function isMutationMethod(method) {+ return ['POST', 'PUT', 'PATCH', 'DELETE'].includes(String(method || '').toUpperCase());+}++function isMetadataApiPath(apiPath) {+ return /^(EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions|PublishXml)(?:\b|\(|\/|\?)/i+ .test(String(apiPath || ''));+}+function parseArgs() {const args = process.argv.slice(2);if (args.length < 3) {process.stderr.write(- 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>] [--include-headers] [--solution <uniqueName>]\n' +- ' node dataverse-request.js <envUrl> BATCH-RECORDS <label> --operations <json> [--concurrency 5] [--solution <name>]\n'+ 'Usage: node dataverse-request.js <envUrl> <method> <apiPath> [--body <json>] [--include-headers] [--solution <uniqueName>] [--tenant-id <id>]\n' ++ ' node dataverse-request.js <envUrl> BATCH-RECORDS <label> --operations <json> [--concurrency 5] [--solution <name>] [--tenant-id <id>]\n' ++ ' node dataverse-request.js <envUrl> BATCH-METADATA <label> --operations <json> [--solution <name>] [--tenant-id <id>] [--journal <path> --manifest-file <validated-manifest.json> --manifest-hash <sha256> --reconciliation-hash <sha256> --manifest-operations <complete-json-array>] [--continue-on-error]\n');process.exit(1);}@@ -57,6 +102,13 @@ function parseArgs() {let solution = null;let operations = null;let concurrency = 5;+ let tenantId = null;+ let continueOnError = false;+ let journal = null;+ let manifestHash = null;+ let reconciliationHash = null;+ let manifestOperations = null;+ let manifestFile = null;for (let i = 3; i < args.length; i++) {if (args[i] === '--body' && args[i + 1]) {@@ -70,10 +122,40 @@ function parseArgs() {} else if (args[i] === '--concurrency' && args[i + 1]) {const n = parseInt(args[++i], 10);if (Number.isFinite(n) && n >= 1 && n <= 20) concurrency = n;+ } else if (args[i] === '--tenant-id' && args[i + 1]) {+ tenantId = args[++i];+ } else if (args[i] === '--continue-on-error') {+ continueOnError = true;+ } else if (args[i] === '--journal' && args[i + 1]) {+ journal = args[++i];+ } else if (args[i] === '--manifest-hash' && args[i + 1]) {+ manifestHash = args[++i];+ } else if (args[i] === '--reconciliation-hash' && args[i + 1]) {+ reconciliationHash = args[++i];+ } else if (args[i] === '--manifest-operations' && args[i + 1]) {+ manifestOperations = args[++i];+ } else if (args[i] === '--manifest-file' && args[i + 1]) {+ manifestFile = args[++i];}}- return { envUrl, method, apiPath, body, includeHeaders, solution, operations, concurrency };+ return {+ envUrl,+ method,+ apiPath,+ body,+ includeHeaders,+ solution,+ operations,+ concurrency,+ tenantId,+ continueOnError,+ journal,+ manifestHash,+ reconciliationHash,+ manifestOperations,+ manifestFile,+ };}async function doRequest(envUrl, method, apiPath, body, token, includeHeaders, solution) {@@ -101,11 +183,78 @@ async function doRequest(envUrl, method, apiPath, body, token, includeHeaders, sreturn res;}+function createDataverseRequestExecutor({+ environmentUrl,+ tenantId,+ solution = null,+ getToken = getAuthToken,+ sendRequest = doRequest,+}) {+ const envUrl = String(environmentUrl || '').replace(/\/+$/, '');+ if (!envUrl) throw new Error('environmentUrl is required');++ let token = null;+ let tokenPromise = null;+ async function ensureToken() {+ if (token) return token;+ if (!tokenPromise) tokenPromise = Promise.resolve(getToken(envUrl, tenantId));+ token = await tokenPromise;+ tokenPromise = null;+ if (!token) {+ throw new Error('Failed to get Azure CLI token. Run `az login` first.');+ }+ return token;+ }++ return async (method, apiPath, body = null, includeHeaders = false) => {+ const requestToken = await ensureToken();+ let bodyString = null;+ if (body !== null && body !== undefined) {+ bodyString = typeof body === 'string' ? body : JSON.stringify(body);+ }+ const executed = await runOneMetadataOperation(+ envUrl,+ String(method || '').toUpperCase(),+ apiPath,+ bodyString,+ requestToken,+ includeHeaders,+ solution,+ tenantId,+ getToken,+ sendRequest,+ );+ token = executed.token;+ return {+ status: executed.status,+ data: executed.data,+ headers: executed.headers,+ error: executed.error,+ rateLimited: executed.rateLimited,+ };+ };+}+async function main() {- const { envUrl, method, apiPath, body, includeHeaders, solution, operations, concurrency } =- parseArgs();+ const {+ envUrl,+ method,+ apiPath,+ body,+ includeHeaders,+ solution,+ operations,+ concurrency,+ tenantId,+ continueOnError,+ journal,+ manifestHash,+ reconciliationHash,+ manifestOperations,+ manifestFile,+ } = parseArgs();- let token = await getAuthToken(envUrl);+ let token = await getAuthToken(envUrl, tenantId);if (!token) {process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');process.exit(1);@@ -130,17 +279,83 @@ async function main() {process.exit(1);}- const results = await runBatch(envUrl, ops, token, solution, concurrency);+ const results = await runBatch(envUrl, ops, token, solution, concurrency, tenantId);console.log(JSON.stringify({ status: 200, data: results }));return;}+ if (method === 'BATCH-METADATA') {+ if (!operations) {+ process.stderr.write('BATCH-METADATA requires --operations <json-array>\n');+ process.exit(1);+ }+ let ops;+ try {+ ops = JSON.parse(operations);+ } catch (e) {+ process.stderr.write(`--operations is not valid JSON: ${e.message}\n`);+ process.exit(1);+ }+ if (!Array.isArray(ops)) {+ process.stderr.write('--operations must be a JSON array\n');+ process.exit(1);+ }+ let allManifestOperations = ops;+ let manifest = null;+ if (manifestOperations) {+ try {+ allManifestOperations = JSON.parse(manifestOperations);+ } catch (error) {+ process.stderr.write(`--manifest-operations is not valid JSON: ${error.message}\n`);+ process.exit(1);+ }+ }+ if (!Array.isArray(allManifestOperations)) {+ process.stderr.write('--manifest-operations must be a JSON array\n');+ process.exit(1);+ }+ if (manifestFile) {+ try {+ manifest = JSON.parse(fs.readFileSync(path.resolve(manifestFile), 'utf8'));+ } catch (error) {+ process.stderr.write(`--manifest-file could not be read: ${error.message}\n`);+ process.exit(1);+ }+ }++ const result = await runMetadataBatch(+ envUrl,+ ops,+ token,+ solution,+ tenantId,+ continueOnError,+ {+ journalPath: journal,+ manifestHash,+ reconciliationHash,+ allOperations: allManifestOperations,+ manifest,+ },+ );+ console.log(JSON.stringify({ status: result.failed ? 207 : 200, data: result.results }));+ return;+ }+const maxRetries = 4;let wasRateLimited = false;for (let attempt = 0; attempt <= maxRetries; attempt++) {- const res = await doRequest(envUrl, method, apiPath, body, token, includeHeaders, solution);+ const res = await doRequest(envUrl, method, apiPath, body, token, true, solution);if (res.error) {+ if (isMutationMethod(method) && isMetadataApiPath(apiPath)) {+ console.log(JSON.stringify({+ status: 0,+ error: res.error,+ uncertain_metadata_mutation: true,+ }));+ return;+ }if (attempt < maxRetries) continue;process.stderr.write(`Request failed: ${res.error}\n`);process.exit(1);@@ -148,7 +363,7 @@ async function main() {// Retry on 401 with token refreshif (res.statusCode === 401 && attempt < maxRetries) {- token = await getAuthToken(envUrl);+ token = await getAuthToken(envUrl, tenantId);if (!token) {process.stderr.write('Token refresh failed. Run `az login` again.\n');process.exit(1);@@ -158,8 +373,7 @@ async function main() {// Retry on 429 — honour Retry-After header if present, else 30s backoffif (res.statusCode === 429 && attempt < maxRetries) {- const retryAfter = res.headers?.['retry-after'];- const delayMs = retryAfter ? parseInt(retryAfter, 10) * 1000 : 30000;+ const delayMs = retryAfterDelayMs(res.headers?.['retry-after'], 30000);process.stderr.write(`429 rate-limited — waiting ${delayMs / 1000}s before retry ${attempt + 1}/${maxRetries}\n`);wasRateLimited = true;await new Promise((r) => setTimeout(r, delayMs));@@ -182,30 +396,6 @@ async function main() {}}- // Idempotency rescue: a write request that hit 429 may have already been- // applied server-side before the rate-limit response was emitted. The retry- // then comes back as a 4xx "already exists" / duplicate. Treat that as- // success so callers don't see a spurious failure.- const isWrite = method === 'POST' || method === 'PUT' || method === 'PATCH';- if (- wasRateLimited &&- isWrite &&- res.statusCode >= 400 &&- res.statusCode < 500 &&- looksLikeDuplicate(data)- ) {- const output = {- status: 200,- data,- note: `Original ${method} likely succeeded before 429 retry; ignoring duplicate/already-exists response (HTTP ${res.statusCode}).`,- original_status: res.statusCode,- rate_limited_during_request: true,- };- if (includeHeaders && res.headers) output.headers = res.headers;- console.log(JSON.stringify(output));- return;- }-const output = { status: res.statusCode, data };if (includeHeaders && res.headers) {output.headers = res.headers;@@ -229,6 +419,9 @@ function looksLikeDuplicate(data) {const messageMatches = ['already exists','duplicate',+ 'not unique',+ 'same name exists',+ 'object with same name exists in solution','cannot insert duplicate key','an item with the same key has already been added','duplicaterecord',@@ -237,6 +430,8 @@ function looksLikeDuplicate(data) {const codeMatches = ['0x80040237', // DuplicateRecord'0x80060888', // SchemaName already in use+ '0x80044363', // schema name is not unique+ '0x80060890', // object with same name exists in solution'0x8004f00d', // duplicate attribute].some((needle) => code.includes(needle));@@ -248,7 +443,7 @@ function looksLikeDuplicate(data) {//// USE FOR: record inserts (no metadata lock). DO NOT USE FOR: metadata writes — they serialize via// the Dataverse metadata lock server-side and parallel calls return 429 / MetadataLockHeldException.-async function runBatch(envUrl, ops, token, solution, initialCap) {+async function runBatch(envUrl, ops, token, solution, initialCap, tenantId) {// Normalize input: every op gets a deterministic slot. Honour caller-supplied `index` if present// (so caller can correlate results to its own row identity), otherwise use position-in-array.const normalized = ops.map((op, i) => ({@@ -267,7 +462,7 @@ async function runBatch(envUrl, ops, token, solution, initialCap) {while (inflight < cap && nextIndex < normalized.length) {const op = normalized[nextIndex++];inflight++;- runOneOperation(envUrl, op, token, solution)+ runOneOperation(envUrl, op, token, solution, tenantId).then((result) => {results[op._slot] = { ...result, index: op.index };// Adaptive cap: drop to 3 on first 429 we see, to ease pressure@@ -299,7 +494,7 @@ async function runBatch(envUrl, ops, token, solution, initialCap) {// Runs a single record-create POST with full retry semantics (matches the single-op main() loop).// Returns { index, status, recordId?, error? }.-async function runOneOperation(envUrl, op, initialToken, solution) {+async function runOneOperation(envUrl, op, initialToken, solution, tenantId) {const { index, entitySet, body } = op;if (!entitySet || !body) {return { index, status: 0, error: 'Operation missing entitySet or body' };@@ -323,7 +518,7 @@ async function runOneOperation(envUrl, op, initialToken, solution) {}if (res.statusCode === 401 && attempt < maxRetries) {- const refreshed = await getAuthToken(envUrl);+ const refreshed = await getAuthToken(envUrl, tenantId);if (refreshed) {token = refreshed;continue;@@ -332,8 +527,7 @@ async function runOneOperation(envUrl, op, initialToken, solution) {}if (res.statusCode === 429 && attempt < maxRetries) {- const retryAfter = res.headers?.['retry-after'];- const delayMs = retryAfter ? parseInt(retryAfter, 10) * 1000 : 5000;+ const delayMs = retryAfterDelayMs(res.headers?.['retry-after'], 5000);await new Promise((r) => setTimeout(r, delayMs));continue;}@@ -369,6 +563,494 @@ async function runOneOperation(envUrl, op, initialToken, solution) {return { index, status: 0, error: 'Exhausted retries' };}+function stableJson(value) {+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;+ return `{${Object.keys(value).sort().map(+ (key) => `${JSON.stringify(key)}:${stableJson(value[key])}`,+ ).join(',')}}`;+}++function stableClone(value) {+ if (Array.isArray(value)) return value.map(stableClone);+ if (!value || typeof value !== 'object') return value;+ return Object.keys(value)+ .sort((left, right) => left.localeCompare(right))+ .reduce((result, key) => {+ result[key] = stableClone(value[key]);+ return result;+ }, {});+}++function manifestStableJson(value) {+ return `${JSON.stringify(stableClone(value), null, 2)}\n`;+}++function operationFingerprint(operation, defaultSolution = null) {+ return crypto.createHash('sha256').update(stableJson({+ id: operation.id || null,+ method: String(operation.method || '').toUpperCase(),+ apiPath: operation.apiPath,+ body: operation.body ?? null,+ solution: operation.solution || defaultSolution || null,+ })).digest('hex');+}++function validateJournalOperations(operations, defaultSolution = null) {+ if (!Array.isArray(operations)) {+ throw new Error('complete manifest operations must be an array');+ }+ const fingerprints = new Set();+ for (const [position, operation] of operations.entries()) {+ if (!Number.isInteger(operation?.index) || operation.index !== position) {+ throw new Error(+ 'complete manifest operation indexes must be unique and ordered from zero',+ );+ }+ const fingerprint = operationFingerprint(operation, defaultSolution);+ if (fingerprints.has(fingerprint)) {+ throw new Error(+ `complete manifest contains duplicate stable operation identity at index ${position}`,+ );+ }+ fingerprints.add(fingerprint);+ }+ return fingerprints;+}++function validateManifestExecutionBinding({+ manifest,+ manifestHash,+ selectedOperations,+ completeOperations,+ defaultSolution,+ environmentUrl,+ reconciliationHash,+ journal,+ checkPredecessors = true,+}) {+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {+ throw new Error('--manifest-file is required for journaled manifest execution');+ }+ const withoutIntegrity = { ...manifest };+ delete withoutIntegrity.integritySha256;+ const computedHash = crypto.createHash('sha256')+ .update(manifestStableJson(withoutIntegrity))+ .digest('hex');+ if (manifest.integritySha256 !== computedHash || manifestHash !== computedHash) {+ throw new Error('manifest execution binding hash does not match manifest content');+ }+ if (String(manifest.binding?.reconciliationSha256 || '') !== reconciliationHash+ || String(manifest.binding?.solutionUniqueName || '') !== String(defaultSolution || '')+ || String(manifest.binding?.environmentUrl || '').replace(/\/+$/, '').toLowerCase()+ !== String(environmentUrl || '').replace(/\/+$/, '').toLowerCase()) {+ throw new Error('manifest execution context binding does not match request context');+ }+ if (manifest.executable !== true+ || manifest.execution?.executor !== 'BATCH-METADATA'+ || manifest.execution?.parallelWrites !== false+ || manifest.execution?.odataBatch !== false) {+ throw new Error('manifest is not executable by sequential BATCH-METADATA');+ }+ const expectedPhases = [+ 'tableCreates',+ 'extensions',+ 'relationships',+ 'alternateKeys',+ 'publish',+ ];+ const phases = manifest.execution?.phases;+ if (!Array.isArray(phases)+ || phases.map((phase) => phase.name).join(',') !== expectedPhases.join(',')) {+ throw new Error('manifest execution phases are missing or out of order');+ }+ const flattened = phases.flatMap((phase) => (+ (phase.operations || []).map((operation) => {+ if (operation.phase !== phase.name) {+ throw new Error(`manifest operation ${operation.id} has an invalid phase binding`);+ }+ return operation;+ })+ ));+ validateJournalOperations(flattened, defaultSolution);+ if (stableJson(completeOperations) !== stableJson(flattened)) {+ throw new Error('--manifest-operations does not exactly match the bound manifest');+ }++ let selectedPhaseIndex = -1;+ for (const [phaseIndex, phase] of phases.entries()) {+ if (stableJson(selectedOperations) === stableJson(phase.operations || [])) {+ selectedPhaseIndex = phaseIndex;+ break;+ }+ }+ if (selectedOperations.length === 0 && flattened.length === 0) {+ selectedPhaseIndex = 0;+ }+ if (selectedPhaseIndex < 0) {+ throw new Error('selected operations are not an exact manifest phase');+ }+ if (checkPredecessors) {+ const predecessors = phases+ .slice(0, selectedPhaseIndex)+ .flatMap((phase) => phase.operations || []);+ for (const predecessor of predecessors) {+ const fingerprint = operationFingerprint(predecessor, defaultSolution);+ if (!journal?.completed?.[fingerprint]) {+ throw new Error(+ `manifest predecessor ${predecessor.id} is not journal-complete`,+ );+ }+ }+ }+ return { flattened, selectedPhaseIndex };+}++function atomicWriteJournal(journalPath, journal) {+ const resolved = path.resolve(journalPath);+ fs.mkdirSync(path.dirname(resolved), { recursive: true });+ const temporary = `${resolved}.tmp-${process.pid}-${Date.now()}`;+ try {+ fs.writeFileSync(temporary, `${stableJson(journal)}\n`, 'utf8');+ fs.renameSync(temporary, resolved);+ } finally {+ if (fs.existsSync(temporary)) fs.rmSync(temporary, { force: true });+ }+}++function prepareMetadataJournal({+ journalPath,+ environmentUrl,+ solution,+ manifestHash,+ reconciliationHash,+ operations,+}) {+ if (!journalPath) return { journal: null, recoveryResults: [] };+ if (!/^[a-f0-9]{64}$/i.test(String(manifestHash || ''))) {+ throw new Error('--manifest-hash must be a SHA-256 hex value when --journal is used');+ }+ if (!/^[a-f0-9]{64}$/i.test(String(reconciliationHash || ''))) {+ throw new Error(+ '--reconciliation-hash must be a SHA-256 hex value when --journal is used',+ );+ }+ const fingerprints = validateJournalOperations(operations, solution);+ const resolved = path.resolve(journalPath);+ const journal = fs.existsSync(resolved)+ ? JSON.parse(fs.readFileSync(resolved, 'utf8'))+ : {+ schemaVersion: 1,+ binding: {+ environmentUrl: String(environmentUrl).replace(/\/+$/, ''),+ solution: solution || null,+ },+ completed: {},+ recoveries: [],+ inFlight: null,+ };+ if (journal.schemaVersion !== 1+ || String(journal.binding?.environmentUrl || '').replace(/\/+$/, '').toLowerCase()+ !== String(environmentUrl).replace(/\/+$/, '').toLowerCase()+ || (journal.binding?.solution || null) !== (solution || null)+ || !journal.completed+ || typeof journal.completed !== 'object'+ || !Array.isArray(journal.recoveries)) {+ throw new Error('metadata journal is malformed or bound to different execution context');+ }++ const recoveryResults = [];+ if (journal.inFlight) {+ if (journal.inFlight.reconciliationHash === reconciliationHash+ || journal.inFlight.manifestHash === manifestHash) {+ throw new Error(+ 'UNCERTAIN_METADATA_OPERATION: fresh bounded reconciliation and regenerated '+ + 'manifest are required before resume',+ );+ }+ const stillRequired = fingerprints.has(journal.inFlight.fingerprint);+ if (journal.inFlight.failure?.collision === true && stillRequired) {+ throw new Error(+ 'COLLISION_REQUIRES_REGENERATED_OPERATIONS: revise the structured schema, '+ + 'regenerate aliases/services/all downstream phases, and do not resume the old array',+ );+ }+ const supersededCollision = journal.inFlight.failure?.collision === true+ && !stillRequired;+ const recovery = {+ operationId: journal.inFlight.operationId,+ fingerprint: journal.inFlight.fingerprint,+ priorManifestHash: journal.inFlight.manifestHash,+ priorReconciliationHash: journal.inFlight.reconciliationHash,+ manifestHash,+ reconciliationHash,+ outcome: stillRequired+ ? 'fresh-reconciliation-confirmed-still-required'+ : supersededCollision+ ? 'fresh-reconciliation-confirmed-superseded-collision'+ : 'fresh-reconciliation-confirmed-already-applied-or-superseded',+ reconciledAt: new Date().toISOString(),+ };+ journal.recoveries.push(recovery);+ if (!stillRequired && !supersededCollision) {+ journal.completed[journal.inFlight.fingerprint] = {+ operationId: journal.inFlight.operationId,+ outcome: recovery.outcome,+ completedAt: recovery.reconciledAt,+ manifestHash,+ reconciliationHash,+ };+ }+ if (!stillRequired) {+ recoveryResults.push({+ index: journal.inFlight.index,+ status: 200,+ operationId: journal.inFlight.operationId,+ journalStatus: recovery.outcome,+ });+ }+ journal.inFlight = null;+ atomicWriteJournal(resolved, journal);+ }+ return { journal, recoveryResults };+}++async function runMetadataBatch(+ envUrl,+ ops,+ initialToken,+ defaultSolution,+ tenantId,+ continueOnError,+ journalOptions = {},+) {+ let preparedJournal;+ try {+ if (journalOptions.journalPath) {+ validateManifestExecutionBinding({+ manifest: journalOptions.manifest,+ manifestHash: journalOptions.manifestHash,+ selectedOperations: ops,+ completeOperations: journalOptions.allOperations || ops,+ defaultSolution,+ environmentUrl: envUrl,+ reconciliationHash: journalOptions.reconciliationHash,+ journal: null,+ checkPredecessors: false,+ });+ }+ preparedJournal = prepareMetadataJournal({+ journalPath: journalOptions.journalPath,+ environmentUrl: envUrl,+ solution: defaultSolution,+ manifestHash: journalOptions.manifestHash,+ reconciliationHash: journalOptions.reconciliationHash,+ operations: journalOptions.allOperations || ops,+ });+ if (journalOptions.journalPath) {+ validateManifestExecutionBinding({+ manifest: journalOptions.manifest,+ manifestHash: journalOptions.manifestHash,+ selectedOperations: ops,+ completeOperations: journalOptions.allOperations || ops,+ defaultSolution,+ environmentUrl: envUrl,+ reconciliationHash: journalOptions.reconciliationHash,+ journal: preparedJournal.journal,+ });+ }+ } catch (error) {+ return {+ results: [{ index: -1, status: 0, error: error.message }],+ failed: true,+ };+ }+ const journal = preparedJournal.journal;+ const results = [...preparedJournal.recoveryResults];+ let token = initialToken;+ let failed = false;++ for (let slot = 0; slot < ops.length; slot++) {+ const op = ops[slot] || {};+ const index = typeof op.index === 'number' ? op.index : slot;+ const method = String(op.method || '').toUpperCase();+ const apiPath = op.apiPath;+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method) || !apiPath) {+ results.push({ index, status: 0, error: 'Operation requires a valid method and apiPath' });+ failed = true;+ if (!continueOnError) break;+ continue;+ }+ const fingerprint = operationFingerprint(op, defaultSolution);+ if (journal?.completed[fingerprint]) {+ results.push({+ index,+ status: 200,+ operationId: op.id || null,+ journalStatus: 'already-completed',+ });+ continue;+ }++ let body = null;+ if (op.body !== undefined && op.body !== null) {+ try {+ body = typeof op.body === 'string' ? op.body : JSON.stringify(op.body);+ } catch (error) {+ results.push({ index, status: 0, error: `Body serialize failed: ${error.message}` });+ failed = true;+ if (!continueOnError) break;+ continue;+ }+ }++ if (journal) {+ journal.inFlight = {+ index,+ operationId: op.id || null,+ fingerprint,+ manifestHash: journalOptions.manifestHash,+ reconciliationHash: journalOptions.reconciliationHash,+ startedAt: new Date().toISOString(),+ };+ atomicWriteJournal(journalOptions.journalPath, journal);+ }+ const started = Date.now();+ const executed = await runOneMetadataOperation(+ envUrl,+ method,+ apiPath,+ body,+ token,+ Boolean(op.includeHeaders),+ op.solution || defaultSolution,+ tenantId,+ );+ token = executed.token;+ const result = {+ index,+ status: executed.status,+ data: executed.data,+ durationMs: Date.now() - started,+ };+ if (executed.headers) result.headers = executed.headers;+ if (executed.error) result.error = executed.error;+ if (executed.rateLimited) result.rateLimited = true;+ if (executed.uncertain) result.uncertain = true;+ results.push(result);++ if (executed.status >= 200 && executed.status < 300) {+ if (journal) {+ journal.completed[fingerprint] = {+ operationId: op.id || null,+ status: executed.status,+ completedAt: new Date().toISOString(),+ manifestHash: journalOptions.manifestHash,+ reconciliationHash: journalOptions.reconciliationHash,+ };+ journal.inFlight = null;+ atomicWriteJournal(journalOptions.journalPath, journal);+ }+ } else {+ failed = true;+ if (journal) {+ if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {+ journal.inFlight = null;+ } else {+ journal.inFlight.failure = {+ status: executed.status,+ error: executed.error || null,+ uncertain: Boolean(executed.uncertain),+ collision: looksLikeDuplicate(executed.data)+ || looksLikeDuplicate({ error: { message: executed.error || '' } }),+ recordedAt: new Date().toISOString(),+ };+ }+ atomicWriteJournal(journalOptions.journalPath, journal);+ }+ if (!continueOnError || journal) break;+ }+ }++ return { results, failed };+}++async function runOneMetadataOperation(+ envUrl,+ method,+ apiPath,+ body,+ initialToken,+ includeHeaders,+ solution,+ tenantId,+ getToken = getAuthToken,+ sendRequest = doRequest,+) {+ let token = initialToken;+ let rateLimited = false;+ const maxRetries = 4;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ // Response headers are always needed internally for Retry-After handling.+ // The caller-facing result still honors includeHeaders below.+ const res = await sendRequest(envUrl, method, apiPath, body, token, true, solution);+ if (res.error) {+ if (isMutationMethod(method)) {+ return {+ status: 0,+ error: res.error,+ token,+ rateLimited,+ uncertain: true,+ };+ }+ if (attempt < maxRetries) continue;+ return { status: 0, error: res.error, token, rateLimited };+ }++ if (res.statusCode === 401 && attempt < maxRetries) {+ const refreshed = await getToken(envUrl, tenantId);+ if (!refreshed) {+ return { status: 401, error: 'Token refresh failed', token, rateLimited };+ }+ token = refreshed;+ continue;+ }++ if (res.statusCode === 429 && attempt < maxRetries) {+ const delayMs = retryAfterDelayMs(res.headers?.['retry-after'], 30000);+ rateLimited = true;+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ continue;+ }++ if ([500, 502, 503].includes(res.statusCode) && attempt < maxRetries) {+ await new Promise((resolve) => setTimeout(resolve, 5000));+ continue;+ }++ let data = null;+ if (res.body) {+ try {+ data = JSON.parse(res.body);+ } catch {+ data = res.body;+ }+ }++ return {+ status: res.statusCode,+ data,+ headers: includeHeaders ? res.headers : undefined,+ token,+ rateLimited,+ };+ }++ return { status: 0, error: 'Exhausted retries', token, rateLimited };+}+// Extract the GUID from an OData-EntityId header value, e.g.// "https://orgX.crm.dynamics.com/api/data/v9.2/cr3e9_jobsites(7da69e03-...-...)"// → "7da69e03-...-..."@@ -377,4 +1059,19 @@ function extractGuid(headerValue) {return m ? m[1] : null;}-main();+if (require.main === module) main();++module.exports = {+ createDataverseRequestExecutor,+ doRequest,+ extractGuid,+ looksLikeDuplicate,+ operationFingerprint,+ prepareMetadataJournal,+ retryAfterDelayMs,+ runBatch,+ runMetadataBatch,+ runOneMetadataOperation,+ validateManifestExecutionBinding,+ validateJournalOperations,+};diff --git a/plugins/mobile-apps/scripts/detect-publisher-prefix.js b/plugins/mobile-apps/scripts/detect-publisher-prefix.jsindex 3de21303a..d966bf5f7 100644--- a/plugins/mobile-apps/scripts/detect-publisher-prefix.js+++ b/plugins/mobile-apps/scripts/detect-publisher-prefix.js@@ -3,7 +3,7 @@* Detect the active publisher prefix for a Dataverse environment.** Usage:- * node scripts/detect-publisher-prefix.js <envUrl> [solutionName]+ * node scripts/detect-publisher-prefix.js <envUrl> [solutionName] [--tenant-id <id>]** solutionName defaults to "Default" (the built-in Default solution).*@@ -18,14 +18,18 @@ const { getAuthToken } = require('./lib/validation-helpers');async function main() {const envUrl = process.argv[2];- const solutionName = process.argv[3] || 'Default';+ const solutionName = process.argv[3] && !process.argv[3].startsWith('--')+ ? process.argv[3]+ : 'Default';+ const tenantFlagIndex = process.argv.indexOf('--tenant-id');+ const tenantId = tenantFlagIndex >= 0 ? process.argv[tenantFlagIndex + 1] : null;if (!envUrl) {console.log(JSON.stringify({ prefix: null, reason: 'envUrl arg missing' }));process.exit(0);}- const token = await getAuthToken(envUrl);+ const token = await getAuthToken(envUrl, tenantId);if (!token) {console.log(JSON.stringify({prefix: null,diff --git a/plugins/mobile-apps/scripts/lib/derived-metadata.js b/plugins/mobile-apps/scripts/lib/derived-metadata.jsnew file mode 100644index 000000000..1d51a384c--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/derived-metadata.js@@ -0,0 +1,186 @@+'use strict';++function normalizedSourceType(value) {+ return value === null || value === undefined ? 0 : Number(value);+}++function normalizeOptions(options) {+ return (options || [])+ .map((option) => ({+ value: Number(option.value ?? option.Value),+ label: String(option.label ?? option.Label ?? '').trim(),+ }))+ .sort((left, right) => left.value - right.value);+}++function validateOptions(options, label, requireBooleanPair = false) {+ if (!Array.isArray(options) || options.length === 0) {+ return [`${label} choice options must be a non-empty array`];+ }+ const normalized = normalizeOptions(options);+ const reasons = [];+ const values = new Set();+ for (const option of normalized) {+ if (!Number.isInteger(option.value)) {+ reasons.push(`${label} choice value must be a finite integer`);+ } else if (values.has(option.value)) {+ reasons.push(`${label} choice value ${option.value} is duplicated`);+ }+ values.add(option.value);+ if (!option.label) reasons.push(`${label} choice value ${option.value} has no label`);+ }+ if (requireBooleanPair && (normalized.length !== 2 || !values.has(0) || !values.has(1))) {+ reasons.push(`${label} Boolean options must define exactly values 0 and 1`);+ }+ return reasons;+}++function compareOptions(expectedOptions, actualOptions, requireBooleanPair = false) {+ const reasons = [];+ reasons.push(...validateOptions(expectedOptions, 'expected', requireBooleanPair));+ reasons.push(...validateOptions(actualOptions, 'live', requireBooleanPair));+ if (reasons.length > 0) return reasons;++ const normalizedExpected = normalizeOptions(expectedOptions);+ const actualByValue = new Map(normalizeOptions(actualOptions).map((option) => [option.value, option]));+ for (const expected of normalizedExpected) {+ const actual = actualByValue.get(expected.value);+ if (!actual) {+ reasons.push(`missing choice value ${expected.value}`);+ } else if (expected.label && actual.label !== expected.label) {+ reasons.push(+ `choice value ${expected.value} label mismatch: expected "${expected.label}", got "${actual.label}"`,+ );+ }+ }+ return reasons;+}++function compareDerivedColumn(expected, actual) {+ const reasons = [];+ for (const field of ['table', 'logicalName', 'kind', 'type', 'sourceType']) {+ if (!Object.prototype.hasOwnProperty.call(expected, field) || expected[field] === '') {+ reasons.push(`expected metadata ${field} is missing`);+ }+ }+ if (expected.kind === 'lookup' && !expected.lookupTarget) {+ reasons.push('expected lookupTarget is missing');+ }+ if (+ (expected.kind === 'choice' || expected.kind === 'boolean')+ && (!Array.isArray(expected.options) || expected.options.length === 0)+ ) {+ reasons.push('expected choice options must be a non-empty array');+ }+ if (expected.kind === 'computed' && !Object.prototype.hasOwnProperty.call(expected, 'sourceTypeMask')) {+ reasons.push('expected computed metadata sourceTypeMask is missing');+ }+ if (reasons.length > 0) return { compatible: false, reasons };+ if (!actual) return { compatible: false, reasons: ['column metadata missing'] };++ if (typeof actual.type !== 'string' || !actual.type) {+ reasons.push('live metadata type is missing or malformed');+ }+ if (!Object.prototype.hasOwnProperty.call(actual, 'sourceType')) {+ reasons.push('live metadata sourceType is missing');+ } else if (+ actual.sourceType !== null+ && actual.sourceType !== undefined+ && !Number.isFinite(Number(actual.sourceType))+ ) {+ reasons.push('live metadata sourceType is malformed');+ }+ if (expected.type && actual.type !== expected.type) {+ reasons.push(`type mismatch: expected ${expected.type}, got ${actual.type || '<missing>'}`);+ }++ const expectedSourceType = normalizedSourceType(expected.sourceType);+ const actualSourceType = normalizedSourceType(actual.sourceType);+ if (actualSourceType !== expectedSourceType) {+ reasons.push(`source type mismatch: expected ${expectedSourceType}, got ${actualSourceType}`);+ }++ if (expected.kind === 'lookup') {+ const targets = actual.lookupTargets;+ if (!Array.isArray(targets)) {+ reasons.push('live lookupTargets must be an array');+ return { compatible: false, reasons };+ }+ if (targets.length !== 1 || targets[0] !== expected.lookupTarget) {+ reasons.push(+ `lookup target mismatch: expected ${expected.lookupTarget || '<missing>'}, `+ + `got ${targets.join(', ') || '<none>'}`,+ );+ }+ }++ if (expected.kind === 'choice' || expected.kind === 'boolean') {+ if (!Array.isArray(actual.options)) {+ reasons.push('live choice options must be an array');+ } else {+ reasons.push(...compareOptions(expected.options, actual.options, expected.kind === 'boolean'));+ }+ }++ if (expected.kind === 'computed') {+ if (!Object.prototype.hasOwnProperty.call(actual, 'sourceTypeMask')) {+ reasons.push('live computed metadata sourceTypeMask is missing');+ } else if (!Number.isInteger(Number(actual.sourceTypeMask))) {+ reasons.push('live computed metadata sourceTypeMask is malformed');+ } else {+ const expectedMask = Number(expected.sourceTypeMask);+ const actualMask = Number(actual.sourceTypeMask);+ if (!Number.isInteger(expectedMask)) {+ reasons.push('expected computed metadata sourceTypeMask is malformed');+ } else if ((actualMask & 32) !== 0) {+ reasons.push('live computed metadata SourceTypeMask contains the Invalid bit');+ } else if (actualMask !== expectedMask) {+ reasons.push(`source type mask mismatch: expected ${expectedMask}, got ${actualMask}`);+ }+ }+ if (!expected.formulaDefinition) {+ reasons.push('expected computed metadata must include an exact FormulaDefinition');+ } else if (!actual.formulaDefinition) {+ reasons.push('live computed metadata did not return FormulaDefinition');+ } else if (actual.formulaDefinition.trim() !== expected.formulaDefinition.trim()) {+ reasons.push('FormulaDefinition mismatch');+ }+ }++ return { compatible: reasons.length === 0, reasons };+}++function compareDerivedMetadata(expectedColumns, actualColumns) {+ const actualByKey = new Map();+ const duplicateKeys = new Set();+ for (const column of actualColumns || []) {+ const key = `${column.table}:${column.logicalName}`;+ if (actualByKey.has(key)) duplicateKeys.add(key);+ actualByKey.set(key, column);+ }+ return (expectedColumns || []).map((expected) => {+ const key = `${expected.table}:${expected.logicalName}`;+ if (duplicateKeys.has(key)) {+ return {+ table: expected.table,+ logicalName: expected.logicalName,+ compatible: false,+ reasons: ['duplicate live metadata rows'],+ };+ }+ return {+ table: expected.table,+ logicalName: expected.logicalName,+ ...compareDerivedColumn(expected, actualByKey.get(key)),+ };+ });+}++module.exports = {+ compareDerivedColumn,+ compareDerivedMetadata,+ compareOptions,+ normalizeOptions,+ normalizedSourceType,+ validateOptions,+};diff --git a/plugins/mobile-apps/scripts/lib/validation-helpers.js b/plugins/mobile-apps/scripts/lib/validation-helpers.jsindex 905520936..fafb7f15d 100644--- a/plugins/mobile-apps/scripts/lib/validation-helpers.js+++ b/plugins/mobile-apps/scripts/lib/validation-helpers.js@@ -149,17 +149,37 @@ function getAzAccessToken(resourceUrl, tenantId = null) {* Gets an Azure CLI access token for the given resource URL.* Targets the env's tenant from Dataverse auth challenge when available.* Falls back to the active az tenant and then unqualified az token lookup.+ * @param {string} resourceUrl Dataverse resource URL to request a token for+ * @param {string|null} explicitTenantId Resolved environment tenant; skips tenant discovery when valid* @returns {Promise<string|null>} Access token, or null if unavailable*/-async function getAuthToken(resourceUrl) {- const tenantCandidates = [- process.env.POWER_PLATFORM_TENANT_ID,- process.env.DATAVERSE_TENANT_ID,- await getDataverseTenantFromChallenge(resourceUrl),- getAzAccountTenantId(),- ].filter(Boolean);+async function getAuthToken(resourceUrl, explicitTenantId = null) {+ // Candidates are produced LAZILY, in priority order. This used to be an array+ // literal, and an array literal evaluates every element before `.filter()`+ // runs — so each call paid for the WWW-Authenticate probe AND an+ // `az account show` spawn even when an env var already supplied the tenant.+ // `az account show` measured ~4.9s on a warm macOS box (it resolves the whole+ // subscription context, not just the tenant), and a single data-model run+ // issues dozens of Dataverse calls, so that dominated wall-clock time.+ // Short-circuiting preserves the exact preference order and fallback below —+ // it only skips work once a candidate has already minted a token.+ const candidateProducers = [+ () => explicitTenantId,+ () => process.env.POWER_PLATFORM_TENANT_ID,+ () => process.env.DATAVERSE_TENANT_ID,+ () => getDataverseTenantFromChallenge(resourceUrl),+ () => getAzAccountTenantId(),+ ];- for (const tenantId of [...new Set(tenantCandidates)]) {+ // Mirrors the previous `.filter(Boolean)` + `new Set(...)` de-duplication:+ // skip empty candidates, and never re-attempt a tenant an earlier producer+ // already tried (common when the env var and the az account agree).+ const attempted = new Set();+ for (const produce of candidateProducers) {+ // Producers are a mix of sync and async; `await` normalizes both.+ const tenantId = await produce();+ if (!tenantId || attempted.has(tenantId)) continue;+ attempted.add(tenantId);const token = getAzAccessToken(resourceUrl, tenantId);if (token) return token;}diff --git a/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.js b/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.jsnew file mode 100644index 000000000..b4d61c81e--- /dev/null+++ b/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.js@@ -0,0 +1,205 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { atomicWriteFile, parseArgs, relationshipCount, validateSnapshot } = require('./create-dataverse-snapshot');++function escapeCell(value) {+ return String(value ?? '')+ .replace(/\|/g, '\\|')+ .replace(/\r?\n/g, ' ');+}++function formatBoolean(value) {+ return value ? 'yes' : 'no';+}++function formatDuration(value) {+ return `${Number(value || 0).toFixed(0)} ms`;+}++function rankedCandidateText(ranking, limit = 5) {+ if (!ranking.candidates?.length) return 'No matching candidates';+ const rendered = ranking.candidates.slice(0, limit).map((candidate) => {+ const flags = [+ candidate.detailStatus === 'unavailable'+ ? 'detail unavailable'+ : candidate.detailed+ ? 'detailed'+ : 'inventory only',+ candidate.versioned ? 'versioned' : 'unversioned',+ candidate.reasons?.slice(0, 2).join(', '),+ ].filter(Boolean).join('; ');+ return `${candidate.rank}. \`${candidate.logicalName}\` (${candidate.score}; ${flags})`;+ });+ if (ranking.candidates.length > limit) {+ rendered.push(`+${ranking.candidates.length - limit} lower-ranked`);+ }+ return rendered.join('<br>');+}++function renderPlanningEvidence(snapshot) {+ const validation = validateSnapshot(snapshot);+ if (!validation.valid) {+ throw new Error(`Invalid Dataverse snapshot: ${validation.errors.join('; ')}`);+ }++ const lines = [+ '# Dataverse Planning Evidence',+ '',+ `- **Environment:** \`${snapshot.environmentUrl}\``,+ `- **Tenant:** \`${snapshot.tenantId}\``,+ `- **Generated:** ${snapshot.generatedAt}`,+ `- **Snapshot version:** ${snapshot.version}`,+ '',+ '## Required exact-name resolution',+ '',+ `- **Requested:** ${(snapshot.exactNameResolution?.requestedTables || []).map((name) => `\`${escapeCell(name)}\``).join(', ') || 'none'}`,+ `- **Loaded:** ${(snapshot.exactNameResolution?.loadedTables || []).map((name) => `\`${escapeCell(name)}\``).join(', ') || 'none'}`,+ `- **Unavailable:** ${(snapshot.exactNameResolution?.unavailableTables || []).map((name) => `\`${escapeCell(name)}\``).join(', ') || 'none'}`,+ '- Proposed logical names are reported separately as collision checks; they are not required existing tables.',+ '',+ '## Concept candidate ranking',+ '',+ '| Concept | Preferred publisher family | Ranked candidates |',+ '|---|---|---|',+ ];++ if (snapshot.candidateRanking.length === 0) {+ lines.push('| — | — | No concepts supplied |');+ } else {+ for (const ranking of snapshot.candidateRanking) {+ lines.push(+ `| ${escapeCell(ranking.concept)} | \`${escapeCell(ranking.preferredPublisherFamily || 'standard')}\` | ${rankedCandidateText(ranking)} |`,+ );+ }+ }++ lines.push(+ '',+ '## Skipped advisory detail failures',+ '',+ '| Logical name | Selection reasons | Status | Error |',+ '|---|---|---:|---|',+ );+ const detailLoadFailures = snapshot.detailLoadFailures || [];+ if (detailLoadFailures.length === 0) {+ lines.push('| — | — | — | None |');+ } else {+ for (const failure of detailLoadFailures) {+ lines.push(+ `| \`${escapeCell(failure.logicalName)}\` | `+ + `${escapeCell(failure.selectionReasons.join(', '))} | `+ + `${failure.status ?? 'n/a'} | ${escapeCell(failure.error)} |`,+ );+ }+ }++ lines.push(+ '',+ '## Detailed candidate facts',+ '',+ '| Logical name | Custom | Managed | Customizable | Columns | Relationships | Keys |',+ '|---|---:|---:|---:|---:|---:|---:|',+ );+ if (snapshot.tables.length === 0) {+ lines.push('| — | — | — | — | 0 | 0 | 0 |');+ } else {+ for (const table of [...snapshot.tables].sort(+ (left, right) => left.logicalName.localeCompare(right.logicalName),+ )) {+ lines.push(+ `| \`${escapeCell(table.logicalName)}\` | ${formatBoolean(table.customEntity)} | `+ + `${formatBoolean(table.managed)} | ${formatBoolean(table.customizable)} | `+ + `${table.facts?.columnCount ?? table.columns?.length ?? 0} | `+ + `${table.facts?.relationshipCount ?? relationshipCount(table)} | `+ + `${table.facts?.keyCount ?? table.alternateKeys?.length ?? 0} |`,+ );+ }+ }++ lines.push(+ '',+ '## Proposed logical-name checks',+ '',+ '| Proposed logical name | Result | Existing table facts |',+ '|---|---|---|',+ );+ const nameChecks = snapshot.proposedNameChecks?.checked || [];+ if (nameChecks.length === 0) {+ lines.push('| — | Not supplied | — |');+ } else {+ for (const item of nameChecks) {+ const facts = item.existing+ ? `custom=${formatBoolean(item.existing.customEntity)}, managed=${formatBoolean(item.existing.managed)}, customizable=${formatBoolean(item.existing.customizable)}`+ : 'No table returned by the bounded inventory/collision-check metadata reads';+ lines.push(`| \`${escapeCell(item.logicalName)}\` | **${item.status}** | ${facts} |`);+ }+ }++ lines.push(+ '',+ '## Snapshot timings',+ '',+ '| Phase | Duration |',+ '|---|---:|',+ `| Inventory retrieval | ${formatDuration(snapshot.timings.inventoryRetrievalMs)} |`,+ `| Candidate selection | ${formatDuration(snapshot.timings.candidateSelectionMs)} |`,+ `| Detail loading | ${formatDuration(snapshot.timings.detailLoadingMs)} |`,+ `| **Total** | **${formatDuration(snapshot.timings.totalDurationMs)}** |`,+ '',+ '> This appendix is deterministic metadata evidence. The data-model architect should reference it rather than restating raw inventory or column payloads.',+ '',+ );+ return lines.join('\n');+}++function readSnapshot(file, fileSystem = fs) {+ return JSON.parse(fileSystem.readFileSync(file, 'utf8'));+}++function main() {+ const args = parseArgs(process.argv);+ if (!args.snapshot || !args.output) {+ process.stderr.write(+ 'Usage: node render-dataverse-planning-evidence.js --snapshot <json> --output <markdown>\n',+ );+ process.exit(1);+ }+ const snapshotPath = path.resolve(args.snapshot);+ const outputPath = path.resolve(args.output);+ const snapshot = readSnapshot(snapshotPath);+ const markdown = renderPlanningEvidence(snapshot);+ atomicWriteFile(outputPath, markdown);+ console.log(JSON.stringify({+ status: 'DONE',+ output: outputPath,+ concepts: snapshot.candidateRanking.length,+ detailedTables: snapshot.tables.length,+ detailedCandidates: {+ attempted: snapshot.detailLoadSummary?.attemptedCandidates || 0,+ loaded: snapshot.detailLoadSummary?.loadedCandidates || 0,+ failed: snapshot.detailLoadSummary?.failedCandidates || 0,+ },+ proposedCollisions: snapshot.proposedNameChecks?.collisions?.length || 0,+ proposedMissing: snapshot.proposedNameChecks?.missing?.length || 0,+ }, null, 2));+}++if (require.main === module) {+ try {+ main();+ } catch (error) {+ process.stderr.write(`${error.message}\n`);+ process.exit(1);+ }+}++module.exports = {+ escapeCell,+ formatDuration,+ rankedCandidateText,+ readSnapshot,+ renderPlanningEvidence,+};diff --git a/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.jsnew file mode 100644index 000000000..480933b95--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js@@ -0,0 +1,143 @@+'use strict';++// Guards the tenant-resolution short-circuit in lib/validation-helpers.js.+//+// getAuthToken() used to build its candidate list as an array literal, which+// evaluates EVERY element before `.filter()` runs. That meant each Dataverse+// call spawned `az account show` (~4.9s measured on a warm macOS box) and probed+// the WWW-Authenticate header even when POWER_PLATFORM_TENANT_ID already+// supplied the answer. A data-model run issues dozens of calls, so the waste+// dominated wall-clock time.+//+// These tests exercise the real code path rather than mocking internals: a fake+// `az` executable is placed first on PATH and logs every invocation, so we can+// assert exactly which subcommands ran. The resource URL points at 127.0.0.1:1+// so that if the challenge probe IS reached it fails instantly with+// ECONNREFUSED instead of touching the network.++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 HELPERS = path.join(__dirname, '..', 'lib', 'validation-helpers.js');+const FAKE_AZ_PRELOAD = path.join(__dirname, 'helpers', 'fake-az-preload.js');+// Connection to port 1 is refused immediately, so the challenge probe (when it+// is reached at all) resolves fast and deterministically offline.+const UNREACHABLE_ENV_URL = 'https://127.0.0.1:1';++// The Node preload intercepts `execFileSync('az', ...)`, writes one line per+// invocation to $FAKE_AZ_LOG, then emulates the two subcommands getAuthToken uses:+// az account show --query tenantId -o tsv+// az account get-access-token --resource <url> [--tenant <id>] ...+// $FAKE_AZ_FAIL_TENANTS is a comma-separated list of tenants for which token+// acquisition should fail (exit 1), letting a test drive the fallback chain.+function makeFakeAzLog(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fake-az-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return path.join(dir, 'az.log');+}++// Runs getAuthToken in a child process so preload/env manipulation cannot leak+// into the test runner, and returns both the token and the az invocation log.+function runGetAuthToken(t, env = {}, explicitTenantId = null) {+ const logPath = makeFakeAzLog(t);+ const script = `+ const { getAuthToken } = require(${JSON.stringify(HELPERS)});+ getAuthToken(${JSON.stringify(UNREACHABLE_ENV_URL)}, ${JSON.stringify(explicitTenantId)})+ .then((token) => { process.stdout.write(String(token)); })+ .catch((error) => { process.stderr.write(String(error)); process.exit(1); });+ `;++ const result = spawnSync(process.execPath, ['-e', script], {+ encoding: 'utf8',+ env: {+ ...process.env,+ NODE_OPTIONS: `--require=${FAKE_AZ_PRELOAD}`,+ FAKE_AZ_LOG: logPath,+ // Cleared unless a test opts in — the ambient shell may have them set.+ POWER_PLATFORM_TENANT_ID: '',+ DATAVERSE_TENANT_ID: '',+ FAKE_AZ_ACCOUNT_TENANT: '',+ FAKE_AZ_FAIL_TENANTS: '',+ ...env,+ },+ });++ assert.equal(result.status, 0, `getAuthToken failed: ${result.stderr}`);+ const log = fs.existsSync(logPath) ? fs.readFileSync(logPath, 'utf8') : '';+ return { token: result.stdout.trim(), log };+}++test('explicit tenant argument short-circuits shell environment and discovery', (t) => {+ const { token, log } = runGetAuthToken(+ t,+ {+ POWER_PLATFORM_TENANT_ID: 'tenant-from-env',+ DATAVERSE_TENANT_ID: 'secondary-tenant',+ FAKE_AZ_ACCOUNT_TENANT: 'tenant-from-az-account',+ },+ 'explicit-tenant',+ );++ assert.equal(token, 'token-for:explicit-tenant');+ assert.doesNotMatch(log, /account show/);+ assert.equal(log.trim().split('\n').length, 1);+});++test('env-supplied tenant short-circuits: no `az account show` is spawned', (t) => {+ const { token, log } = runGetAuthToken(t, {+ POWER_PLATFORM_TENANT_ID: 'tenant-from-env',+ FAKE_AZ_ACCOUNT_TENANT: 'tenant-from-az-account',+ });++ assert.equal(token, 'token-for:tenant-from-env');+ assert.match(log, /get-access-token/);+ // The regression this test exists for.+ assert.doesNotMatch(log, /account show/);+ // Exactly one az invocation — nothing speculative.+ assert.equal(log.trim().split('\n').length, 1);+});++test('POWER_PLATFORM_TENANT_ID wins over DATAVERSE_TENANT_ID', (t) => {+ const { token } = runGetAuthToken(t, {+ POWER_PLATFORM_TENANT_ID: 'primary-tenant',+ DATAVERSE_TENANT_ID: 'secondary-tenant',+ });++ assert.equal(token, 'token-for:primary-tenant');+});++test('falls through to the next candidate when a tenant yields no token', (t) => {+ const { token, log } = runGetAuthToken(t, {+ POWER_PLATFORM_TENANT_ID: 'broken-tenant',+ DATAVERSE_TENANT_ID: 'working-tenant',+ FAKE_AZ_FAIL_TENANTS: 'broken-tenant',+ });++ assert.equal(token, 'token-for:working-tenant');+ assert.match(log, /--tenant broken-tenant/);+ assert.match(log, /--tenant working-tenant/);+});++test('still falls back to `az account show` when no env tenant is set', (t) => {+ // With no env tenant and an unreachable endpoint, the challenge probe yields+ // nothing, so the az active-account tenant must still be consulted.+ const { token, log } = runGetAuthToken(t, {+ FAKE_AZ_ACCOUNT_TENANT: 'tenant-from-az-account',+ });++ assert.match(log, /account show/);+ assert.equal(token, 'token-for:tenant-from-az-account');+});++test('final fallback mints an unqualified token when no tenant resolves', (t) => {+ // No env tenant, unreachable challenge, and `az account show` returns blank.+ const { token, log } = runGetAuthToken(t);++ assert.match(log, /account show/);+ assert.equal(token, 'token-for:active-account');+ assert.doesNotMatch(log, /--tenant/);+});diff --git a/plugins/mobile-apps/scripts/tests/check-routes.test.js b/plugins/mobile-apps/scripts/tests/check-routes.test.jsnew file mode 100644index 000000000..d35676a61--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/check-routes.test.js@@ -0,0 +1,59 @@+'use strict';++const assert = require('node:assert/strict');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');++const script = path.resolve(__dirname, '..', 'check-routes.js');++function makeProject(t, files) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'check-routes-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ for (const [relativePath, content] of Object.entries(files)) {+ const file = path.join(root, relativePath);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ }+ return root;+}++function run(projectRoot) {+ return spawnSync(process.execPath, [script, '--json'], {+ cwd: projectRoot,+ encoding: 'utf8',+ });+}++test('does not require useLocalSearchParams when navigation sends zero params', (t) => {+ const root = makeProject(t, {+ 'app/index.tsx': `+ import { useRouter } from 'expo-router';+ export default function Index() {+ const router = useRouter();+ return <Button onPress={() => router.push('/home')} />;+ }+ `,+ 'app/home.tsx': 'export default function Home() { return null; }',+ });++ const result = run(root);+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(JSON.parse(result.stdout).findings, []);+});++test('reports a route file that conflicts with its same-name child folder', (t) => {+ const root = makeProject(t, {+ 'app/incidents/[id].tsx': 'export default function Detail() { return null; }',+ 'app/incidents/[id]/review.tsx': 'export default function Review() { return null; }',+ });++ const result = run(root);+ assert.equal(result.status, 1);+ const findings = JSON.parse(result.stdout).findings;+ assert.equal(findings.length, 1);+ assert.equal(findings[0].kind, 'file-folder-route-collision');+ assert.equal(findings[0].route, '/incidents/[id]');+});diff --git a/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.jsnew file mode 100644index 000000000..8f8c5b1c5--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js@@ -0,0 +1,2121 @@+'use strict';++const assert = require('node:assert/strict');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const {+ bindContractToPlan,+ buildManifest,+ contractApprovalContent,+ normalizedContract,+ reconciliationScope,+ rollForwardPublishCheckpoint,+ sha256,+ stableJson,+ validateManifest,+} = require('../build-dataverse-operation-manifest');+const { operationFingerprint } = require('../dataverse-request');++const NOW = '2026-08-19T00:00:00.000Z';+const SNAPSHOT_AT = '2026-08-18T23:55:00.000Z';+const CONTEXT = {+ environmentId: 'environment-1',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ publisherPrefix: 'cr1',+ solutionUniqueName: 'MobileAppSolution',+};++function column(logicalName, type = 'String', overrides = {}) {+ const constraints = {+ BigInt: {},+ Boolean: { defaultValue: false },+ DateTime: { format: 'DateAndTime', dateTimeBehavior: 'UserLocal' },+ Decimal: {+ minValue: -100000000000,+ maxValue: 100000000000,+ precision: 2,+ },+ Double: {+ minValue: -100000000000,+ maxValue: 100000000000,+ precision: 2,+ },+ File: { maxSizeInKB: 32768 },+ Image: { maxHeight: 1440, maxWidth: 1440 },+ Integer: { minValue: -2147483648, maxValue: 2147483647, format: 'None' },+ Memo: { maxLength: 10000, format: 'TextArea' },+ Money: {+ minValue: -922337203685477,+ maxValue: 922337203685477,+ precision: 2,+ precisionSource: 2,+ },+ String: { maxLength: 200, formatName: 'Text' },+ }[type] || {};+ return {+ logicalName,+ schemaName: logicalName,+ type,+ typeName: `${type}Type`,+ sourceType: 0,+ sourceTypeMask: 0,+ lookupTargets: [],+ choices: [],+ formulaDefinition: null,+ primaryName: false,+ requiredLevel: 'None',+ ...constraints,+ ...overrides,+ };+}++function table(logicalName, columns, overrides = {}) {+ return {+ logicalName,+ schemaName: logicalName,+ displayName: logicalName,+ displayCollectionName: `${logicalName}s`,+ entitySetName: `${logicalName}s`,+ primaryIdAttribute: `${logicalName}id`,+ primaryNameAttribute: columns.find((item) => item.primaryName)?.logicalName+ || columns[0]?.logicalName+ || `${logicalName}name`,+ ownershipType: 'UserOwned',+ hasActivities: false,+ hasNotes: false,+ isAvailableOffline: true,+ changeTrackingEnabled: true,+ customEntity: logicalName !== 'contact',+ managed: false,+ customizable: true,+ canCreateAttributes: true,+ canBePrimaryEntityInRelationship: true,+ canBeRelatedEntityInRelationship: true,+ canBeInManyToMany: true,+ columns,+ manyToOneRelationships: [],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ facts: {+ columnCount: columns.length,+ relationshipCount: 0,+ keyCount: 0,+ },+ ...overrides,+ };+}++function inventory(tableValue) {+ return {+ logicalName: tableValue.logicalName,+ schemaName: tableValue.schemaName,+ displayName: tableValue.displayName,+ displayCollectionName: tableValue.displayCollectionName,+ description: '',+ entitySetName: tableValue.entitySetName,+ primaryIdAttribute: tableValue.primaryIdAttribute,+ primaryNameAttribute: tableValue.primaryNameAttribute,+ ownershipType: tableValue.ownershipType,+ hasActivities: tableValue.hasActivities,+ hasNotes: tableValue.hasNotes,+ isAvailableOffline: tableValue.isAvailableOffline,+ changeTrackingEnabled: tableValue.changeTrackingEnabled,+ customEntity: tableValue.customEntity,+ managed: tableValue.managed,+ customizable: tableValue.customizable,+ canCreateAttributes: tableValue.canCreateAttributes,+ canBePrimaryEntityInRelationship: tableValue.canBePrimaryEntityInRelationship,+ canBeRelatedEntityInRelationship: tableValue.canBeRelatedEntityInRelationship,+ canBeInManyToMany: tableValue.canBeInManyToMany,+ };+}++function snapshot({+ tables = [],+ proposedMissing = [],+ proposedCollisions = [],+ exactUnavailable = [],+ generatedAt = SNAPSHOT_AT,+} = {}) {+ const exactLoaded = tables.map((item) => item.logicalName);+ const requested = [...new Set([+ ...exactLoaded,+ ...exactUnavailable,+ ...proposedMissing,+ ...proposedCollisions,+ ])].sort();+ const loadedSet = new Set(exactLoaded);+ const unavailable = requested.filter((logicalName) => !loadedSet.has(logicalName));+ const checked = [+ ...proposedMissing.map((logicalName) => ({ logicalName, status: 'missing', existing: null })),+ ...proposedCollisions.map((logicalName) => ({+ logicalName,+ status: 'collision',+ existing: inventory(tables.find((item) => item.logicalName === logicalName)),+ })),+ ].sort((left, right) => left.logicalName.localeCompare(right.logicalName));+ const collisions = checked.filter((item) => item.status === 'collision');+ return {+ version: 3,+ purpose: 'execution-reconciliation',+ environmentUrl: CONTEXT.environmentUrl,+ tenantId: CONTEXT.tenantId,+ generatedAt,+ inputs: {+ concepts: [],+ explicitTableNames: requested,+ proposedTableNames: checked.map((item) => item.logicalName),+ },+ inventory: tables.map(inventory).sort((left, right) => (+ left.logicalName.localeCompare(right.logicalName)+ )),+ inventoryFacts: {+ customizableTables: tables.length,+ exactNameTables: tables.length,+ requiredExactNameTables: tables.length,+ proposedCollisionTables: collisions.length,+ totalTables: tables.length,+ },+ candidateRanking: [],+ selectedCandidateEvidence: [],+ tables,+ detailLoadFailures: [],+ detailLoadSummary: {+ attemptedCandidates: tables.length,+ loadedCandidates: tables.length,+ failedCandidates: 0,+ },+ proposedNameChecks: {+ checked,+ collisions,+ missing: proposedMissing,+ },+ exactNameResolution: {+ requestedTables: requested,+ loadedTables: exactLoaded,+ unavailableTables: unavailable,+ },+ timings: {+ inventoryRetrievalMs: 10,+ candidateSelectionMs: 1,+ detailLoadingMs: 3,+ totalDurationMs: 14,+ },+ reconciliation: {+ boundedExactNames: true,+ fullInventoryRead: false,+ tables: requested,+ proposedNames: checked.map((item) => item.logicalName),+ },+ };+}++function contractTable(logicalName, plannedDecision, dependencyTier, columns, overrides = {}) {+ return {+ logicalName,+ schemaName: logicalName,+ displayName: logicalName,+ displayCollectionName: `${logicalName}s`,+ plannedDecision,+ dependencyTier,+ serviceRequired: true,+ ownershipType: 'UserOwned',+ columns,+ relationships: [],+ alternateKeys: [],+ ...overrides,+ };+}++function contractColumn(logicalName, type, plannedDecision = 'create', overrides = {}) {+ return {+ logicalName,+ schemaName: logicalName,+ displayName: logicalName,+ type,+ plannedDecision,+ requiredLevel: 'None',+ ...overrides,+ };+}++function createContract() {+ return {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'create', 1, [+ contractColumn('cr1_name', 'string', 'create', {+ primaryName: true,+ requiredLevel: 'ApplicationRequired',+ }),+ contractColumn('cr1_categoryid', 'lookup', 'create', {+ lookupTarget: 'cr1_category',+ }),+ contractColumn('cr1_code', 'string'),+ ], {+ relationships: [{+ kind: 'many-to-one',+ schemaName: 'cr1_Category_Item',+ plannedDecision: 'create',+ parentTable: 'cr1_category',+ childTable: 'cr1_item',+ lookup: {+ logicalName: 'cr1_categoryid',+ schemaName: 'cr1_categoryid',+ displayName: 'Category',+ requiredLevel: 'None',+ },+ }],+ alternateKeys: [{+ schemaName: 'cr1_item_code_key',+ displayName: 'Item Code Key',+ plannedDecision: 'create',+ columns: ['cr1_code'],+ }],+ }),+ contractTable('cr1_category', 'create', 0, [+ contractColumn('cr1_name', 'string', 'create', {+ primaryName: true,+ requiredLevel: 'ApplicationRequired',+ }),+ ]),+ contractTable('contact', 'reuse', 0, [+ contractColumn('fullname', 'string', 'reuse', { primaryName: true }),+ ]),+ contractTable('cr1_deferred', 'defer', 0, [], {+ reason: 'owning solution is not installed',+ }),+ ],+ };+}++function buildInputs(contract, reconciliation, plan = '# Plan\n') {+ const planBytes = Buffer.from(plan);+ const normalized = normalizedContract(contract);+ const serviceRequiredTables = [];+ for (const tableValue of normalized.tables) {+ if (tableValue.serviceRequired && tableValue.plannedDecision !== 'defer') {+ serviceRequiredTables.push({+ logicalName: tableValue.plannedDecision === 'adapt'+ ? tableValue.adaptedLogicalName+ : tableValue.logicalName,+ consumers: [`test:${tableValue.logicalName}`],+ });+ }+ for (const relationship of tableValue.relationships) {+ if (relationship.kind !== 'many-to-many'+ || !relationship.serviceRequired+ || relationship.plannedDecision === 'defer') continue;+ serviceRequiredTables.push({+ logicalName: relationship.plannedDecision === 'adapt'+ ? relationship.adaptedIntersectTable+ : relationship.intersectTable,+ consumers: [`test:${relationship.schemaName}`],+ });+ }+ }+ const serviceDependencies = {+ schemaVersion: 1,+ serviceRequiredTables: [...new Map(serviceRequiredTables.map((item) => [+ item.logicalName,+ item,+ ])).values()],+ };+ const approvedContract = contractApprovalContent(normalized);+ const approvalReceipt = {+ schemaVersion: 1,+ workflow: 'create-mobile-app',+ approvals: {+ dataModel: {+ status: 'approved',+ approvedAt: NOW,+ approvedContractSha256: sha256(stableJson(approvedContract)),+ },+ nativeCapabilities: { status: 'approved', approvedAt: NOW },+ connectors: { status: 'approved', approvedAt: NOW },+ screenPlan: { status: 'approved', approvedAt: NOW },+ },+ approvedPlanSha256: sha256(planBytes),+ approvedContractSha256: sha256(stableJson(approvedContract)),+ approvedContract,+ serviceRequiredTables: serviceDependencies.serviceRequiredTables,+ };+ approvalReceipt.integritySha256 = sha256(stableJson(approvalReceipt));+ const bound = bindContractToPlan(normalized, planBytes, approvalReceipt);+ const scope = reconciliationScope(bound);+ const scopedReconciliation = structuredClone(reconciliation);+ const tableByName = new Map(+ (scopedReconciliation.tables || []).map((item) => [item.logicalName, item]),+ );+ scopedReconciliation.inputs = {+ ...(scopedReconciliation.inputs || {}),+ explicitTableNames: scope.exactTables,+ proposedTableNames: scope.proposedTables,+ };+ scopedReconciliation.exactNameResolution = {+ requestedTables: scope.exactTables,+ loadedTables: scope.exactTables.filter((logicalName) => tableByName.has(logicalName)),+ unavailableTables: scope.exactTables.filter((logicalName) => !tableByName.has(logicalName)),+ };+ const checked = scope.proposedTables.map((logicalName) => ({+ logicalName,+ status: tableByName.has(logicalName) ? 'collision' : 'missing',+ existing: tableByName.has(logicalName) ? inventory(tableByName.get(logicalName)) : null,+ }));+ scopedReconciliation.proposedNameChecks = {+ checked,+ collisions: checked.filter((item) => item.status === 'collision'),+ missing: checked.filter((item) => item.status === 'missing')+ .map((item) => item.logicalName),+ };+ scopedReconciliation.reconciliation = {+ boundedExactNames: true,+ fullInventoryRead: false,+ tables: scope.exactTables,+ proposedNames: scope.proposedTables,+ };+ const contractBytes = Buffer.from(stableJson(bound));+ const reconciliationBytes = Buffer.from(JSON.stringify(scopedReconciliation, null, 2));+ return {+ contract: bound,+ approvalReceipt,+ reconciliation: scopedReconciliation,+ contractBytes,+ reconciliationBytes,+ planBytes,+ context: CONTEXT,+ now: NOW,+ };+}++function approvedDecisions(contract) {+ const decisions = new Map();+ for (const tableValue of normalizedContract(contract).tables) {+ decisions.set(`table:${tableValue.logicalName}`, tableValue.plannedDecision);+ for (const columnValue of tableValue.columns) {+ decisions.set(+ `column:${tableValue.logicalName}:${columnValue.logicalName}`,+ columnValue.plannedDecision,+ );+ }+ for (const relationship of tableValue.relationships) {+ decisions.set(+ `relationship:${tableValue.logicalName}:${relationship.schemaName.toLowerCase()}`,+ relationship.plannedDecision,+ );+ }+ for (const key of tableValue.alternateKeys) {+ decisions.set(+ `key:${tableValue.logicalName}:${key.schemaName.toLowerCase()}`,+ key.plannedDecision,+ );+ }+ }+ return decisions;+}++function basePlanningSnapshot() {+ const contact = table('contact', [+ column('fullname', 'String', {+ primaryName: true,+ customAttribute: false,+ }),+ ], { customEntity: false });+ return snapshot({+ tables: [contact],+ proposedMissing: ['cr1_category', 'cr1_item'],+ exactUnavailable: ['cr1_deferred'],+ });+}++function fullyAppliedSnapshot() {+ const category = table('cr1_category', [+ column('cr1_name', 'String', {+ primaryName: true,+ requiredLevel: 'ApplicationRequired',+ }),+ ]);+ const item = table('cr1_item', [+ column('cr1_name', 'String', {+ primaryName: true,+ requiredLevel: 'ApplicationRequired',+ }),+ column('cr1_categoryid', 'Lookup', {+ lookupTargets: ['cr1_category'],+ }),+ column('cr1_code', 'String'),+ ], {+ manyToOneRelationships: [{+ schemaName: 'cr1_Category_Item',+ lookupColumn: 'cr1_categoryid',+ targetTable: 'cr1_category',+ targetColumn: 'cr1_categoryid',+ managed: false,+ cascadeConfiguration: {+ Assign: 'NoCascade',+ Delete: 'RemoveLink',+ Merge: 'NoCascade',+ Reparent: 'NoCascade',+ Share: 'NoCascade',+ Unshare: 'NoCascade',+ RollupView: 'NoCascade',+ },+ }],+ alternateKeys: [{+ logicalName: 'cr1_item_code_key',+ schemaName: 'cr1_item_code_key',+ columns: ['cr1_code'],+ status: 'Active',+ managed: false,+ }],+ });+ const contact = table('contact', [+ column('fullname', 'String', { primaryName: true }),+ ], { customEntity: false });+ return snapshot({+ tables: [category, item, contact],+ proposedCollisions: ['cr1_category', 'cr1_item'],+ exactUnavailable: ['cr1_deferred'],+ });+}++test('manifest output is deterministic with complete coverage and dependency order', () => {+ const contract = createContract();+ const inputs = buildInputs(contract, basePlanningSnapshot());+ const first = buildManifest(inputs);+ const second = buildManifest(inputs);++ assert.deepEqual(first, second);+ assert.equal(first.executable, true);+ assert.equal(first.summary.decisionCount, 11);+ assert.equal(first.decisions.length, 11);+ assert.equal(new Set(first.decisions.map((item) => item.itemId)).size, 11);+ assert.equal(first.schemaVersion, 2);+ assert.equal(first.binding.environmentId, CONTEXT.environmentId);+ assert.equal(first.binding.environmentUrl, CONTEXT.environmentUrl);+ assert.equal(first.binding.tenantId, CONTEXT.tenantId);+ assert.equal(first.binding.publisherPrefix, CONTEXT.publisherPrefix);+ assert.equal(first.binding.solutionUniqueName, CONTEXT.solutionUniqueName);+ assert.match(first.binding.planSha256, /^[a-f0-9]{64}$/);+ assert.match(first.binding.structuredSchemaSha256, /^[a-f0-9]{64}$/);+ assert.match(first.binding.reconciliationSha256, /^[a-f0-9]{64}$/);+ assert.deepEqual(+ first.execution.phases.map((phase) => phase.name),+ ['tableCreates', 'extensions', 'relationships', 'alternateKeys', 'publish'],+ );+ assert.deepEqual(first.execution.journal, {+ required: true,+ schemaVersion: 1,+ atomicPerOperation: true,+ uncertainResumeRequiresFreshReconciliation: true,+ });+ assert.deepEqual(+ first.execution.phases[0].operations.map((item) => item.id),+ ['create-table:cr1_category', 'create-table:cr1_item'],+ );+ assert.equal(first.execution.phases[0].operations[1].body.Attributes.length, 2);+ assert.equal(first.execution.phases[1].operations.length, 0);+ assert.equal(+ first.execution.phases[0].operations[1].body.Attributes.some(+ (item) => item['@odata.type'].includes('Lookup'),+ ),+ false,+ );+ assert.equal(first.execution.phases[2].operations[0].id, 'create-relationship:cr1_category_item');+ assert.equal(first.execution.phases[3].operations[0].id, 'create-key:cr1_item:cr1_item_code_key');+ assert.equal(first.execution.phases[4].operations[0].apiPath, 'PublishXml');+ assert.deepEqual(+ first.execution.phases.flatMap((phase) => phase.operations).map((item) => item.index),+ [0, 1, 2, 3, 4],+ );+});++test('fresh reconciliation scope comes only from the structured schema artifact', () => {+ const scope = reconciliationScope(createContract());+ assert.deepEqual(scope, {+ schemaVersion: 1,+ exactTables: ['contact', 'cr1_category', 'cr1_deferred', 'cr1_item'],+ proposedTables: ['cr1_category', 'cr1_item'],+ });+ const manifest = buildManifest(buildInputs(createContract(), basePlanningSnapshot()));+ assert.deepEqual(manifest.verification.reconciliationScope, scope);+});++test('lookup columns require an explicit matching relationship contract', () => {+ const contract = createContract();+ contract.tables.find((item) => item.logicalName === 'cr1_item').relationships = [];+ assert.throws(+ () => reconciliationScope(contract),+ /lookup has no matching many-to-one relationship/,+ );+});++test('schema names deterministically resolve to their logical identities', () => {+ const valid = createContract();+ const item = valid.tables.find((entry) => entry.logicalName === 'cr1_item');+ item.schemaName = 'cr1_Item';+ item.columns.find((entry) => entry.logicalName === 'cr1_name').schemaName = 'cr1_Name';+ item.relationships[0].lookup.schemaName = 'cr1_CategoryId';+ assert.doesNotThrow(() => reconciliationScope(valid));+ const defaultedLookupSchema = structuredClone(valid);+ delete defaultedLookupSchema.tables+ .find((entry) => entry.logicalName === 'cr1_item')+ .relationships[0].lookup.schemaName;+ assert.equal(+ normalizedContract(defaultedLookupSchema).tables+ .find((entry) => entry.logicalName === 'cr1_item')+ .relationships[0].lookup.schemaName,+ 'cr1_categoryid',+ );++ const tableMismatch = structuredClone(valid);+ tableMismatch.tables.find((entry) => entry.logicalName === 'cr1_item').schemaName = 'cr1_Other';+ assert.throws(+ () => reconciliationScope(tableMismatch),+ /schemaName must resolve to logicalName cr1_item/,+ );++ const columnMismatch = structuredClone(valid);+ columnMismatch.tables+ .find((entry) => entry.logicalName === 'cr1_item')+ .columns+ .find((entry) => entry.logicalName === 'cr1_name')+ .schemaName = 'cr1_OtherName';+ assert.throws(+ () => reconciliationScope(columnMismatch),+ /schemaName must resolve to logicalName cr1_name/,+ );++ const adaptedTableMismatch = createContract();+ const adaptedItem = adaptedTableMismatch.tables.find(+ (entry) => entry.logicalName === 'cr1_item',+ );+ adaptedItem.plannedDecision = 'adapt';+ adaptedItem.adaptedLogicalName = 'cr1_itemv2';+ adaptedItem.adaptedSchemaName = 'cr1_WrongV2';+ assert.throws(+ () => reconciliationScope(adaptedTableMismatch),+ /schemaName must resolve to logicalName cr1_itemv2/,+ );+});++test('adapted relationship lookup identity must match the adapted child column', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_child', 'extend', 1, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_parentid', 'lookup', 'adapt', {+ lookupTarget: 'cr1_parent',+ adaptedLogicalName: 'cr1_parentidv2',+ adaptedSchemaName: 'cr1_ParentIdV2',+ }),+ ], {+ relationships: [{+ kind: 'many-to-one',+ schemaName: 'cr1_Parent_Child_v2',+ adaptedSchemaName: 'cr1_Parent_Child_v2',+ plannedDecision: 'adapt',+ parentTable: 'cr1_parent',+ childTable: 'cr1_child',+ lookup: {+ logicalName: 'cr1_parentid',+ schemaName: 'cr1_ParentId',+ adaptedLogicalName: 'cr1_differentid',+ adaptedSchemaName: 'cr1_DifferentId',+ },+ }],+ }),+ contractTable('cr1_parent', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ ],+ };+ const adaptedColumnMismatch = structuredClone(contract);+ const mismatchedColumn = adaptedColumnMismatch.tables[0].columns.find(+ (entry) => entry.logicalName === 'cr1_parentid',+ );+ mismatchedColumn.adaptedSchemaName = 'cr1_WrongId';+ adaptedColumnMismatch.tables[0].relationships[0].lookup.adaptedLogicalName =+ mismatchedColumn.adaptedLogicalName;+ adaptedColumnMismatch.tables[0].relationships[0].lookup.adaptedSchemaName =+ 'cr1_ParentIdV2';+ assert.throws(+ () => reconciliationScope(adaptedColumnMismatch),+ /schemaName must resolve to logicalName cr1_parentidv2/,+ );+ assert.throws(+ () => reconciliationScope(contract),+ /adapted lookup identity must match/,+ );+});++test('lookup and relationship decisions cannot authorize different outcomes', () => {+ const contract = createContract();+ contract.tables+ .find((item) => item.logicalName === 'cr1_item')+ .columns+ .find((item) => item.logicalName === 'cr1_categoryid')+ .plannedDecision = 'defer';+ assert.throws(+ () => reconciliationScope(contract),+ /decision must match its lookup column decision/,+ );+});++test('lookup column requiredLevel is authoritative for relationship payloads', () => {+ const mismatch = createContract();+ mismatch.tables+ .find((item) => item.logicalName === 'cr1_item')+ .relationships[0].lookup.requiredLevel = 'ApplicationRequired';+ assert.throws(+ () => reconciliationScope(mismatch),+ /lookup requiredLevel must match/,+ );++ const contract = createContract();+ const item = contract.tables.find((entry) => entry.logicalName === 'cr1_item');+ item.columns.find((entry) => entry.logicalName === 'cr1_categoryid')+ .requiredLevel = 'ApplicationRequired';+ delete item.relationships[0].lookup.requiredLevel;+ const manifest = buildManifest(buildInputs(contract, basePlanningSnapshot()));+ assert.equal(+ manifest.execution.phases[2].operations[0].body.Lookup.RequiredLevel.Value,+ 'ApplicationRequired',+ );+});++test('alternate keys cannot depend on deferred or unverified columns', () => {+ const contract = createContract();+ contract.tables+ .find((item) => item.logicalName === 'cr1_item')+ .columns+ .find((item) => item.logicalName === 'cr1_code')+ .plannedDecision = 'defer';+ assert.throws(+ () => reconciliationScope(contract),+ /cannot depend on cr1_code with decision defer/,+ );+});++test('reuse tables cannot smuggle create or adapt column writes', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [contractTable('cr1_existing', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ ])],+ };+ assert.throws(+ () => reconciliationScope(contract),+ /reuse table cannot authorize create column cr1_name/,+ );+});++test('existing create targets with missing ordinary columns conflict instead of extending', () => {+ const contact = table('contact', [+ column('fullname', 'String', { primaryName: true, customAttribute: false }),+ ], { customEntity: false });+ const partialCategory = table('cr1_category', []);+ const manifest = buildManifest(buildInputs(createContract(), snapshot({+ tables: [contact, partialCategory],+ proposedMissing: ['cr1_item'],+ proposedCollisions: ['cr1_category'],+ exactUnavailable: ['cr1_deferred'],+ })));+ const categoryName = manifest.decisions.find(+ (item) => item.itemId === 'column:cr1_category:cr1_name',+ );+ assert.equal(categoryName.decision, 'create');+ assert.equal(categoryName.verificationStatus, 'unverified');+ assert.equal(manifest.execution.phases[1].operations.length, 0);+ assert.equal(manifest.executable, false);+});++test('free-form Markdown is hash-bound but never parsed into operations', () => {+ const contract = createContract();+ const reconciliation = basePlanningSnapshot();+ const first = buildManifest(buildInputs(contract, reconciliation, '# Approved A\n'));+ const second = buildManifest(buildInputs(contract, reconciliation, '# Completely different prose\n'));+ assert.notEqual(first.binding.planSha256, second.binding.planSha256);+ assert.deepEqual(first.decisions, second.decisions);+ assert.deepEqual(first.aliases, second.aliases);+ assert.deepEqual(first.service, second.service);+ assert.deepEqual(first.execution, second.execution);+});++test('service-required tables are explicit and deferred tables are excluded', () => {+ const manifest = buildManifest(buildInputs(createContract(), basePlanningSnapshot()));+ assert.deepEqual(+ manifest.service.requiredTables.map((item) => item.logicalName),+ ['contact', 'cr1_category', 'cr1_item'],+ );+ assert.equal(manifest.service.generationMode, 'sequential-outside-batch-metadata');+ assert.equal(manifest.execution.executor, 'BATCH-METADATA');+ assert.equal(manifest.execution.odataBatch, false);+ assert.equal(manifest.execution.parallelWrites, false);+});++test('service-required M:N intersect tables stay outside metadata table creates', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'create', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ ], {+ relationships: [{+ kind: 'many-to-many',+ schemaName: 'cr1_Item_Tag',+ plannedDecision: 'create',+ entity1: 'cr1_item',+ entity2: 'cr1_tag',+ intersectTable: 'cr1_item_tag',+ serviceRequired: true,+ }],+ }),+ contractTable('cr1_tag', 'create', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ ]),+ ],+ };+ const manifest = buildManifest(buildInputs(contract, snapshot({+ proposedMissing: ['cr1_item', 'cr1_tag'],+ })));+ assert.deepEqual(reconciliationScope(contract), {+ schemaVersion: 1,+ exactTables: ['cr1_item', 'cr1_item_tag', 'cr1_tag'],+ proposedTables: ['cr1_item', 'cr1_item_tag', 'cr1_tag'],+ });++ assert.deepEqual(+ manifest.service.requiredTables.map((item) => item.logicalName),+ ['cr1_item', 'cr1_item_tag', 'cr1_tag'],+ );+ assert.deepEqual(+ manifest.execution.phases[0].operations.map((item) => item.id),+ ['create-table:cr1_item', 'create-table:cr1_tag'],+ );+ assert.equal(manifest.execution.phases[2].operations[0].id, 'create-relationship:cr1_item_tag');++ const collidingIntersect = table('cr1_item_tag', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ const existingItem = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ const existingTag = table('cr1_tag', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ const blocked = buildManifest(buildInputs(contract, snapshot({+ tables: [existingItem, collidingIntersect, existingTag],+ })));+ const relationshipDecision = blocked.decisions.find(+ (decision) => decision.itemType === 'relationship',+ );+ assert.equal(relationshipDecision.verificationStatus, 'unverified');+ assert.match(relationshipDecision.reason, /intersect name cr1_item_tag collides/);+ assert.equal(blocked.execution.phases[2].operations.length, 0);+});++test('existing customizable tables queue only missing ordinary columns as extensions', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_code', 'string', 'create'),+ ]),+ ],+ };+ const liveItem = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ const manifest = buildManifest(buildInputs(contract, snapshot({ tables: [liveItem] })));++ assert.equal(+ manifest.decisions.find((item) => item.itemId === 'table:cr1_item').decision,+ 'extend',+ );+ assert.equal(manifest.execution.phases[0].operations.length, 0);+ assert.deepEqual(+ manifest.execution.phases[1].operations.map((item) => item.id),+ ['extend-column:cr1_item:cr1_code'],+ );+ assert.equal(manifest.execution.phases[4].operations.length, 1);+});++test('adapt, defer, and unverified decisions are explicit and unverified blocks execution', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_collision', 'adapt', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ ], {+ adaptedLogicalName: 'cr1_collisionv2',+ adaptedSchemaName: 'cr1_collisionv2',+ }),+ contractTable('cr1_manageddependency', 'defer', 0, []),+ contractTable('cr1_unknown', 'unverified', 0, [+ contractColumn('cr1_name', 'string', 'unverified', { primaryName: true }),+ ]),+ ],+ };+ const manifest = buildManifest(buildInputs(contract, snapshot({+ proposedMissing: ['cr1_collisionv2'],+ exactUnavailable: ['cr1_manageddependency'],+ })));+ const byId = new Map(manifest.decisions.map((item) => [item.itemId, item]));++ assert.equal(byId.get('table:cr1_collision').decision, 'adapt');+ assert.equal(byId.get('table:cr1_collision').effectiveName, 'cr1_collisionv2');+ assert.equal(byId.get('table:cr1_manageddependency').decision, 'defer');+ assert.equal(byId.get('table:cr1_unknown').decision, 'unverified');+ assert.equal(byId.get('table:cr1_unknown').verificationStatus, 'unverified');+ assert.equal(byId.get('column:cr1_unknown:cr1_name').decision, 'unverified');+ assert.equal(+ byId.get('column:cr1_unknown:cr1_name').verificationStatus,+ 'unverified',+ );+ assert.equal(manifest.executable, false);+ assert.equal(manifest.publishCheckpoint, null);+ assert.deepEqual(manifest.verification.unresolvedItemIds, [+ 'column:cr1_unknown:cr1_name',+ 'table:cr1_unknown',+ ]);+});++test('validation rejects environment, plan, and reconciliation mismatches', () => {+ const contract = createContract();+ const snapshotValue = basePlanningSnapshot();+ const inputs = buildInputs(contract, snapshotValue, '# Approved plan\n');+ const manifest = buildManifest(inputs);++ const wrongEnvironment = validateManifest(manifest, {+ ...inputs,+ context: { ...CONTEXT, environmentId: 'environment-2' },+ });+ assert.equal(wrongEnvironment.valid, false);+ assert.match(wrongEnvironment.errors.join('; '), /environmentId mismatch/);++ const wrongPlan = validateManifest(manifest, {+ ...inputs,+ planBytes: Buffer.from('# Changed plan\n'),+ });+ assert.equal(wrongPlan.valid, false);+ assert.match(wrongPlan.errors.join('; '), /plan hash mismatch/);+ assert.throws(+ () => buildManifest({+ ...inputs,+ planBytes: Buffer.from('# Changed plan\n'),+ }),+ /mobile plan approval receipt plan hash does not match/,+ );++ const changedSnapshot = {+ ...snapshotValue,+ generatedAt: '2026-08-18T23:40:00.000Z',+ };+ const wrongSnapshot = validateManifest(manifest, {+ ...inputs,+ reconciliation: changedSnapshot,+ reconciliationBytes: Buffer.from(JSON.stringify(changedSnapshot, null, 2)),+ });+ assert.equal(wrongSnapshot.valid, false);+ assert.match(+ wrongSnapshot.errors.join('; '),+ /execution reconciliation hash mismatch|execution reconciliation timestamp mismatch/,+ );+});++test('validation rejects stale reconciliations and non-executable manifests', () => {+ const contract = createContract();+ const stale = basePlanningSnapshot();+ stale.generatedAt = '2026-08-18T20:00:00.000Z';+ assert.throws(+ () => buildManifest(buildInputs(contract, stale)),+ /execution reconciliation is stale/,+ );++ const unverifiedContract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_unknown', 'unverified', 0, [+ contractColumn('cr1_name', 'string', 'unverified', { primaryName: true }),+ ]),+ ],+ };+ const inputs = buildInputs(unverifiedContract, snapshot());+ const manifest = buildManifest(inputs);+ const validation = validateManifest(manifest, {+ ...inputs,+ requireExecutable: true,+ });+ assert.equal(validation.valid, false);+ assert.match(validation.errors.join('; '), /approved schema revision is required/);+});++test('foreground planning snapshot alone can never authorize metadata writes', () => {+ const contract = createContract();+ const planningSnapshot = basePlanningSnapshot();+ planningSnapshot.purpose = 'foreground-planning';+ delete planningSnapshot.reconciliation;+ assert.throws(+ () => buildManifest(buildInputs(contract, planningSnapshot)),+ /fresh bounded exact-name artifact/,+ );+});++test('fresh reconciliation must cover the exact structured-schema scope', () => {+ const inputs = buildInputs(createContract(), basePlanningSnapshot());+ const removed = inputs.reconciliation.inputs.explicitTableNames.pop();+ inputs.reconciliation.exactNameResolution.requestedTables = inputs.reconciliation+ .exactNameResolution.requestedTables.filter((name) => name !== removed);+ inputs.reconciliation.exactNameResolution.unavailableTables = inputs.reconciliation+ .exactNameResolution.unavailableTables.filter((name) => name !== removed);+ inputs.reconciliationBytes = Buffer.from(JSON.stringify(+ inputs.reconciliation,+ null,+ 2,+ ));+ assert.throws(+ () => buildManifest(inputs),+ /scope does not exactly match the approved structured schema/,+ );+});++test('a fully applied rerun produces zero metadata POST operations', () => {+ const contract = createContract();+ const manifest = buildManifest(buildInputs(contract, fullyAppliedSnapshot()));+ const operations = manifest.execution.phases.flatMap((phase) => phase.operations);++ assert.equal(manifest.executable, true);+ assert.equal(manifest.summary.metadataOperationCount, 0);+ assert.equal(manifest.summary.metadataWriteCount, 0);+ assert.deepEqual(operations, []);+ assert.ok(+ manifest.decisions+ .filter((item) => item.decision === 'create')+ .every((item) => item.operation === 'none' && item.verificationStatus === 'verified'),+ );+});++test('mobile plan approval receipt binds exact contract and service dependencies', () => {+ const contract = createContract();+ const inputs = buildInputs(contract, basePlanningSnapshot(), '# Approved plan\n');+ const manifest = buildManifest(inputs);++ assert.equal(+ manifest.binding.approvedContractSha256,+ inputs.approvalReceipt.approvedContractSha256,+ );+ assert.equal(+ manifest.binding.approvalReceiptSha256,+ inputs.approvalReceipt.integritySha256,+ );+ assert.deepEqual(+ manifest.service.requiredTables.map((item) => ({+ logicalName: item.logicalName,+ consumers: item.consumers,+ })),+ inputs.approvalReceipt.serviceRequiredTables,+ );++ const addedTable = createContract();+ addedTable.tables.push(contractTable('cr1_unapproved', 'create', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ ]));+ assert.throws(+ () => bindContractToPlan(+ addedTable,+ inputs.planBytes,+ inputs.approvalReceipt,+ ),+ /structured contract content does not match the approved contract/,+ );++ const alteredBoundContract = structuredClone(inputs.contract);+ alteredBoundContract.tables.find(+ (tableValue) => tableValue.logicalName === 'cr1_item',+ ).columns.push(contractColumn('cr1_unapprovedcolumn', 'string', 'create'));+ assert.throws(+ () => buildManifest({+ ...inputs,+ contract: alteredBoundContract,+ contractBytes: Buffer.from(stableJson(alteredBoundContract)),+ }),+ /structured contract content does not match the approved contract/,+ );++ const missingServiceReceipt = structuredClone(inputs.approvalReceipt);+ missingServiceReceipt.serviceRequiredTables =+ missingServiceReceipt.serviceRequiredTables.filter(+ (item) => item.logicalName !== 'contact',+ );+ delete missingServiceReceipt.integritySha256;+ missingServiceReceipt.integritySha256 = sha256(stableJson(missingServiceReceipt));+ assert.throws(+ () => bindContractToPlan(+ contract,+ inputs.planBytes,+ missingServiceReceipt,+ ),+ /approved service dependencies do not exactly match contract serviceRequired declarations/,+ );++ const pendingReceipt = structuredClone(inputs.approvalReceipt);+ pendingReceipt.approvals.screenPlan.status = 'pending';+ delete pendingReceipt.integritySha256;+ pendingReceipt.integritySha256 = sha256(stableJson(pendingReceipt));+ assert.throws(+ () => bindContractToPlan(contract, inputs.planBytes, pendingReceipt),+ /screenPlan status must be approved/,+ );+ assert.throws(+ () => bindContractToPlan(contract, inputs.planBytes, null),+ /mobile plan approval receipt must be an object/,+ );+});++test('existing Dataverse File and Image virtual attributes are zero-write compatible', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_document', 'file', 'create', { maxSizeInKB: 32768 }),+ contractColumn('cr1_photo', 'image', 'create', {+ maxHeight: 1440,+ maxWidth: 1440,+ }),+ ]),+ ],+ };+ const existing = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ column('cr1_document', 'Virtual', {+ typeName: 'FileType',+ maxSizeInKB: 32768,+ }),+ column('cr1_photo', 'Virtual', {+ typeName: 'ImageType',+ maxHeight: 1440,+ maxWidth: 1440,+ }),+ ]);+ const manifest = buildManifest(buildInputs(contract, snapshot({+ tables: [existing],+ })));+ assert.equal(manifest.summary.metadataOperationCount, 0);+ for (const logicalName of ['cr1_document', 'cr1_photo']) {+ const decision = manifest.decisions.find(+ (item) => item.itemId === `column:cr1_item:${logicalName}`,+ );+ assert.equal(decision.decision, 'create');+ assert.equal(decision.observedOutcome, 'reuse');+ assert.equal(decision.verificationStatus, 'verified');+ }++ for (const [logicalName, typeName] of [+ ['cr1_document', 'ImageType'],+ ['cr1_photo', 'FileType'],+ ]) {+ const incompatible = structuredClone(existing);+ incompatible.columns.find(+ (item) => item.logicalName === logicalName,+ ).typeName = typeName;+ const mismatch = buildManifest(buildInputs(contract, snapshot({+ tables: [incompatible],+ })));+ const decision = mismatch.decisions.find(+ (item) => item.itemId === `column:cr1_item:${logicalName}`,+ );+ assert.notEqual(decision.verificationStatus, 'verified');+ assert.equal(mismatch.executable, false);+ assert.equal(mismatch.summary.metadataOperationCount, 0);+ }+});++test('mechanical reconciliation never changes approved architecture decisions', () => {+ const contract = createContract();+ const manifest = buildManifest(buildInputs(contract, fullyAppliedSnapshot()));+ const approved = approvedDecisions(contract);+ for (const decision of manifest.decisions) {+ assert.equal(decision.decision, approved.get(decision.itemId));+ }+ assert.ok(manifest.decisions.some(+ (decision) => decision.decision === 'create'+ && decision.observedOutcome === 'reuse'+ && decision.operation === 'none',+ ));+});++test('unverified table, column, relationship, and key decisions never queue writes', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_unknown', 'unverified', 0, [+ contractColumn('cr1_name', 'string', 'unverified', { primaryName: true }),+ contractColumn('cr1_parentid', 'lookup', 'unverified', {+ lookupTarget: 'cr1_parent',+ }),+ ], {+ relationships: [{+ kind: 'many-to-one',+ schemaName: 'cr1_Parent_Unknown',+ plannedDecision: 'unverified',+ parentTable: 'cr1_parent',+ childTable: 'cr1_unknown',+ lookup: {+ logicalName: 'cr1_parentid',+ schemaName: 'cr1_parentid',+ },+ }],+ alternateKeys: [{+ schemaName: 'cr1_unknown_name_key',+ plannedDecision: 'unverified',+ columns: ['cr1_name'],+ }],+ }),+ contractTable('cr1_parent', 'unverified', 0, [+ contractColumn('cr1_name', 'string', 'unverified', { primaryName: true }),+ ]),+ ],+ };+ const manifest = buildManifest(buildInputs(contract, snapshot({+ proposedMissing: ['cr1_parent', 'cr1_unknown'],+ })));++ assert.equal(manifest.executable, false);+ assert.equal(manifest.summary.metadataOperationCount, 0);+ assert.deepEqual(+ [...new Set(manifest.decisions.map((item) => item.decision))],+ ['unverified'],+ );+ assert.ok(manifest.decisions.every((item) => item.operation === 'none'));+});++test('semantic validation rejects recomputed-hash tampering across executable content', () => {+ const inputs = buildInputs(createContract(), basePlanningSnapshot());+ const manifest = buildManifest(inputs);+ const variants = [+ (candidate) => { candidate.decisions[0].reason = 'tampered decision'; },+ (candidate) => { candidate.service.requiredTables[0].logicalName = 'cr1_other'; },+ (candidate) => {+ candidate.execution.phases[0].operations[0].apiPath = 'OtherDefinitions';+ },+ (candidate) => {+ candidate.execution.phases[0].operations[0].body.LogicalName = 'cr1_other';+ },+ (candidate) => { candidate.aliases.tables.cr1_item = 'cr1_other'; },+ (candidate) => { candidate.binding.maxReconciliationAgeMs *= 2; },+ ];++ for (const mutate of variants) {+ const candidate = structuredClone(manifest);+ mutate(candidate);+ delete candidate.integritySha256;+ candidate.integritySha256 = sha256(stableJson(candidate));+ const validation = validateManifest(candidate, inputs);+ assert.equal(validation.valid, false);+ assert.match(validation.errors.join('; '), /semantic content/);+ }+});++test('ordinary-column reuse requires complete compatible behavior evidence', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', {+ primaryName: true,+ maxLength: 100,+ format: 'Text',+ requiredLevel: 'ApplicationRequired',+ }),+ ]),+ ],+ };+ const compatible = column('cr1_name', 'String', {+ primaryName: true,+ maxLength: 200,+ formatName: 'Text',+ requiredLevel: 'ApplicationRequired',+ });+ const compatibleManifest = buildManifest(buildInputs(contract, snapshot({+ tables: [table('cr1_item', [compatible])],+ })));+ assert.equal(+ compatibleManifest.decisions.find((item) => item.itemType === 'column').decision,+ 'reuse',+ );++ for (const liveColumn of [+ { ...compatible, maxLength: 50 },+ (() => {+ const missing = { ...compatible };+ delete missing.formatName;+ return missing;+ })(),+ { ...compatible, requiredLevel: 'None' },+ ]) {+ const manifest = buildManifest(buildInputs(contract, snapshot({+ tables: [table('cr1_item', [liveColumn])],+ })));+ assert.equal(+ manifest.decisions.find((item) => item.itemType === 'column').decision,+ 'reuse',+ );+ assert.equal(+ manifest.decisions.find((item) => item.itemType === 'column').verificationStatus,+ 'unverified',+ );+ assert.equal(manifest.summary.metadataOperationCount, 0);+ }+});++test('ordinary Memo and Lookup columns accept nullable Dataverse SourceType', () => {+ const lookupReconciliation = fullyAppliedSnapshot();+ lookupReconciliation.tables+ .find((tableValue) => tableValue.logicalName === 'cr1_item')+ .columns+ .find((columnValue) => columnValue.logicalName === 'cr1_categoryid')+ .sourceType = null;+ const lookupManifest = buildManifest(buildInputs(+ createContract(),+ lookupReconciliation,+ ));+ assert.equal(lookupManifest.executable, true);+ assert.equal(lookupManifest.summary.metadataOperationCount, 0);++ const memoContract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_note', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_description', 'memo', 'reuse', {+ maxLength: 10000,+ format: 'TextArea',+ }),+ ]),+ ],+ };+ const memoManifest = buildManifest(buildInputs(memoContract, snapshot({+ tables: [table('cr1_note', [+ column('cr1_name', 'String', { primaryName: true }),+ column('cr1_description', 'Memo', { sourceType: null }),+ ])],+ })));+ assert.equal(memoManifest.executable, true);+ assert.equal(memoManifest.summary.metadataOperationCount, 0);++ const stringWithNullSourceType = column('cr1_name', 'String', {+ primaryName: true,+ sourceType: null,+ });+ const blocked = buildManifest(buildInputs({+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_note', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ ],+ }, snapshot({+ tables: [table('cr1_note', [stringWithNullSourceType])],+ })));+ assert.equal(blocked.executable, false);+ assert.match(+ blocked.decisions.find((item) => item.itemType === 'column').reason,+ /SourceType evidence is missing/,+ );+});++test('ordinary-column precision, range, date behavior, and primary-name constraints are enforced', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_amount', 'decimal', 'reuse', {+ minValue: -10,+ maxValue: 10,+ precision: 2,+ }),+ contractColumn('cr1_occurredon', 'datetime', 'reuse', {+ format: 'DateAndTime',+ behavior: 'UserLocal',+ }),+ ]),+ ],+ };+ const compatibleColumns = [+ column('cr1_name', 'String', { primaryName: true }),+ column('cr1_amount', 'Decimal', {+ minValue: -100,+ maxValue: 100,+ precision: 2,+ }),+ column('cr1_occurredon', 'DateTime', {+ format: 'DateAndTime',+ dateTimeBehavior: 'UserLocal',+ }),+ ];+ assert.equal(buildManifest(buildInputs(contract, snapshot({+ tables: [table('cr1_item', compatibleColumns)],+ }))).executable, true);++ const mutations = [+ (columns) => { columns[0].primaryName = false; },+ (columns) => { columns[1].minValue = 0; },+ (columns) => { columns[1].precision = 4; },+ (columns) => { columns[2].dateTimeBehavior = 'TimeZoneIndependent'; },+ ];+ for (const mutate of mutations) {+ const liveColumns = structuredClone(compatibleColumns);+ mutate(liveColumns);+ const manifest = buildManifest(buildInputs(contract, snapshot({+ tables: [table('cr1_item', liveColumns)],+ })));+ assert.equal(manifest.executable, false);+ assert.equal(manifest.summary.metadataOperationCount, 0);+ }+});++test('relationship reuse requires complete matching cascade semantics', () => {+ for (const mutate of [+ (relationship) => { relationship.cascadeConfiguration = null; },+ (relationship) => { relationship.cascadeConfiguration.Delete = 'Cascade'; },+ ]) {+ const reconciliation = fullyAppliedSnapshot();+ const relationship = reconciliation.tables+ .find((tableValue) => tableValue.logicalName === 'cr1_item')+ .manyToOneRelationships[0];+ mutate(relationship);+ const manifest = buildManifest(buildInputs(createContract(), reconciliation));+ const decision = manifest.decisions.find(+ (item) => item.itemType === 'relationship',+ );+ assert.equal(decision.decision, 'create');+ assert.equal(decision.verificationStatus, 'conflict');+ assert.equal(manifest.executable, false);+ }+});++test('create-table idempotency requires complete matching emitted table behavior', () => {+ for (const mutate of [+ (liveTable) => { liveTable.hasActivities = true; },+ (liveTable) => { delete liveTable.ownershipType; },+ (liveTable) => { liveTable.changeTrackingEnabled = false; },+ ]) {+ const reconciliation = fullyAppliedSnapshot();+ const liveItem = reconciliation.tables.find(+ (tableValue) => tableValue.logicalName === 'cr1_item',+ );+ mutate(liveItem);+ const manifest = buildManifest(buildInputs(createContract(), reconciliation));+ const itemDecision = manifest.decisions.find(+ (decision) => decision.itemId === 'table:cr1_item',+ );+ assert.equal(itemDecision.decision, 'create');+ assert.equal(itemDecision.verificationStatus, 'unverified');+ assert.equal(manifest.executable, false);+ assert.equal(manifest.summary.metadataOperationCount, 0);+ }++ const matchingContract = createContract();+ matchingContract.tables.find((tableValue) => tableValue.logicalName === 'cr1_item')+ .hasActivities = true;+ const matchingSnapshot = fullyAppliedSnapshot();+ matchingSnapshot.tables.find((tableValue) => tableValue.logicalName === 'cr1_item')+ .hasActivities = true;+ const matching = buildManifest(buildInputs(matchingContract, matchingSnapshot));+ assert.equal(matching.executable, true);+ assert.equal(matching.summary.metadataOperationCount, 0);+});++test('missing lookups on non-extensible child tables conflict without changing approved decisions', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_child', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_parentid', 'lookup', 'create', {+ lookupTarget: 'cr1_parent',+ }),+ ], {+ relationships: [{+ kind: 'many-to-one',+ schemaName: 'cr1_Parent_Child',+ plannedDecision: 'create',+ parentTable: 'cr1_parent',+ childTable: 'cr1_child',+ lookup: {+ logicalName: 'cr1_parentid',+ schemaName: 'cr1_parentid',+ },+ }],+ }),+ contractTable('cr1_parent', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ ],+ };+ const parent = table('cr1_parent', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ for (const capabilities of [+ { customizable: false, canCreateAttributes: true },+ { customizable: true, canCreateAttributes: false },+ {+ customizable: true,+ canCreateAttributes: true,+ canBeRelatedEntityInRelationship: false,+ },+ ]) {+ const child = table('cr1_child', [+ column('cr1_name', 'String', { primaryName: true }),+ ], capabilities);+ const manifest = buildManifest(buildInputs(+ contract,+ snapshot({ tables: [child, parent] }),+ ));++ assert.equal(+ manifest.decisions.find(+ (item) => item.itemId === 'column:cr1_child:cr1_parentid',+ ).decision,+ 'create',+ );+ assert.equal(+ manifest.decisions.find((item) => item.itemType === 'relationship').decision,+ 'create',+ );+ assert.equal(+ manifest.decisions.find(+ (item) => item.itemId === 'column:cr1_child:cr1_parentid',+ ).verificationStatus,+ 'conflict',+ );+ assert.equal(+ manifest.decisions.find((item) => item.itemType === 'relationship')+ .verificationStatus,+ 'conflict',+ );+ assert.equal(manifest.execution.phases[2].operations.length, 0);+ }+});++test('supplied fast-path failures fail closed while absent handoffs retain Step 2 fallback', () => {+ const skill = fs.readFileSync(path.join(+ __dirname,+ '../../skills/add-dataverse/SKILL.md',+ ), 'utf8');+ assert.match(skill, /An entirely absent fast-path handoff means[\s\S]*fallback/);+ assert.match(skill, /partially supplied handoff[\s\S]*must fail closed/);+ assert.match(skill, /Never jump to[\s\S]*Step 4 without Step 2 initialization/);+ assert.match(skill, /do not[\s\S]*switch a supplied candidate to the standalone fallback/i);+ assert.match(+ skill,+ /non-executable[\s\S]*candidate[\s\S]*authorizes no metadata write/,+ );+ assert.match(skill, /discard[\s\S]*not-yet-run phase arrays/);+ assert.match(+ skill,+ /structured schema[\s\S]*regenerate the complete aliases[\s\S]*service-required names/,+ );+ assert.match(skill, /--approval-receipt <working_dir>\/\.tmp\/mobile-plan-status\.json/);+ const createSkill = fs.readFileSync(path.join(+ __dirname,+ '../../skills/create-mobile-app/SKILL.md',+ ), 'utf8');+ assert.match(+ createSkill,+ /foreground planning snapshot[\s\S]*never authorizes a write/,+ );+ assert.match(createSkill, /--reconcile-exact/);+ assert.match(+ createSkill,+ /one fresh bounded reconciliation[\s\S]*ordinary typed columns[\s\S]*relationships[\s\S]*alternate keys/,+ );+ assert.match(createSkill, /--bind-plan "\$SCHEMA_CONTRACT"/);+ assert.match(createSkill, /--approval-receipt "\$APPROVAL_RECEIPT"/);+ assert.match(+ createSkill,+ /receipt is missing, STOP as `BLOCKED`[\s\S]*must not synthesize it/,+ );+ const planner = fs.readFileSync(path.join(+ __dirname,+ '../../agents/native-app-planner.md',+ ), 'utf8');+ assert.match(+ planner,+ /Approved:[\s\S]*mobile-plan-status\.json[\s\S]*dataModel.*approval record/,+ );+ assert.match(+ planner,+ /Do not call the manifest builder to create or restamp this receipt/,+ );+});++test('publish checkpoint retries PublishXml after schema writes become idempotent', () => {+ const contract = createContract();+ const first = buildManifest(buildInputs(contract, basePlanningSnapshot()));+ assert.ok(first.publishCheckpoint);+ assert.deepEqual(first.publishCheckpoint.tables, ['cr1_category', 'cr1_item']);++ const appliedInputs = buildInputs(contract, fullyAppliedSnapshot());+ const retry = buildManifest({+ ...appliedInputs,+ publishCheckpoint: first.publishCheckpoint,+ });+ assert.deepEqual(+ retry.execution.phases.flatMap((phase) => phase.operations).map((item) => item.id),+ ['publish-customizations'],+ );+ assert.deepEqual(retry.publishCheckpoint, first.publishCheckpoint);++ const complete = buildManifest(appliedInputs);+ assert.equal(complete.publishCheckpoint, null);+ assert.equal(complete.summary.metadataOperationCount, 0);++ const mismatchedCheckpoint = structuredClone(first.publishCheckpoint);+ mismatchedCheckpoint.binding.environmentId = 'environment-2';+ delete mismatchedCheckpoint.integritySha256;+ mismatchedCheckpoint.integritySha256 = sha256(stableJson(mismatchedCheckpoint));+ assert.throws(+ () => buildManifest({ ...appliedInputs, publishCheckpoint: mismatchedCheckpoint }),+ /publish checkpoint environmentId mismatch/,+ );+});++test('collision checkpoint roll-forward preserves prior writes and rebinds revised aliases', () => {+ const priorInputs = buildInputs(createContract(), basePlanningSnapshot(), '# Prior plan\n');+ const priorManifest = buildManifest(priorInputs);+ const priorOperations = priorManifest.execution.phases.flatMap(+ (phase) => phase.operations,+ );+ const completedOperation = priorOperations.find(+ (operation) => operation.id === 'create-table:cr1_category',+ );+ const collisionOperation = priorOperations.find(+ (operation) => operation.id === 'create-table:cr1_item',+ );+ const journal = {+ schemaVersion: 1,+ binding: {+ environmentUrl: CONTEXT.environmentUrl,+ solution: CONTEXT.solutionUniqueName,+ },+ completed: {+ [operationFingerprint(completedOperation, CONTEXT.solutionUniqueName)]: {+ operationId: completedOperation.id,+ },+ },+ recoveries: [],+ inFlight: {+ index: collisionOperation.index,+ operationId: collisionOperation.id,+ fingerprint: operationFingerprint(+ collisionOperation,+ CONTEXT.solutionUniqueName,+ ),+ manifestHash: priorManifest.integritySha256,+ reconciliationHash: priorManifest.binding.reconciliationSha256,+ failure: {+ status: 400,+ collision: true,+ },+ },+ };+ const supersededFingerprint = 'f'.repeat(64);+ journal.completed[supersededFingerprint] = {+ operationId: 'create-table:older-collision',+ };+ journal.recoveries.push({+ fingerprint: supersededFingerprint,+ outcome: 'fresh-reconciliation-confirmed-superseded-collision',+ });++ const revisedContract = createContract();+ const revisedItem = revisedContract.tables.find(+ (tableValue) => tableValue.logicalName === 'cr1_item',+ );+ revisedItem.plannedDecision = 'adapt';+ revisedItem.adaptedLogicalName = 'cr1_itemv2';+ revisedItem.adaptedSchemaName = 'cr1_ItemV2';+ const revisedTables = fullyAppliedSnapshot().tables.filter(+ (tableValue) => tableValue.logicalName !== 'cr1_item',+ );+ const revisedSnapshot = snapshot({+ tables: revisedTables,+ exactUnavailable: ['cr1_deferred'],+ });+ const revisedInputs = buildInputs(+ revisedContract,+ revisedSnapshot,+ '# Revised plan\n',+ );+ const rolled = rollForwardPublishCheckpoint({+ checkpoint: priorManifest.publishCheckpoint,+ previousManifest: priorManifest,+ journal,+ contract: revisedInputs.contract,+ approvalReceipt: revisedInputs.approvalReceipt,+ contractBytes: revisedInputs.contractBytes,+ planBytes: revisedInputs.planBytes,+ context: CONTEXT,+ rolledAt: NOW,+ });++ assert.deepEqual(rolled.tables, ['cr1_category', 'cr1_itemv2']);+ assert.equal(rolled.binding.planSha256, sha256(revisedInputs.planBytes));+ assert.equal(+ rolled.binding.structuredSchemaSha256,+ sha256(revisedInputs.contractBytes),+ );+ assert.deepEqual(rolled.rollForwards[0].previousTables, [+ 'cr1_category',+ 'cr1_item',+ ]);+ assert.deepEqual(+ rolled.rollForwards[0].previousCheckpoint,+ priorManifest.publishCheckpoint,+ );+ assert.deepEqual(rolled.rollForwards[0].tableMappings, [{+ requestedName: 'cr1_item',+ from: 'cr1_item',+ to: 'cr1_itemv2',+ }]);++ const revisedManifest = buildManifest({+ ...revisedInputs,+ publishCheckpoint: rolled,+ });+ assert.deepEqual(revisedManifest.publishCheckpoint.rollForwards, rolled.rollForwards);+ assert.equal(+ revisedManifest.execution.phases[4].operations[0].body.ParameterXml+ .includes('<entity>cr1_item</entity>'),+ false,+ );+ assert.match(+ revisedManifest.execution.phases[4].operations[0].body.ParameterXml,+ /<entity>cr1_category<\/entity>.*<entity>cr1_itemv2<\/entity>/,+ );+ const erasedEvidence = structuredClone(rolled);+ erasedEvidence.rollForwards[0].previousCheckpoint.tables = ['cr1_item'];+ delete erasedEvidence.integritySha256;+ erasedEvidence.integritySha256 = sha256(stableJson(erasedEvidence));+ assert.throws(+ () => buildManifest({+ ...revisedInputs,+ publishCheckpoint: erasedEvidence,+ }),+ /previousCheckpoint integrity does not match|previousCheckpoint evidence does not match/,+ );++ const unsafeContract = structuredClone(revisedInputs.contract);+ unsafeContract.tables = unsafeContract.tables.filter(+ (tableValue) => tableValue.logicalName !== 'cr1_category',+ );+ const unsafeItem = unsafeContract.tables.find(+ (tableValue) => tableValue.logicalName === 'cr1_item',+ );+ unsafeItem.columns = unsafeItem.columns.filter(+ (columnValue) => columnValue.logicalName !== 'cr1_categoryid',+ );+ unsafeItem.relationships = [];+ const unsafeInputs = buildInputs(+ unsafeContract,+ revisedSnapshot,+ '# Revised plan\n',+ );+ assert.throws(+ () => rollForwardPublishCheckpoint({+ checkpoint: priorManifest.publishCheckpoint,+ previousManifest: priorManifest,+ journal,+ contract: unsafeInputs.contract,+ approvalReceipt: unsafeInputs.approvalReceipt,+ contractBytes: unsafeInputs.contractBytes,+ planBytes: unsafeInputs.planBytes,+ context: CONTEXT,+ rolledAt: NOW,+ }),+ /checkpoint table cr1_category is outside the revised contract without collision evidence/,+ );+});++test('checkpoint roll-forward rejects removed completed columns, relationships, and keys', () => {+ function expectCompletedComponentRejected({+ priorContract,+ reconciliation,+ completedId,+ collisionId,+ revise,+ }) {+ const priorInputs = buildInputs(priorContract, reconciliation, '# Prior component plan\n');+ const priorManifest = buildManifest(priorInputs);+ const operations = priorManifest.execution.phases.flatMap((phase) => phase.operations);+ const completedOperation = operations.find((item) => item.id === completedId);+ const collisionOperation = operations.find((item) => item.id === collisionId);+ assert.ok(completedOperation, completedId);+ assert.ok(collisionOperation, collisionId);+ const journal = {+ schemaVersion: 1,+ binding: {+ environmentUrl: CONTEXT.environmentUrl,+ solution: CONTEXT.solutionUniqueName,+ },+ completed: {+ [operationFingerprint(completedOperation, CONTEXT.solutionUniqueName)]: {+ operationId: completedOperation.id,+ },+ },+ recoveries: [],+ inFlight: {+ index: collisionOperation.index,+ operationId: collisionOperation.id,+ fingerprint: operationFingerprint(+ collisionOperation,+ CONTEXT.solutionUniqueName,+ ),+ manifestHash: priorManifest.integritySha256,+ reconciliationHash: priorManifest.binding.reconciliationSha256,+ failure: { status: 400, collision: true },+ },+ };+ const revisedContract = structuredClone(priorContract);+ revise(revisedContract);+ const revisedInputs = buildInputs(+ revisedContract,+ reconciliation,+ '# Revised component plan\n',+ );+ assert.throws(+ () => rollForwardPublishCheckpoint({+ checkpoint: priorManifest.publishCheckpoint,+ previousManifest: priorManifest,+ journal,+ contract: revisedInputs.contract,+ approvalReceipt: revisedInputs.approvalReceipt,+ contractBytes: revisedInputs.contractBytes,+ planBytes: revisedInputs.planBytes,+ context: CONTEXT,+ rolledAt: NOW,+ }),+ new RegExp(`completed metadata component ${completedId} was removed or changed`),+ );+ }++ const extensionContract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [contractTable('cr1_item', 'extend', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_a', 'string', 'create'),+ contractColumn('cr1_b', 'string', 'create'),+ ])],+ };+ const existingItem = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ expectCompletedComponentRejected({+ priorContract: extensionContract,+ reconciliation: snapshot({ tables: [existingItem] }),+ completedId: 'extend-column:cr1_item:cr1_a',+ collisionId: 'extend-column:cr1_item:cr1_b',+ revise: (contract) => {+ contract.tables[0].columns = contract.tables[0].columns.filter(+ (item) => item.logicalName !== 'cr1_a',+ );+ const collisionColumn = contract.tables[0].columns.find(+ (item) => item.logicalName === 'cr1_b',+ );+ collisionColumn.plannedDecision = 'adapt';+ collisionColumn.adaptedLogicalName = 'cr1_bv2';+ collisionColumn.adaptedSchemaName = 'cr1_BV2';+ },+ });++ const relationshipContract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ], {+ relationships: [{+ kind: 'many-to-many',+ schemaName: 'cr1_Item_Tag',+ plannedDecision: 'create',+ entity1: 'cr1_item',+ entity2: 'cr1_tag',+ intersectTable: 'cr1_item_tag',+ }, {+ kind: 'many-to-many',+ schemaName: 'cr1_Item_Category',+ plannedDecision: 'create',+ entity1: 'cr1_item',+ entity2: 'cr1_category',+ intersectTable: 'cr1_item_category',+ }],+ }),+ contractTable('cr1_category', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ contractTable('cr1_tag', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ ],+ };+ const relationshipSnapshot = snapshot({+ tables: [+ table('cr1_item', [column('cr1_name', 'String', { primaryName: true })]),+ table('cr1_category', [column('cr1_name', 'String', { primaryName: true })]),+ table('cr1_tag', [column('cr1_name', 'String', { primaryName: true })]),+ ],+ });+ expectCompletedComponentRejected({+ priorContract: relationshipContract,+ reconciliation: relationshipSnapshot,+ completedId: 'create-relationship:cr1_item_category',+ collisionId: 'create-relationship:cr1_item_tag',+ revise: (contract) => {+ contract.tables[0].relationships = contract.tables[0].relationships.filter(+ (item) => item.schemaName !== 'cr1_Item_Category',+ );+ const collisionRelationship = contract.tables[0].relationships[0];+ collisionRelationship.plannedDecision = 'adapt';+ collisionRelationship.adaptedSchemaName = 'cr1_Item_Tag_v2';+ collisionRelationship.adaptedIntersectTable = 'cr1_item_tag_v2';+ },+ });++ const keyContract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [contractTable('cr1_item', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ contractColumn('cr1_code', 'string', 'reuse'),+ ], {+ alternateKeys: [{+ schemaName: 'cr1_item_code_key_a',+ plannedDecision: 'create',+ columns: ['cr1_code'],+ }, {+ schemaName: 'cr1_item_code_key_b',+ plannedDecision: 'create',+ columns: ['cr1_code'],+ }],+ })],+ };+ const keySnapshot = snapshot({+ tables: [table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ column('cr1_code', 'String'),+ ])],+ });+ expectCompletedComponentRejected({+ priorContract: keyContract,+ reconciliation: keySnapshot,+ completedId: 'create-key:cr1_item:cr1_item_code_key_a',+ collisionId: 'create-key:cr1_item:cr1_item_code_key_b',+ revise: (contract) => {+ contract.tables[0].alternateKeys =+ contract.tables[0].alternateKeys.filter(+ (item) => item.schemaName !== 'cr1_item_code_key_a',+ );+ contract.tables[0].alternateKeys[0].plannedDecision = 'adapt';+ contract.tables[0].alternateKeys[0].adaptedSchemaName =+ 'cr1_item_code_key_b_v2';+ },+ });+});++test('CLI cannot self-mint approval receipts and still enforces publish checkpoints', (t) => {+ const directory = fs.mkdtempSync(path.join(__dirname, '.manifest-scratch-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const planContent = '# Plan\n';+ const contract = normalizedContract(createContract());+ const prepared = buildInputs(contract, basePlanningSnapshot(), planContent);+ const reconciliation = prepared.reconciliation;+ const files = {+ contract: path.join(directory, 'contract.json'),+ approvalReceipt: path.join(directory, 'mobile-plan-status.json'),+ selfMintedReceipt: path.join(directory, 'self-minted-receipt.json'),+ reconciliation: path.join(directory, 'reconciliation.json'),+ plan: path.join(directory, 'plan.md'),+ manifest: path.join(directory, 'manifest.json'),+ checkpoint: path.join(directory, 'publish.json'),+ };+ fs.writeFileSync(files.contract, stableJson(contract));+ fs.writeFileSync(files.approvalReceipt, stableJson(prepared.approvalReceipt));+ fs.writeFileSync(files.reconciliation, JSON.stringify(reconciliation, null, 2));+ fs.writeFileSync(files.plan, planContent);+ const script = path.join(__dirname, '../build-dataverse-operation-manifest.js');+ assert.equal(+ require('../build-dataverse-operation-manifest').createApprovalEnvelope,+ undefined,+ );+ const selfMint = spawnSync(process.execPath, [+ script,+ '--create-approval-envelope', files.contract,+ '--plan', files.plan,+ '--output', files.selfMintedReceipt,+ ], { encoding: 'utf8' });+ assert.equal(selfMint.status, 1);+ assert.equal(fs.existsSync(files.selfMintedReceipt), false);+ assert.doesNotMatch(selfMint.stderr, /create approval receipt|create approval envelope/i);+ const bound = spawnSync(process.execPath, [+ script,+ '--bind-plan', files.contract,+ '--approval-receipt', files.approvalReceipt,+ '--plan', files.plan,+ '--output', files.contract,+ ], { encoding: 'utf8' });+ assert.equal(bound.status, 0, bound.stderr);+ assert.equal(+ JSON.parse(fs.readFileSync(files.contract, 'utf8')).approvedPlanSha256,+ sha256(Buffer.from(planContent)),+ );+ const commonArgs = [+ '--contract', files.contract,+ '--approval-receipt', files.approvalReceipt,+ '--reconciliation', files.reconciliation,+ '--plan', files.plan,+ '--environment-id', CONTEXT.environmentId,+ '--env-url', CONTEXT.environmentUrl,+ '--tenant-id', CONTEXT.tenantId,+ '--publisher-prefix', CONTEXT.publisherPrefix,+ '--solution', CONTEXT.solutionUniqueName,+ '--publish-checkpoint', files.checkpoint,+ '--now', NOW,+ ];+ const built = spawnSync(process.execPath, [+ script,+ ...commonArgs,+ '--output', files.manifest,+ ], { encoding: 'utf8' });+ assert.equal(built.status, 0, built.stderr);+ const manifest = JSON.parse(fs.readFileSync(files.manifest, 'utf8'));+ const checkpoint = JSON.parse(fs.readFileSync(files.checkpoint, 'utf8'));+ assert.deepEqual(checkpoint, manifest.publishCheckpoint);++ fs.rmSync(files.checkpoint);+ const validation = spawnSync(process.execPath, [+ script,+ ...commonArgs,+ '--validate', files.manifest,+ '--require-executable',+ ], { encoding: 'utf8' });+ assert.equal(validation.status, 1);+ assert.match(validation.stderr, /persisted publish checkpoint is required/);+});++test('M:N adapt reruns match effective schema and intersect names', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ], {+ relationships: [{+ kind: 'many-to-many',+ schemaName: 'cr1_Item_Tag',+ adaptedSchemaName: 'cr1_Item_Tag_v2',+ plannedDecision: 'adapt',+ entity1: 'cr1_item',+ entity2: 'cr1_tag',+ intersectTable: 'cr1_item_tag',+ adaptedIntersectTable: 'cr1_item_tag_v2',+ serviceRequired: true,+ }],+ }),+ contractTable('cr1_tag', 'reuse', 0, [+ contractColumn('cr1_name', 'string', 'reuse', { primaryName: true }),+ ]),+ ],+ };+ const item = table('cr1_item', [+ column('cr1_name', 'String', { primaryName: true }),+ ], {+ manyToManyRelationships: [{+ schemaName: 'cr1_Item_Tag_v2',+ entity1: 'cr1_item',+ entity2: 'cr1_tag',+ intersectTable: 'cr1_item_tag_v2',+ managed: false,+ }],+ });+ const tag = table('cr1_tag', [+ column('cr1_name', 'String', { primaryName: true }),+ ]);+ const manifest = buildManifest(buildInputs(contract, snapshot({ tables: [item, tag] })));++ assert.equal(+ manifest.decisions.find((decision) => decision.itemType === 'relationship').decision,+ 'adapt',+ );+ assert.equal(manifest.execution.phases[2].operations.length, 0);+ assert.deepEqual(+ manifest.service.requiredTables.map((item) => item.logicalName),+ ['cr1_item', 'cr1_item_tag_v2', 'cr1_tag'],+ );+});++test('BigInt payload omits unsafe default bounds and accepts only explicit safe bounds', () => {+ const contract = {+ schemaVersion: 1,+ publisherPrefix: 'cr1',+ tables: [+ contractTable('cr1_item', 'create', 0, [+ contractColumn('cr1_name', 'string', 'create', { primaryName: true }),+ contractColumn('cr1_count', 'bigint', 'create'),+ ]),+ ],+ };+ const manifest = buildManifest(buildInputs(contract, snapshot({+ proposedMissing: ['cr1_item'],+ })));+ const bigIntBody = manifest.execution.phases[0].operations[0].body.Attributes+ .find((attribute) => attribute.SchemaName === 'cr1_count');+ assert.equal(Object.hasOwn(bigIntBody, 'MinValue'), false);+ assert.equal(Object.hasOwn(bigIntBody, 'MaxValue'), false);++ const unsafe = structuredClone(contract);+ unsafe.tables[0].columns[1].maxValue = Number.MAX_SAFE_INTEGER + 1;+ assert.throws(+ () => buildManifest(buildInputs(unsafe, snapshot({ proposedMissing: ['cr1_item'] }))),+ /maxValue must be a safely representable integer/,+ );+});++test('deterministic local manifest preparation remains sub-second for a typical plan', () => {+ const inputs = buildInputs(createContract(), basePlanningSnapshot());+ const started = process.hrtime.bigint();+ for (let index = 0; index < 100; index += 1) buildManifest(inputs);+ const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;++ assert.ok(+ elapsedMs < 1000,+ `expected 100 deterministic local preparations under 1000ms, got ${elapsedMs.toFixed(1)}ms`,+ );+});diff --git a/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.jsnew file mode 100644index 000000000..fe90557a5--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.js@@ -0,0 +1,52 @@+'use strict';++const assert = require('node:assert/strict');+const test = require('node:test');++const {+ REQUIREMENT_SETS,+ renderBenchmarkMarkdown,+ runBenchmark,+} = require('../benchmark-dataverse-planning');++test('fixture benchmark covers wildlife and an unrelated laboratory workflow', async () => {+ const result = await runBenchmark();+ assert.equal(result.scenarios.length, 2);+ assert.deepEqual(+ result.scenarios.map((scenario) => scenario.id),+ ['wildlife-rehabilitation', 'laboratory-chain-of-custody'],+ );+ for (const scenario of result.scenarios) {+ assert.equal(scenario.requiredConceptCount, 5);+ assert.ok(scenario.selectedCandidateCount >= 5);+ assert.equal(scenario.detailedCandidateBreakdown.required, 0);+ assert.equal(scenario.detailedCandidateBreakdown.advisory, 5);+ assert.equal(scenario.detailedCandidateBreakdown.exactCoveredConcepts, 0);+ assert.equal(scenario.detailedCandidateBreakdown.advisoryLimit, 40);+ assert.equal(scenario.metadataRequests.snapshotFirstAgentRequests, 0);+ assert.ok(scenario.metadataRequests.snapshotForegroundRequests > 0);+ assert.equal(scenario.outputCompleteness.percent, 100);+ assert.deepEqual(scenario.outputCompleteness.checks, {+ candidateSelection: true,+ relationshipExtraction: true,+ computedExtraction: true,+ proposedNameChecks: true,+ evidenceOutput: true,+ });+ assert.ok(scenario.evidenceCharacters > 0);+ assert.ok(scenario.elapsedLocalProcessingMs >= 0);+ }+});++test('benchmark report is explicit about real fixture execution and A/B limitations', async () => {+ const markdown = renderBenchmarkMarkdown(await runBenchmark(REQUIREMENT_SETS));+ assert.match(markdown, /Wildlife rehabilitation/);+ assert.match(markdown, /Laboratory sample chain-of-custody/);+ assert.match(markdown, /Foreground fixture requests/);+ assert.match(markdown, /Required \/ advisory/);+ assert.match(markdown, /Exact-covered concepts/);+ assert.match(markdown, /Snapshot-first agent requests/);+ assert.match(markdown, /real snapshot candidate selection/);+ assert.match(markdown, /Matched agent A\/B runs are still required/);+ assert.match(markdown, /matched agent A\/B decision and timing runs/);+});diff --git a/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.jsnew file mode 100644index 000000000..697a7b2aa--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js@@ -0,0 +1,1091 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const {+ analyzeProposedNames,+ atomicWriteFile,+ canonicalAttributeType,+ createCliRequest,+ createReconciliationSnapshot,+ createSnapshot,+ expandSnapshot,+ loadDetailedEntity,+ normalizedTokens,+ parseArgs,+ rankCandidatesByConcept,+ selectDetailedCandidates,+ selectDetailedEntities,+ singularizeToken,+ validateSnapshot,+} = require('../create-dataverse-snapshot');+const { renderPlanningEvidence } = require('../render-dataverse-planning-evidence');++function label(value) {+ return { UserLocalizedLabel: { Label: value } };+}++test('canonicalizes Dataverse virtual File and Image attribute types', () => {+ assert.equal(canonicalAttributeType('Virtual', { Value: 'FileType' }), 'File');+ assert.equal(canonicalAttributeType('Virtual', { Value: 'ImageType' }), 'Image');+ assert.equal(canonicalAttributeType('Virtual', { Value: 'StringType' }), 'Virtual');+ assert.equal(canonicalAttributeType('String', { Value: 'StringType' }), 'String');+});++function entity(logicalName, displayName, overrides = {}) {+ return {+ LogicalName: logicalName,+ SchemaName: logicalName,+ EntitySetName: `${logicalName}s`,+ DisplayName: label(displayName),+ DisplayCollectionName: label(`${displayName}s`),+ Description: label(`${displayName} records`),+ PrimaryIdAttribute: `${logicalName}id`,+ PrimaryNameAttribute: `${logicalName}name`,+ OwnershipType: 'UserOwned',+ HasActivities: false,+ HasNotes: false,+ IsAvailableOffline: true,+ ChangeTrackingEnabled: true,+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ CanBePrimaryEntityInRelationship: { Value: true },+ CanBeRelatedEntityInRelationship: { Value: true },+ CanBeInManyToMany: { Value: true },+ ...overrides,+ };+}++function normalizeInventoryForTest(value) {+ return {+ logicalName: value.LogicalName,+ schemaName: value.SchemaName,+ displayName: value.DisplayName.UserLocalizedLabel.Label,+ displayCollectionName: value.DisplayCollectionName.UserLocalizedLabel.Label,+ description: value.Description.UserLocalizedLabel.Label,+ entitySetName: value.EntitySetName,+ primaryIdAttribute: value.PrimaryIdAttribute,+ primaryNameAttribute: value.PrimaryNameAttribute,+ ownershipType: value.OwnershipType,+ hasActivities: value.HasActivities,+ hasNotes: value.HasNotes,+ isAvailableOffline: value.IsAvailableOffline,+ changeTrackingEnabled: value.ChangeTrackingEnabled,+ customEntity: value.IsCustomEntity,+ managed: value.IsManaged,+ customizable: value.IsCustomizable.Value,+ canCreateAttributes: value.CanCreateAttributes.Value,+ canBePrimaryEntityInRelationship: value.CanBePrimaryEntityInRelationship.Value,+ canBeRelatedEntityInRelationship: value.CanBeRelatedEntityInRelationship.Value,+ canBeInManyToMany: value.CanBeInManyToMany.Value,+ };+}++function projectScratch(t) {+ const directory = fs.mkdtempSync(path.join(__dirname, '.scratch-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ return directory;+}++function validSnapshotBase(overrides = {}) {+ const snapshot = {+ version: 3,+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ generatedAt: '2026-08-18T05:00:00.000Z',+ inputs: { concepts: [], explicitTableNames: [], proposedTableNames: [] },+ inventory: [],+ candidateRanking: [],+ selectedCandidateEvidence: [],+ tables: [],+ detailLoadFailures: [],+ proposedNameChecks: { checked: [], collisions: [], missing: [] },+ exactNameResolution: {+ requestedTables: [],+ loadedTables: [],+ unavailableTables: [],+ },+ timings: {+ inventoryRetrievalMs: 20,+ candidateSelectionMs: 2,+ detailLoadingMs: 0,+ totalDurationMs: 22,+ },+ ...overrides,+ };+ snapshot.inventoryFacts = overrides.inventoryFacts || {+ customizableTables: snapshot.inventory.length,+ exactNameTables: 0,+ requiredExactNameTables: 0,+ proposedCollisionTables: snapshot.proposedNameChecks.collisions.length,+ totalTables: snapshot.inventory.length,+ };+ snapshot.detailLoadSummary = overrides.detailLoadSummary || {+ attemptedCandidates: snapshot.tables.length + snapshot.detailLoadFailures.length,+ loadedCandidates: snapshot.tables.length,+ failedCandidates: snapshot.detailLoadFailures.length,+ };+ return snapshot;+}++test('concept ranking normalizes plurals and maps workflow families', () => {+ assert.equal(singularizeToken('activities'), 'activity');+ assert.equal(singularizeToken('batches'), 'batch');+ assert.deepEqual(normalizedTokens('Medical assessments'), ['medical', 'assessment']);++ const rankings = rankCandidatesByConcept([+ entity('wr_medicalassessment', 'Medical Assessment'),+ entity('wr_careactivity', 'Care Activity'),+ ], ['medical assessments', 'care activities']);++ assert.equal(rankings[0].candidates[0].logicalName, 'wr_medicalassessment');+ assert.equal(rankings[1].candidates[0].logicalName, 'wr_careactivity');+});++test('CLI parsing preserves intentionally empty optional lists', () => {+ assert.deepEqual(+ parseArgs(['node', 'script', '--tables', '', '--json']),+ { tables: '', json: true },+ );+});++test('selection prefers shortest unversioned tables in the best publisher family', () => {+ const entities = [+ entity('new_product', 'Product'),+ entity('new_productv2', 'Product'),+ entity('twd_product', 'Product'),+ entity('new_batch', 'Batch'),+ ];+ const rankings = rankCandidatesByConcept(entities, ['products', 'batches']);+ const productRanking = rankings.find((item) => item.concept === 'products');+ assert.equal(productRanking.preferredPublisherFamily, 'new');+ assert.equal(productRanking.candidates[0].logicalName, 'new_product');+ assert.equal(productRanking.candidates.find((item) => item.logicalName === 'new_productv2').versioned, true);++ const selected = selectDetailedEntities(entities, [], ['products', 'batches'])+ .map((item) => item.LogicalName);+ assert.deepEqual(selected, ['new_batch', 'new_product']);+});++test('explicit table names are always included when present', () => {+ const entities = [+ entity('new_product', 'Product'),+ entity('new_unrelatedaudit', 'Audit Ledger'),+ ];+ const selected = selectDetailedEntities(+ entities,+ ['new_unrelatedaudit'],+ ['products'],+ ).map((item) => item.LogicalName);+ assert.deepEqual(selected, ['new_product', 'new_unrelatedaudit']);+});++test('exact-covered concepts suppress unnecessary advisory alternatives', () => {+ const selection = selectDetailedCandidates([+ entity('new_product', 'Product'),+ entity('other_product', 'Product'),+ ], ['new_product'], ['products']);++ assert.deepEqual(+ selection.selectedEntities.map((item) => item.LogicalName),+ ['new_product'],+ );+ assert.deepEqual(selection.detailSelectionSummary, {+ requiredCandidates: 1,+ advisoryCandidates: 0,+ exactCoveredConcepts: 1,+ unresolvedConcepts: 0,+ advisoryLimit: 40,+ });+});++test('advisory allocation covers every concept before adding alternatives', () => {+ const concepts = Array.from({ length: 20 }, (_, index) => `domain${index}`);+ const entities = concepts.flatMap((concept) => [+ entity(`new_${concept}`, concept),+ entity(`new_${concept}detail`, concept),+ entity(`new_${concept}log`, concept),+ ]);+ const selection = selectDetailedCandidates(entities, [], concepts);+ const selected = new Set(selection.selectedEntities.map((item) => item.LogicalName));++ assert.equal(selection.detailSelectionSummary.advisoryCandidates, 40);+ for (const concept of concepts) {+ assert.ok(selected.has(`new_${concept}`), `${concept} should keep its best candidate`);+ }+});++test('one-per-concept quality coverage may exceed the advisory target', () => {+ const concepts = Array.from({ length: 45 }, (_, index) => `workflow${index}`);+ const selection = selectDetailedCandidates(+ concepts.map((concept) => entity(`new_${concept}`, concept)),+ [],+ concepts,+ );++ assert.equal(selection.detailSelectionSummary.advisoryCandidates, 45);+ assert.equal(selection.detailSelectionSummary.advisoryLimit, 45);+ assert.equal(selection.selectedEntities.length, 45);+});++test('proposed logical-name checks distinguish collisions and missing names', () => {+ const result = analyzeProposedNames(+ [entity('new_product', 'Product')],+ ['new_product', 'new_inventoryreview'],+ );+ assert.deepEqual(result.collisions.map((item) => item.logicalName), ['new_product']);+ assert.deepEqual(result.missing, ['new_inventoryreview']);+ assert.equal(result.checked[0].status, 'missing');+ assert.equal(result.checked[1].status, 'collision');+});++test('fresh reconciliation is bounded to exact approved names and reloads full metadata', async () => {+ const calls = [];+ const reconciliation = await createReconciliationSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['new_product', 'new_missing'],+ proposedTableNames: ['new_missing'],+ nowIso: () => '2026-08-19T00:00:00.000Z',+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('new_product', 'Product')] } };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [{+ MetadataId: 'name-id',+ LogicalName: 'new_name',+ SchemaName: 'new_Name',+ AttributeType: 'String',+ AttributeTypeName: { Value: 'StringType' },+ RequiredLevel: { Value: 'None' },+ IsPrimaryName: true,+ SourceType: 0,+ }] } };+ }+ if (apiPath.includes('StringAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_name',+ MaxLength: 200,+ FormatName: { Value: 'Text' },+ }] } };+ }+ if (apiPath.includes('/ManyToOneRelationships?')) {+ return { status: 200, data: { value: [{+ SchemaName: 'new_Category_Product',+ ReferencingAttribute: 'new_categoryid',+ ReferencedEntity: 'new_category',+ ReferencedAttribute: 'new_categoryid',+ IsManaged: false,+ CascadeConfiguration: {+ Assign: 'NoCascade',+ Delete: 'RemoveLink',+ Merge: 'NoCascade',+ Reparent: 'NoCascade',+ Share: 'NoCascade',+ Unshare: 'NoCascade',+ RollupView: 'NoCascade',+ },+ }] } };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.equal(reconciliation.purpose, 'execution-reconciliation');+ assert.deepEqual(reconciliation.reconciliation, {+ boundedExactNames: true,+ fullInventoryRead: false,+ tables: ['new_missing', 'new_product'],+ proposedNames: ['new_missing'],+ });+ assert.deepEqual(reconciliation.exactNameResolution, {+ requestedTables: ['new_missing', 'new_product'],+ loadedTables: ['new_product'],+ unavailableTables: ['new_missing'],+ });+ assert.equal(+ calls.some((apiPath) => apiPath.includes('IsCustomizable/Value eq true')),+ false,+ );+ assert.equal(+ calls.filter((apiPath) => apiPath.includes('/Attributes?$select=')).length,+ 1,+ );+ assert.match(calls[0], /CanBePrimaryEntityInRelationship/);+ assert.match(calls[0], /CanBeRelatedEntityInRelationship/);+ assert.match(calls[0], /CanBeInManyToMany/);+ assert.match(calls[0], /OwnershipType/);+ assert.match(calls[0], /HasActivities/);+ assert.match(calls[0], /HasNotes/);+ assert.match(calls[0], /IsAvailableOffline/);+ assert.match(calls[0], /ChangeTrackingEnabled/);+ assert.equal(reconciliation.tables[0].canBeRelatedEntityInRelationship, true);+ assert.equal(reconciliation.tables[0].ownershipType, 'UserOwned');+ assert.equal(reconciliation.tables[0].isAvailableOffline, true);+ assert.match(+ calls.find((apiPath) => apiPath.includes('/ManyToOneRelationships?')),+ /CascadeConfiguration/,+ );+ assert.equal(+ reconciliation.tables[0].manyToOneRelationships[0]+ .cascadeConfiguration.Delete,+ 'RemoveLink',+ );+});++test('proposed names are collision checks and stay out of required exact-name loading', async () => {+ const calls = [];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ proposedTableNames: ['new_product', 'new_missing'],+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.includes('IsCustomizable/Value eq true')) {+ return { status: 200, data: { value: [] } };+ }+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('new_product', 'Product')] } };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(snapshot.exactNameResolution, {+ requestedTables: [],+ loadedTables: [],+ unavailableTables: [],+ });+ assert.deepEqual(snapshot.proposedNameChecks.missing, ['new_missing']);+ assert.deepEqual(+ snapshot.proposedNameChecks.collisions.map((item) => item.logicalName),+ ['new_product'],+ );+ assert.deepEqual(snapshot.tables, []);+ assert.deepEqual(snapshot.detailLoadSummary, {+ attemptedCandidates: 0,+ loadedCandidates: 0,+ failedCandidates: 0,+ requiredCandidates: 0,+ advisoryCandidates: 0,+ exactCoveredConcepts: 0,+ unresolvedConcepts: 0,+ advisoryLimit: 40,+ });+ assert.equal(calls.some((apiPath) => apiPath.includes('/Attributes?$select=')), false);+});++test('unreadable exact-name metadata fails closed instead of reporting absence', async () => {+ await assert.rejects(+ createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['contact'],+ request: async (_method, apiPath) => {+ if (apiPath.includes('IsCustomizable/Value eq true')) {+ return { status: 200, data: { value: [] } };+ }+ return { status: 403, error: 'metadata forbidden' };+ },+ }),+ /Exact-name table metadata failed \(403\): metadata forbidden/,+ );+});++test('advisory candidate detail failure is recorded and does not abort the snapshot', async () => {+ const progress = [];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: ['activities', 'products'],+ onProgress: (event) => progress.push(event),+ request: async (_method, apiPath) => {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return {+ status: 200,+ data: {+ value: [+ entity('activitypointer', 'Activity'),+ entity('new_product', 'Product'),+ ],+ },+ };+ }+ if (apiPath.includes("EntityDefinitions(LogicalName='activitypointer')/Attributes?")) {+ return { status: 400, error: 'abstract metadata type is unsupported' };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(snapshot.tables.map((table) => table.logicalName), ['new_product']);+ assert.deepEqual(snapshot.detailLoadSummary, {+ attemptedCandidates: 2,+ loadedCandidates: 1,+ failedCandidates: 1,+ requiredCandidates: 0,+ advisoryCandidates: 2,+ exactCoveredConcepts: 0,+ unresolvedConcepts: 2,+ advisoryLimit: 40,+ });+ assert.deepEqual(snapshot.detailLoadFailures, [{+ logicalName: 'activitypointer',+ selectionReasons: ['concept:activities'],+ status: 400,+ error: 'abstract metadata type is unsupported',+ required: false,+ }]);+ const detailProgress = progress.find((event) => event.milestoneId === 'details-loaded');+ assert.deepEqual({+ attempted: detailProgress.attemptedDetailedCandidates,+ loaded: detailProgress.loadedDetailedCandidates,+ failed: detailProgress.failedDetailedCandidates,+ }, { attempted: 2, loaded: 1, failed: 1 });+ const failedCandidate = snapshot.candidateRanking+ .flatMap((ranking) => ranking.candidates)+ .find((candidate) => candidate.logicalName === 'activitypointer');+ assert.equal(failedCandidate.detailed, false);+ assert.equal(failedCandidate.detailStatus, 'unavailable');+ assert.deepEqual(failedCandidate.detailFailure, snapshot.detailLoadFailures[0]);+ assert.equal(validateSnapshot(snapshot).valid, true);++ const malformed = JSON.parse(JSON.stringify(snapshot));+ malformed.detailLoadFailures[0].status = '400';+ assert.deepEqual(validateSnapshot(malformed), {+ valid: false,+ errors: ['detailLoadFailures[0].status must be null or an HTTP status integer'],+ });+});++test('explicit candidate detail failure remains required and throws', async () => {+ await assert.rejects(+ createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['activitypointer'],+ concepts: ['activities'],+ request: async (_method, apiPath) => {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('activitypointer', 'Activity')] } };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 400, error: 'abstract metadata type is unsupported' };+ }+ return { status: 200, data: { value: [] } };+ },+ }),+ /activitypointer attributes failed \(400\): abstract metadata type is unsupported/,+ );+});++test('lookup sub-metadata failure skips advisory tables and blocks required tables', async () => {+ const request = async (_method, apiPath) => {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('new_product', 'Product')] } };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [{+ MetadataId: 'lookup-id',+ LogicalName: 'new_categoryid',+ SchemaName: 'new_CategoryId',+ AttributeType: 'Lookup',+ AttributeTypeName: { Value: 'LookupType' },+ SourceType: 0,+ }] } };+ }+ if (apiPath.includes('LookupAttributeMetadata')) {+ return { status: 404, error: 'lookup metadata unavailable' };+ }+ return { status: 200, data: { value: [] } };+ };++ const advisory = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: ['products'],+ request,+ });+ assert.deepEqual(advisory.tables, []);+ assert.equal(advisory.detailLoadFailures[0].logicalName, 'new_product');+ assert.match(advisory.detailLoadFailures[0].error, /lookup metadata unavailable/);++ await assert.rejects(+ createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['new_product'],+ request,+ }),+ /new_product lookup metadata failed \(404\): lookup metadata unavailable/,+ );+});++test('snapshot captures detailed metadata, evidence, and timing shape without network access', async () => {+ const calls = [];+ const clock = [100, 140, 150, 210, 215];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com/',+ tenantId: 'tenant-1',+ tableNames: ['new_product'],+ proposedTableNames: ['new_product', 'new_missing'],+ concepts: ['products'],+ nowMs: () => clock.shift(),+ nowIso: () => '2026-08-18T05:00:00.000Z',+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('new_product', 'Product')] } };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [+ {+ MetadataId: 'name-id',+ LogicalName: 'new_name',+ SchemaName: 'new_Name',+ AttributeType: 'String',+ AttributeTypeName: { Value: 'StringType' },+ RequiredLevel: { Value: 'ApplicationRequired' },+ IsCustomAttribute: true,+ IsCustomizable: { Value: true },+ IsPrimaryName: true,+ IsValidForCreate: true,+ IsValidForRead: true,+ IsValidForUpdate: true,+ SourceType: 0,+ },+ {+ MetadataId: 'category-id',+ LogicalName: 'new_categoryid',+ SchemaName: 'new_CategoryId',+ AttributeType: 'Lookup',+ AttributeTypeName: { Value: 'LookupType' },+ IsCustomizable: { Value: true },+ SourceType: 0,+ },+ {+ MetadataId: 'status-id',+ LogicalName: 'new_status',+ SchemaName: 'new_Status',+ AttributeType: 'Picklist',+ AttributeTypeName: { Value: 'PicklistType' },+ IsCustomizable: { Value: true },+ SourceType: 0,+ },+ {+ MetadataId: 'total-id',+ LogicalName: 'new_total',+ SchemaName: 'new_Total',+ AttributeType: 'Decimal',+ AttributeTypeName: { Value: 'DecimalType' },+ IsCustomizable: { Value: true },+ SourceType: 3,+ SourceTypeMask: 4,+ },+ ] } };+ }+ if (apiPath.includes('/ManyToOneRelationships?')) {+ return { status: 200, data: { value: [{+ SchemaName: 'new_Product_Category',+ ReferencingAttribute: 'new_categoryid',+ ReferencedEntity: 'new_category',+ ReferencedAttribute: 'new_categoryid',+ }] } };+ }+ if (apiPath.includes('/OneToManyRelationships?')+ || apiPath.includes('/ManyToManyRelationships?')) {+ return { status: 200, data: { value: [] } };+ }+ if (apiPath.includes('/Keys?')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_product_key',+ SchemaName: 'new_ProductKey',+ KeyAttributes: ['new_name'],+ EntityKeyIndexStatus: 'Active',+ }] } };+ }+ if (apiPath.includes('PicklistAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_status',+ OptionSet: { Options: [{+ Value: 1,+ Label: label('Active'),+ }] },+ }] } };+ }+ if (apiPath.includes('LookupAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_categoryid',+ Targets: ['new_category'],+ }] } };+ }+ if (apiPath.includes('/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_name',+ MaxLength: 160,+ Format: 'Text',+ FormatName: { Value: 'Text' },+ }] } };+ }+ if (apiPath.includes('/Attributes/Microsoft.Dynamics.CRM.DecimalAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_total',+ MinValue: -100000,+ MaxValue: 100000,+ Precision: 2,+ }] } };+ }+ if (apiPath.includes('Attributes(total-id)')) {+ return {+ status: 200,+ data: {+ LogicalName: 'new_total',+ SourceType: 3,+ SourceTypeMask: '4',+ FormulaDefinition: 'new_quantity * new_price',+ },+ };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(snapshot.timings, {+ inventoryRetrievalMs: 40,+ candidateSelectionMs: 10,+ detailLoadingMs: 60,+ totalDurationMs: 115,+ });+ assert.deepEqual(snapshot.proposedNameChecks.missing, ['new_missing']);+ assert.equal(snapshot.proposedNameChecks.collisions[0].logicalName, 'new_product');+ assert.equal(snapshot.tables[0].facts.columnCount, 4);+ assert.equal(snapshot.tables[0].facts.relationshipCount, 1);+ assert.equal(snapshot.tables[0].facts.keyCount, 1);+ assert.deepEqual(snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_categoryid',+ ).lookupTargets, ['new_category']);+ assert.deepEqual(snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_status',+ ).choices, [{ value: 1, label: 'Active' }]);+ assert.deepEqual(+ {+ maxLength: snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_name',+ ).maxLength,+ formatName: snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_name',+ ).formatName,+ },+ { maxLength: 160, formatName: 'Text' },+ );+ assert.deepEqual(+ {+ minValue: snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_total',+ ).minValue,+ maxValue: snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_total',+ ).maxValue,+ precision: snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_total',+ ).precision,+ },+ { minValue: -100000, maxValue: 100000, precision: 2 },+ );+ assert.equal(snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_total',+ ).computed.formula, 'new_quantity * new_price');+ assert.deepEqual(snapshot.tables[0].columns.find(+ (column) => column.logicalName === 'new_total',+ ).computed, {+ sourceType: 3,+ sourceTypeMask: 4,+ formulaDefinition: 'new_quantity * new_price',+ metadataStatus: 'available',+ unavailableReason: null,+ formula: 'new_quantity * new_price',+ attributeOf: null,+ });+ assert.deepEqual(snapshot.exactNameResolution, {+ requestedTables: ['new_product'],+ loadedTables: ['new_product'],+ unavailableTables: [],+ });+ assert.equal(validateSnapshot(snapshot, {+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ }).valid, true);+ assert.equal(calls.filter((apiPath) => (+ apiPath.startsWith('EntityDefinitions?') && apiPath.includes('IsCustomizable/Value eq true')+ )).length, 1);+ assert.equal(calls.filter((apiPath) => (+ apiPath.startsWith('EntityDefinitions?') && apiPath.includes("LogicalName eq 'new_missing'")+ )).length, 1);+ assert.equal(calls.some((apiPath) => (+ apiPath.includes("EntityDefinitions(LogicalName='new_missing')/Attributes?")+ )), false);+});++test('snapshot validation rejects missing decision evidence', () => {+ const snapshot = validSnapshotBase();+ for (const field of [+ 'generatedAt',+ 'inventoryFacts',+ 'proposedNameChecks',+ 'exactNameResolution',+ 'detailLoadSummary',+ ]) {+ const malformed = { ...snapshot };+ delete malformed[field];+ assert.equal(validateSnapshot(malformed).valid, false, field);+ }+});++test('exact-name expansion reuses inventory and performs no broad discovery request', async () => {+ const calls = [];+ const base = validSnapshotBase({+ inputs: { concepts: ['products'], explicitTableNames: [], proposedTableNames: [] },+ inventory: [{+ logicalName: 'new_product',+ schemaName: 'new_product',+ displayName: 'Product',+ displayCollectionName: 'Products',+ description: 'Product records',+ entitySetName: 'new_products',+ primaryIdAttribute: 'new_productid',+ primaryNameAttribute: 'new_name',+ customEntity: true,+ managed: false,+ customizable: true,+ canCreateAttributes: true,+ }],+ candidateRanking: [{+ concept: 'products',+ normalizedTokens: ['product'],+ preferredPublisherFamily: 'new',+ candidates: [{+ rank: 1,+ logicalName: 'new_product',+ displayName: 'Product',+ publisherFamily: 'new',+ versioned: false,+ score: 999.89,+ reasons: ['exact:product'],+ detailed: false,+ selectionEvidence: [],+ }],+ }],+ selectedCandidateEvidence: [],+ });+ const clock = [100, 105, 130, 132];+ const expanded = await expandSnapshot({+ snapshot: base,+ tableNames: ['new_product'],+ nowMs: () => clock.shift(),+ nowIso: () => '2026-08-18T05:01:00.000Z',+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [] } };+ }+ return { status: 200, data: { value: [] } };+ },+ });+ assert.equal(expanded.expansion.inventoryReused, true);+ assert.deepEqual(expanded.expansion.loadedTables, ['new_product']);+ assert.equal(expanded.timings.inventoryRetrievalMs, 5);+ assert.equal(expanded.candidateRanking[0].candidates[0].detailed, true);+ assert.equal(calls.some((apiPath) => apiPath.startsWith('EntityDefinitions?')), false);+});++test('exact-name expansion discovers and details a managed dependency absent from inventory', async () => {+ const calls = [];+ const base = validSnapshotBase({+ inputs: { concepts: ['animals'], explicitTableNames: [], proposedTableNames: [] },+ inventory: [normalizeInventoryForTest(entity('wr_animal', 'Animal'))],+ });+ const managedContact = entity('contact', 'Contact', {+ IsCustomEntity: false,+ IsManaged: true,+ IsCustomizable: { Value: false },+ CanCreateAttributes: { Value: false },+ });+ const expanded = await expandSnapshot({+ snapshot: base,+ tableNames: ['contact'],+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ assert.match(apiPath, /LogicalName eq 'contact'/);+ assert.doesNotMatch(apiPath, /IsCustomizable\/Value eq true/);+ return { status: 200, data: { value: [managedContact] } };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.equal(calls.filter((apiPath) => apiPath.startsWith('EntityDefinitions?')).length, 1);+ assert.equal(calls.some((apiPath) => apiPath.includes("EntityDefinitions(LogicalName='contact')/Attributes?")), true);+ assert.deepEqual(expanded.expansion.requestedTables, ['contact']);+ assert.deepEqual(expanded.expansion.loadedTables, ['contact']);+ assert.deepEqual(expanded.expansion.newlyLoadedTables, ['contact']);+ assert.deepEqual(expanded.expansion.unavailableTables, []);+ assert.equal(expanded.inventory.find((item) => item.logicalName === 'contact').managed, true);+ assert.equal(expanded.inventory.find((item) => item.logicalName === 'contact').customizable, false);+ assert.equal(expanded.tables.find((item) => item.logicalName === 'contact').facts.columnCount, 0);+});++test('proposed-name expansion checks collisions without loading details', async () => {+ const calls = [];+ const base = validSnapshotBase();+ const expanded = await expandSnapshot({+ snapshot: base,+ proposedTableNames: ['new_product', 'new_missing'],+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity('new_product', 'Product')] } };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(+ expanded.proposedNameChecks.collisions.map((item) => item.logicalName),+ ['new_product'],+ );+ assert.deepEqual(expanded.proposedNameChecks.missing, ['new_missing']);+ assert.deepEqual(expanded.tables, []);+ assert.equal(calls.some((apiPath) => apiPath.includes('/Attributes?$select=')), false);+ assert.deepEqual(expanded.exactNameResolution, {+ requestedTables: [],+ loadedTables: [],+ unavailableTables: [],+ });+});++test('exact-name expansion fails closed when required detail metadata is unreadable', async () => {+ const base = validSnapshotBase({+ inputs: { concepts: ['activities'], explicitTableNames: [], proposedTableNames: [] },+ inventory: [normalizeInventoryForTest(entity('activitypointer', 'Activity'))],+ });++ await assert.rejects(+ expandSnapshot({+ snapshot: base,+ tableNames: ['activitypointer'],+ request: async (_method, apiPath) => {+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 403, error: 'metadata forbidden' };+ }+ return { status: 200, data: { value: [] } };+ },+ }),+ /activitypointer attributes failed \(403\): metadata forbidden/,+ );+});++test('computed metadata is explicitly unavailable when SourceTypeMask cannot be proven', async () => {+ const table = await loadDetailedEntity(async (_method, apiPath) => {+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [{+ MetadataId: 'computed-id',+ LogicalName: 'new_computed',+ SchemaName: 'new_Computed',+ AttributeType: 'Decimal',+ AttributeTypeName: { Value: 'DecimalType' },+ SourceType: 1,+ }] } };+ }+ if (apiPath.includes('Attributes(computed-id)')) {+ return {+ status: 200,+ data: {+ LogicalName: 'new_computed',+ SourceType: 1,+ FormulaDefinition: 'new_amount * 2',+ },+ };+ }+ return { status: 200, data: { value: [] } };+ }, entity('new_invoice', 'Invoice'));++ const computed = table.columns[0].computed;+ assert.equal(computed.sourceType, 1);+ assert.equal(computed.sourceTypeMask, null);+ assert.equal(computed.formulaDefinition, 'new_amount * 2');+ assert.equal(computed.metadataStatus, 'unavailable');+ assert.match(computed.unavailableReason, /SourceTypeMask unavailable or malformed/);+});++test('CLI request creation initializes one long-lived executor for the snapshot phase', async () => {+ let executorCreations = 0;+ let requests = 0;+ const request = createCliRequest({+ 'env-url': 'https://example.crm.dynamics.com',+ 'tenant-id': 'tenant-1',+ }, (options) => {+ executorCreations += 1;+ assert.equal(options.environmentUrl, 'https://example.crm.dynamics.com');+ return async () => {+ requests += 1;+ return { status: 200, data: { value: [] } };+ };+ });++ await request('GET', 'EntityDefinitions');+ await request('GET', "EntityDefinitions(LogicalName='contact')/Attributes");+ await request('GET', "EntityDefinitions(LogicalName='contact')/Keys");+ assert.equal(executorCreations, 1);+ assert.equal(requests, 3);+});++test('evidence renderer emits compact deterministic planning facts', () => {+ const collision = {+ logicalName: 'wr_animal',+ status: 'collision',+ existing: { customEntity: true, managed: false, customizable: true },+ };+ const snapshot = validSnapshotBase({+ candidateRanking: [{+ concept: 'animals',+ preferredPublisherFamily: 'wr',+ candidates: [{+ rank: 1,+ logicalName: 'wr_animal',+ score: 999.91,+ detailed: true,+ versioned: false,+ reasons: ['exact:animal'],+ }],+ }],+ tables: [{+ logicalName: 'wr_animal',+ customEntity: true,+ managed: false,+ customizable: true,+ columns: [{ logicalName: 'wr_name' }],+ manyToOneRelationships: [{}],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ }],+ proposedNameChecks: {+ checked: [+ collision,+ { logicalName: 'wr_releaseevent', status: 'missing', existing: null },+ ],+ collisions: [collision],+ missing: ['wr_releaseevent'],+ },+ timings: {+ inventoryRetrievalMs: 25,+ candidateSelectionMs: 2,+ detailLoadingMs: 50,+ totalDurationMs: 78,+ },+ });+ const markdown = renderPlanningEvidence(snapshot);+ assert.match(markdown, /# Dataverse Planning Evidence/);+ assert.match(markdown, /animals.*wr_animal.*999\.91/);+ assert.match(markdown, /wr_animal.*yes.*no.*yes.*1.*1.*0/);+ assert.match(markdown, /wr_releaseevent.*missing/);+ assert.match(markdown, /Inventory retrieval.*25 ms/);+ assert.match(markdown, /\*\*Total\*\*.*\*\*78 ms\*\*/);+});++test('evidence renderer reports skipped advisory detail failures', () => {+ const snapshot = validSnapshotBase({+ candidateRanking: [{+ concept: 'activities',+ preferredPublisherFamily: '',+ candidates: [{+ rank: 1,+ logicalName: 'activitypointer',+ score: 749.85,+ detailed: false,+ detailStatus: 'unavailable',+ versioned: false,+ reasons: ['contains:activity'],+ }],+ }],+ tables: [],+ detailLoadFailures: [{+ logicalName: 'activitypointer',+ selectionReasons: ['concept:activities'],+ status: 400,+ error: 'abstract metadata type is unsupported',+ required: false,+ }],+ detailLoadSummary: {+ attemptedCandidates: 1,+ loadedCandidates: 0,+ failedCandidates: 1,+ },+ proposedNameChecks: { checked: [], collisions: [], missing: [] },+ timings: {+ inventoryRetrievalMs: 25,+ candidateSelectionMs: 2,+ detailLoadingMs: 15,+ totalDurationMs: 42,+ },+ });++ const markdown = renderPlanningEvidence(snapshot);+ assert.match(markdown, /activitypointer.*detail unavailable/);+ assert.match(markdown, /Skipped advisory detail failures/);+ assert.match(markdown, /activitypointer.*concept:activities.*400.*abstract metadata type is unsupported/);+});++test('atomic output replaces the target and leaves no sibling temporary file', (t) => {+ const directory = projectScratch(t);+ const output = path.join(directory, 'evidence.md');+ fs.writeFileSync(output, 'old\n');+ atomicWriteFile(output, 'new\n');+ assert.equal(fs.readFileSync(output, 'utf8'), 'new\n');+ assert.deepEqual(fs.readdirSync(directory), ['evidence.md']);+});++test('planning contracts require the snapshot-only path and bounded expansion', () => {+ const pluginRoot = path.resolve(__dirname, '..', '..');+ const architect = fs.readFileSync(+ path.join(pluginRoot, 'agents', 'data-model-architect.md'),+ 'utf8',+ );+ const planner = fs.readFileSync(+ path.join(pluginRoot, 'agents', 'native-app-planner.md'),+ 'utf8',+ );+ const createSkill = fs.readFileSync(+ path.join(pluginRoot, 'skills', 'create-mobile-app', 'SKILL.md'),+ 'utf8',+ );+ const snapshotScript = fs.readFileSync(+ path.join(pluginRoot, 'scripts', 'create-dataverse-snapshot.js'),+ 'utf8',+ );+ assert.match(architect, /## Snapshot-only fast path/);+ assert.match(architect, /Do \*\*not\*\* run Bash discovery/);+ assert.match(architect, /NEEDS_CONTEXT: detailed-dataverse-metadata:<comma-separated-logical-names>/);+ assert.match(architect, /NEEDS_CONTEXT: proposed-dataverse-names:<comma-separated-logical-names>/);+ assert.match(architect, /\.tmp\/data-model-planning-status\.json/);+ assert.match(planner, /Dataverse planning forwarding is verbatim/);+ assert.match(planner, /Do not duplicate raw evidence/);+ assert.match(createSkill, /render-dataverse-planning-evidence\.js/);+ assert.match(createSkill, /--base-snapshot "\$SNAPSHOT_PATH"/);+ assert.match(createSkill, /--proposed-tables "<exact comma-separated logical names>"/);+ assert.match(createSkill, /connector-only.*skip every command/s);+ assert.match(createSkill, /Publisher-prefix discovery skipped — connector-only planning/);+ assert.doesNotMatch(createSkill, /legacy-unverified/);+ assert.match(createSkill, /does not accept an unresolved\s+`Unverified` plan/s);+ assert.match(createSkill, /BLOCKED: Dataverse planning metadata unavailable for exact target decisions/);+ assert.match(createSkill, /10–15 minute target/);+ assert.doesNotMatch(snapshotScript, /execFileSync/);+});diff --git a/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.jsnew file mode 100644index 000000000..57b3bd0f6--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js@@ -0,0 +1,766 @@+const assert = require('node:assert/strict');+const { execFile } = require('node:child_process');+const crypto = require('node:crypto');+const fs = require('node:fs');+const http = require('node:http');+const path = require('node:path');+const test = require('node:test');+const { promisify } = require('node:util');++const execFileAsync = promisify(execFile);+const scriptPath = path.resolve(__dirname, '..', 'dataverse-request.js');+const fakeAzPreload = path.join(__dirname, 'helpers', 'fake-az-preload.js');+const {+ createDataverseRequestExecutor,+ looksLikeDuplicate,+ operationFingerprint,+ prepareMetadataJournal,+ retryAfterDelayMs,+ runMetadataBatch,+ runOneMetadataOperation,+ validateManifestExecutionBinding,+ validateJournalOperations,+} = require('../dataverse-request');++function manifestStableJson(value) {+ function clone(item) {+ if (Array.isArray(item)) return item.map(clone);+ if (!item || typeof item !== 'object') return item;+ return Object.keys(item).sort().reduce((result, key) => {+ result[key] = clone(item[key]);+ return result;+ }, {});+ }+ return `${JSON.stringify(clone(value), null, 2)}\n`;+}++function executionManifest(phaseOperations, {+ environmentUrl = 'https://example.crm.dynamics.com',+ solutionUniqueName = null,+ reconciliationSha256 = 'b'.repeat(64),+} = {}) {+ const phaseNames = [+ 'tableCreates',+ 'extensions',+ 'relationships',+ 'alternateKeys',+ 'publish',+ ];+ const manifest = {+ schemaVersion: 2,+ executable: true,+ binding: {+ environmentUrl,+ solutionUniqueName,+ reconciliationSha256,+ },+ execution: {+ executor: 'BATCH-METADATA',+ odataBatch: false,+ parallelWrites: false,+ phases: phaseNames.map((name) => ({+ name,+ operations: phaseOperations[name] || [],+ })),+ },+ };+ manifest.integritySha256 = crypto.createHash('sha256')+ .update(manifestStableJson(manifest))+ .digest('hex');+ return manifest;+}++test('Retry-After supports delta-seconds and HTTP-date with a safe fallback', () => {+ assert.equal(retryAfterDelayMs('7', 30000), 7000);+ assert.equal(+ retryAfterDelayMs('Wed, 19 Aug 2026 00:00:05 GMT', 30000, Date.parse(+ 'Wed, 19 Aug 2026 00:00:00 GMT',+ )),+ 5000,+ );+ assert.equal(retryAfterDelayMs('invalid', 30000), 30000);+ assert.equal(retryAfterDelayMs(undefined, 5000), 5000);+ assert.equal(retryAfterDelayMs('invalid', -1), 30000);+ const offlineUpdater = fs.readFileSync(path.join(+ __dirname,+ '../update-entity-offline-flags.js',+ ), 'utf8');+ assert.match(offlineUpdater, /require\('\.\/dataverse-request'\)/);+ assert.match(+ offlineUpdater,+ /await new Promise\(\(r\) => setTimeout\(r, delayMs\)\)/,+ );+});++test('hidden Dataverse metadata collision signatures require regeneration', () => {+ assert.equal(looksLikeDuplicate({+ error: {+ code: '0x80044363',+ message: 'The schema name new_Table is not unique',+ },+ }), true);+ assert.equal(looksLikeDuplicate({+ error: {+ code: '0x80060890',+ message: 'An object with same name exists in solution',+ },+ }), true);+});++test('operation fingerprints ignore reindexing while order is validated separately', () => {+ const operation = {+ id: 'create-table:cr1_item',+ index: 4,+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_Item' },+ };+ assert.equal(+ operationFingerprint(operation, 'Default'),+ operationFingerprint({ ...operation, index: 0 }, 'Default'),+ );+ assert.throws(+ () => validateJournalOperations([+ { ...operation, index: 0 },+ { ...operation, index: 1 },+ ], 'Default'),+ /duplicate stable operation identity/,+ );+ assert.throws(+ () => validateJournalOperations([+ { ...operation, index: 1 },+ ], 'Default'),+ /indexes must be unique and ordered from zero/,+ );+});++test('manifest execution requires exact phase membership and completed predecessors', () => {+ const first = {+ id: 'create-table:cr1_item',+ index: 0,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_Item' },+ solution: 'Default',+ };+ const second = {+ id: 'extend-column:cr1_item:cr1_code',+ index: 1,+ phase: 'extensions',+ method: 'POST',+ apiPath: "EntityDefinitions(LogicalName='cr1_item')/Attributes",+ body: { SchemaName: 'cr1_Code' },+ solution: 'Default',+ };+ const manifest = executionManifest({+ tableCreates: [first],+ extensions: [second],+ }, {+ solutionUniqueName: 'Default',+ });+ assert.throws(+ () => validateManifestExecutionBinding({+ manifest,+ manifestHash: manifest.integritySha256,+ selectedOperations: [{ ...second, body: { SchemaName: 'cr1_Tampered' } }],+ completeOperations: [first, second],+ defaultSolution: 'Default',+ environmentUrl: 'https://example.crm.dynamics.com',+ reconciliationHash: 'b'.repeat(64),+ journal: { completed: {} },+ }),+ /not an exact manifest phase/,+ );+ assert.throws(+ () => validateManifestExecutionBinding({+ manifest,+ manifestHash: manifest.integritySha256,+ selectedOperations: [second],+ completeOperations: [first, second],+ defaultSolution: 'Default',+ environmentUrl: 'https://example.crm.dynamics.com',+ reconciliationHash: 'b'.repeat(64),+ journal: { completed: {} },+ }),+ /predecessor create-table:cr1_item is not journal-complete/,+ );+ assert.doesNotThrow(() => validateManifestExecutionBinding({+ manifest,+ manifestHash: manifest.integritySha256,+ selectedOperations: [second],+ completeOperations: [first, second],+ defaultSolution: 'Default',+ environmentUrl: 'https://example.crm.dynamics.com',+ reconciliationHash: 'b'.repeat(64),+ journal: {+ completed: {+ [operationFingerprint(first, 'Default')]: { operationId: first.id },+ },+ },+ }));+ assert.throws(+ () => validateManifestExecutionBinding({+ manifest,+ manifestHash: 'a'.repeat(64),+ selectedOperations: [first],+ completeOperations: [first, second],+ defaultSolution: 'Default',+ environmentUrl: 'https://example.crm.dynamics.com',+ reconciliationHash: 'b'.repeat(64),+ journal: { completed: {} },+ }),+ /binding hash does not match/,+ );+});++function makeTempDir(t) {+ const tempDir = fs.mkdtempSync(path.join(__dirname, '.metadata-batch-scratch-'));+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));+ return tempDir;+}++function fakeAzEnv(overrides = {}) {+ return {+ ...process.env,+ NODE_OPTIONS: `--require=${fakeAzPreload}`,+ FAKE_AZ_STATIC_TOKEN: 'test-token',+ ...overrides,+ };+}++test('in-process request executor reuses one token across sequential metadata reads', async () => {+ let tokenCalls = 0;+ const requests = [];+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com/',+ tenantId: 'tenant-1',+ getToken: async () => {+ tokenCalls += 1;+ return 'shared-token';+ },+ sendRequest: async (_envUrl, method, apiPath, _body, token) => {+ requests.push({ method, apiPath, token });+ return {+ statusCode: 200,+ body: JSON.stringify({ value: [] }),+ headers: {},+ };+ },+ });++ await request('GET', 'EntityDefinitions');+ await request('GET', "EntityDefinitions(LogicalName='contact')/Attributes");+ await request('GET', "EntityDefinitions(LogicalName='contact')/Keys");++ assert.equal(tokenCalls, 1);+ assert.equal(requests.length, 3);+ assert.deepEqual(new Set(requests.map((item) => item.token)), new Set(['shared-token']));+});++test('metadata transport loss is uncertain and mutation is not retried', async () => {+ let requests = 0;+ const result = await runOneMetadataOperation(+ 'https://example.crm.dynamics.com',+ 'POST',+ 'EntityDefinitions',+ JSON.stringify({ SchemaName: 'cr1_Item' }),+ 'token',+ false,+ 'Default',+ 'tenant-1',+ async () => 'refreshed-token',+ async () => {+ requests += 1;+ return { error: 'socket closed before response' };+ },+ );+ assert.equal(requests, 1);+ assert.equal(result.status, 0);+ assert.equal(result.uncertain, true);+ assert.match(result.error, /socket closed/);++ let reads = 0;+ const readResult = await runOneMetadataOperation(+ 'https://example.crm.dynamics.com',+ 'GET',+ 'EntityDefinitions',+ null,+ 'token',+ false,+ 'Default',+ 'tenant-1',+ async () => 'refreshed-token',+ async () => {+ reads += 1;+ return reads === 1+ ? { error: 'temporary read transport loss' }+ : { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ );+ assert.equal(reads, 2);+ assert.equal(readResult.status, 200);+});++test('journal preserves inFlight uncertainty after metadata transport loss', async (t) => {+ const directory = makeTempDir(t);+ const journalPath = path.join(directory, 'metadata-journal.json');+ let requests = 0;+ const server = http.createServer((req) => {+ requests += 1;+ req.socket.destroy();+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());+ const envUrl = `http://127.0.0.1:${server.address().port}`;+ const operation = {+ id: 'create-table:cr1_item',+ index: 0,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_Item' },+ solution: null,+ };+ const reconciliationHash = 'b'.repeat(64);+ const manifest = executionManifest({ tableCreates: [operation] }, {+ environmentUrl: envUrl,+ reconciliationSha256: reconciliationHash,+ });+ const result = await runMetadataBatch(+ envUrl,+ [operation],+ 'token',+ null,+ 'tenant-1',+ false,+ {+ journalPath,+ manifestHash: manifest.integritySha256,+ reconciliationHash,+ allOperations: [operation],+ manifest,+ },+ );+ assert.equal(result.failed, true);+ assert.equal(result.results[0].uncertain, true);+ assert.equal(requests, 1);+ const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));+ assert.equal(journal.inFlight.operationId, operation.id);+ assert.equal(journal.inFlight.failure.uncertain, true);+});++test('BATCH-METADATA reuses auth, preserves order, and stops on first failure', async (t) => {+ const tempDir = makeTempDir(t);+ const azLog = path.join(tempDir, 'az.log');++ const requests = [];+ let active = 0;+ let maxActive = 0;+ const server = http.createServer((req, res) => {+ active++;+ maxActive = Math.max(maxActive, active);+ requests.push(req.url);+ const finish = () => {+ active--;+ if (req.url.endsWith('/two')) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: { message: 'planned failure' } }));+ return;+ }+ res.writeHead(204);+ res.end();+ };+ setTimeout(finish, 25);+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());++ const envUrl = `http://127.0.0.1:${server.address().port}`;+ const operations = [+ { index: 10, method: 'POST', apiPath: 'one', body: { value: 1 } },+ { index: 20, method: 'POST', apiPath: 'two', body: { value: 2 } },+ { index: 30, method: 'POST', apiPath: 'three', body: { value: 3 } },+ ];+ const { stdout } = await execFileAsync(+ process.execPath,+ [+ scriptPath,+ envUrl,+ 'BATCH-METADATA',+ 'test',+ '--operations',+ JSON.stringify(operations),+ '--tenant-id',+ 'explicit-tenant',+ ],+ {+ env: fakeAzEnv({+ FAKE_AZ_LOG: azLog,+ }),+ },+ );++ const output = JSON.parse(stdout);+ assert.equal(output.status, 207);+ assert.deepEqual(+ output.data.map(({ index, status }) => ({ index, status })),+ [+ { index: 10, status: 204 },+ { index: 20, status: 400 },+ ],+ );+ assert.equal(requests.length, 2);+ assert.match(requests[0], /\/api\/data\/v9\.2\/one$/);+ assert.match(requests[1], /\/api\/data\/v9\.2\/two$/);+ assert.equal(maxActive, 1);++ const authCalls = fs.readFileSync(azLog, 'utf8').trim().split('\n');+ assert.equal(authCalls.length, 1);+ assert.match(authCalls[0], /--tenant explicit-tenant/);+});++test('BATCH-METADATA atomically journals each completed manifest operation', async (t) => {+ const directory = makeTempDir(t);+ const journalPath = path.join(directory, 'metadata-journal.json');+ let requestCount = 0;+ const server = http.createServer((_req, res) => {+ requestCount += 1;+ res.writeHead(204);+ res.end();+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());++ const envUrl = `http://127.0.0.1:${server.address().port}`;+ const operations = [+ {+ id: 'create-table:one',+ index: 0,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'one',+ body: { a: 1 },+ },+ {+ id: 'create-table:two',+ index: 1,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'two',+ body: { a: 2 },+ },+ ];+ const manifest = executionManifest({ tableCreates: operations }, {+ environmentUrl: envUrl,+ });+ const manifestPath = path.join(directory, 'manifest.json');+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));+ const manifestHash = manifest.integritySha256;+ const reconciliationHash = 'b'.repeat(64);+ const args = [+ scriptPath,+ envUrl,+ 'BATCH-METADATA',+ 'journal',+ '--operations',+ JSON.stringify(operations),+ '--tenant-id',+ 'explicit-tenant',+ '--journal',+ journalPath,+ '--manifest-file',+ manifestPath,+ '--manifest-hash',+ manifestHash,+ '--reconciliation-hash',+ reconciliationHash,+ '--manifest-operations',+ JSON.stringify(operations),+ ];+ const first = await execFileAsync(process.execPath, args, { env: fakeAzEnv() });+ assert.equal(JSON.parse(first.stdout).status, 200);+ const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));+ assert.equal(journal.inFlight, null);+ assert.equal(Object.keys(journal.completed).length, 2);+ assert.equal(requestCount, 2);++ const second = await execFileAsync(process.execPath, args, { env: fakeAzEnv() });+ assert.deepEqual(+ JSON.parse(second.stdout).data.map((result) => result.journalStatus),+ ['already-completed', 'already-completed'],+ );+ assert.equal(requestCount, 2);+});++test('BATCH-METADATA requires fresh reconciliation before uncertain-operation resume', async (t) => {+ const directory = makeTempDir(t);+ const journalPath = path.join(directory, 'metadata-journal.json');+ let requestCount = 0;+ const server = http.createServer((_req, res) => {+ requestCount += 1;+ res.writeHead(204);+ res.end();+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());+ const envUrl = `http://127.0.0.1:${server.address().port}`;+ const operation = {+ id: 'create-table:uncertain',+ index: 0,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_uncertain' },+ };+ const oldManifest = executionManifest({ tableCreates: [operation] }, {+ environmentUrl: envUrl,+ reconciliationSha256: 'd'.repeat(64),+ });+ const oldManifestPath = path.join(directory, 'old-manifest.json');+ fs.writeFileSync(oldManifestPath, JSON.stringify(oldManifest));+ const oldManifestHash = oldManifest.integritySha256;+ const oldReconciliationHash = 'd'.repeat(64);+ const fingerprint = operationFingerprint(operation);+ fs.writeFileSync(journalPath, JSON.stringify({+ schemaVersion: 1,+ binding: { environmentUrl: envUrl, solution: null },+ completed: {},+ recoveries: [],+ inFlight: {+ index: 0,+ operationId: operation.id,+ fingerprint,+ manifestHash: oldManifestHash,+ reconciliationHash: oldReconciliationHash,+ startedAt: '2026-08-19T00:00:00.000Z',+ },+ }));++ const stale = await execFileAsync(process.execPath, [+ scriptPath,+ envUrl,+ 'BATCH-METADATA',+ 'resume',+ '--operations',+ JSON.stringify([operation]),+ '--tenant-id',+ 'explicit-tenant',+ '--journal',+ journalPath,+ '--manifest-file',+ oldManifestPath,+ '--manifest-hash',+ oldManifestHash,+ '--reconciliation-hash',+ oldReconciliationHash,+ '--manifest-operations',+ JSON.stringify([operation]),+ ], { env: fakeAzEnv() });+ const staleOutput = JSON.parse(stale.stdout);+ assert.equal(staleOutput.status, 207);+ assert.match(staleOutput.data[0].error, /UNCERTAIN_METADATA_OPERATION/);+ assert.equal(requestCount, 0);++ const recoveredManifest = executionManifest({}, {+ environmentUrl: envUrl,+ reconciliationSha256: 'f'.repeat(64),+ });+ const recoveredManifestPath = path.join(directory, 'recovered-manifest.json');+ fs.writeFileSync(recoveredManifestPath, JSON.stringify(recoveredManifest));+ const recovered = await execFileAsync(process.execPath, [+ scriptPath,+ envUrl,+ 'BATCH-METADATA',+ 'resume',+ '--operations',+ '[]',+ '--tenant-id',+ 'explicit-tenant',+ '--journal',+ journalPath,+ '--manifest-file',+ recoveredManifestPath,+ '--manifest-hash',+ recoveredManifest.integritySha256,+ '--reconciliation-hash',+ 'f'.repeat(64),+ ], { env: fakeAzEnv() });+ const recoveredOutput = JSON.parse(recovered.stdout);+ assert.equal(recoveredOutput.status, 200);+ assert.equal(+ recoveredOutput.data[0].journalStatus,+ 'fresh-reconciliation-confirmed-already-applied-or-superseded',+ );+ assert.equal(requestCount, 0);+ const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));+ assert.equal(journal.inFlight, null);+ assert.equal(journal.recoveries.length, 1);+});++test('collision recovery rejects the old operation array after a rename', (t) => {+ const directory = makeTempDir(t);+ const journalPath = path.join(directory, 'metadata-journal.json');+ const priorOperation = {+ id: 'create-table:old-name',+ index: 5,+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_oldname' },+ };+ fs.writeFileSync(journalPath, JSON.stringify({+ schemaVersion: 1,+ binding: {+ environmentUrl: 'https://example.crm.dynamics.com',+ solution: 'Default',+ },+ completed: {},+ recoveries: [],+ inFlight: {+ index: priorOperation.index,+ operationId: priorOperation.id,+ fingerprint: operationFingerprint(priorOperation, 'Default'),+ manifestHash: '1'.repeat(64),+ reconciliationHash: '2'.repeat(64),+ failure: {+ status: 400,+ collision: true,+ recordedAt: '2026-08-19T00:00:00.000Z',+ },+ },+ }));++ assert.throws(+ () => prepareMetadataJournal({+ journalPath,+ environmentUrl: 'https://example.crm.dynamics.com',+ solution: 'Default',+ manifestHash: '3'.repeat(64),+ reconciliationHash: '4'.repeat(64),+ operations: [{ ...priorOperation, index: 0 }],+ }),+ /COLLISION_REQUIRES_REGENERATED_OPERATIONS/,+ );+});++test('superseded collision fingerprints remain recovery evidence, not completion', (t) => {+ const directory = makeTempDir(t);+ const journalPath = path.join(directory, 'metadata-journal.json');+ const priorOperation = {+ id: 'create-table:old-name',+ index: 2,+ phase: 'tableCreates',+ method: 'POST',+ apiPath: 'EntityDefinitions',+ body: { SchemaName: 'cr1_oldname' },+ };+ const fingerprint = operationFingerprint(priorOperation, 'Default');+ fs.writeFileSync(journalPath, JSON.stringify({+ schemaVersion: 1,+ binding: {+ environmentUrl: 'https://example.crm.dynamics.com',+ solution: 'Default',+ },+ completed: {},+ recoveries: [],+ inFlight: {+ index: priorOperation.index,+ operationId: priorOperation.id,+ fingerprint,+ manifestHash: '1'.repeat(64),+ reconciliationHash: '2'.repeat(64),+ failure: { status: 400, collision: true },+ },+ }));++ const prepared = prepareMetadataJournal({+ journalPath,+ environmentUrl: 'https://example.crm.dynamics.com',+ solution: 'Default',+ manifestHash: '3'.repeat(64),+ reconciliationHash: '4'.repeat(64),+ operations: [],+ });+ assert.equal(prepared.recoveryResults[0].journalStatus,+ 'fresh-reconciliation-confirmed-superseded-collision');+ const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));+ assert.equal(Object.hasOwn(journal.completed, fingerprint), false);+ assert.equal(journal.recoveries[0].fingerprint, fingerprint);+});++test('BATCH-METADATA does not turn a post-throttle collision into success', async (t) => {+ makeTempDir(t);++ let requestCount = 0;+ const server = http.createServer((req, res) => {+ requestCount++;+ if (requestCount === 1) {+ res.writeHead(429, { 'Retry-After': '0' });+ res.end();+ return;+ }+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: { message: 'object with same name already exists' } }));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());++ const envUrl = `http://127.0.0.1:${server.address().port}`;+ const { stdout } = await execFileAsync(+ process.execPath,+ [+ scriptPath,+ envUrl,+ 'BATCH-METADATA',+ 'collision',+ '--operations',+ JSON.stringify([{ method: 'POST', apiPath: 'EntityDefinitions', body: { value: 1 } }]),+ '--tenant-id',+ 'explicit-tenant',+ ],+ { env: fakeAzEnv() },+ );++ const output = JSON.parse(stdout);+ assert.equal(output.status, 207);+ assert.equal(output.data[0].status, 400);+ assert.equal(output.data[0].rateLimited, true);+ assert.equal(requestCount, 2);+});++test('direct writes return post-throttle collisions for fresh reconciliation', async (t) => {+ makeTempDir(t);+ let requestCount = 0;+ const server = http.createServer((_req, res) => {+ requestCount += 1;+ if (requestCount === 1) {+ res.writeHead(429, { 'Retry-After': '0' });+ res.end();+ return;+ }+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: {+ code: '0x80044363',+ message: 'The schema name cr1_Item is not unique',+ },+ }));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(() => server.close());++ const { stdout } = await execFileAsync(process.execPath, [+ scriptPath,+ `http://127.0.0.1:${server.address().port}`,+ 'POST',+ 'EntityDefinitions',+ '--body',+ JSON.stringify({ SchemaName: 'cr1_Item' }),+ '--tenant-id',+ 'explicit-tenant',+ ], { env: fakeAzEnv() });+ const output = JSON.parse(stdout);+ assert.equal(output.status, 400);+ assert.equal(output.rate_limited_during_request, true);+ assert.equal(requestCount, 2);+});diff --git a/plugins/mobile-apps/scripts/tests/derived-metadata.test.js b/plugins/mobile-apps/scripts/tests/derived-metadata.test.jsnew file mode 100644index 000000000..3582d5900--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/derived-metadata.test.js@@ -0,0 +1,234 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert');+const { spawnSync } = require('node:child_process');+const path = require('node:path');++const {+ compareDerivedColumn,+ compareDerivedMetadata,+} = require('../lib/derived-metadata');++test('lookup reconciliation rejects a same-named lookup targeting another table', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_productid',+ kind: 'lookup',+ type: 'Lookup',+ sourceType: 0,+ lookupTarget: 'cr1_product',+ },+ {+ type: 'Lookup',+ sourceType: 0,+ lookupTargets: ['cr1_supplier'],+ },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /lookup target mismatch/);+});++test('lookup reconciliation rejects a broader polymorphic target set', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_customerid',+ kind: 'lookup',+ type: 'Lookup',+ sourceType: 0,+ lookupTarget: 'account',+ },+ {+ type: 'Lookup',+ sourceType: 0,+ lookupTargets: ['account', 'contact'],+ },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /lookup target mismatch/);+});++test('choice reconciliation requires every planned integer and label mapping', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_status',+ kind: 'choice',+ type: 'Picklist',+ sourceType: 0,+ options: [+ { value: 100000000, label: 'Open' },+ { value: 100000001, label: 'Closed' },+ ],+ },+ {+ type: 'Picklist',+ sourceType: 0,+ options: [+ { value: 100000000, label: 'Open' },+ { value: 100000001, label: 'Resolved' },+ ],+ },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /label mismatch/);+});++test('ordinary columns reject live calculated or formula metadata', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_name',+ kind: 'ordinary',+ type: 'String',+ sourceType: 0,+ },+ { type: 'String', sourceType: 3 },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /source type mismatch/);+});++test('malformed normalized metadata fails closed', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_productid',+ kind: 'lookup',+ type: 'Lookup',+ sourceType: 0,+ lookupTarget: 'cr1_product',+ },+ {+ type: 'Lookup',+ lookupTargets: 'cr1_product',+ },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /sourceType is missing/);+ assert.match(result.reasons.join('; '), /lookupTargets must be an array/);+});++test('malformed expected contracts and duplicate live rows fail closed', () => {+ const malformed = compareDerivedColumn(+ { table: 'cr1_order', logicalName: 'cr1_status', kind: 'choice', type: 'Picklist' },+ { type: 'Picklist', sourceType: 0, options: [] },+ );+ assert.strictEqual(malformed.compatible, false);+ assert.match(malformed.reasons.join('; '), /sourceType is missing/);+ assert.match(malformed.reasons.join('; '), /expected choice options/);++ const duplicate = compareDerivedMetadata(+ [{+ table: 'cr1_order',+ logicalName: 'cr1_status',+ kind: 'ordinary',+ type: 'String',+ sourceType: 0,+ }],+ [+ { table: 'cr1_order', logicalName: 'cr1_status', type: 'String', sourceType: 0 },+ { table: 'cr1_order', logicalName: 'cr1_status', type: 'String', sourceType: 0 },+ ],+ );+ assert.strictEqual(duplicate[0].compatible, false);+ assert.match(duplicate[0].reasons.join('; '), /duplicate live metadata rows/);+});++test('malformed choice and Boolean mappings fail closed', () => {+ const emptyChoice = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_status',+ kind: 'choice',+ type: 'Picklist',+ sourceType: 0,+ options: [],+ },+ { type: 'Picklist', sourceType: 0, options: [] },+ );+ assert.strictEqual(emptyChoice.compatible, false);+ assert.match(emptyChoice.reasons.join('; '), /non-empty array/);++ const malformedBoolean = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_active',+ kind: 'boolean',+ type: 'Boolean',+ sourceType: 0,+ options: [{ value: 1, label: 'Yes' }, { value: 1, label: '' }],+ },+ {+ type: 'Boolean',+ sourceType: 0,+ options: [{ value: 0, label: 'No' }, { value: 1, label: 'Yes' }],+ },+ );+ assert.strictEqual(malformedBoolean.compatible, false);+ assert.match(malformedBoolean.reasons.join('; '), /duplicated|no label|exactly values 0 and 1/);+});++test('computed-column reuse requires an exact formula definition', () => {+ const results = compareDerivedMetadata(+ [{+ table: 'cr1_order',+ logicalName: 'cr1_total',+ kind: 'computed',+ type: 'Decimal',+ sourceType: 3,+ sourceTypeMask: 2,+ formulaDefinition: 'expected-definition',+ }],+ [{+ table: 'cr1_order',+ logicalName: 'cr1_total',+ type: 'Decimal',+ sourceType: 3,+ sourceTypeMask: 2,+ formulaDefinition: 'different-definition',+ }],+ );+ assert.strictEqual(results[0].compatible, false);+ assert.match(results[0].reasons.join('; '), /FormulaDefinition mismatch/);+});++test('computed-column reuse rejects invalid or mismatched source type masks', () => {+ const result = compareDerivedColumn(+ {+ table: 'cr1_order',+ logicalName: 'cr1_total',+ kind: 'computed',+ type: 'Decimal',+ sourceType: 3,+ sourceTypeMask: 2,+ formulaDefinition: 'definition',+ },+ {+ type: 'Decimal',+ sourceType: 3,+ sourceTypeMask: 32,+ formulaDefinition: 'definition',+ },+ );+ assert.strictEqual(result.compatible, false);+ assert.match(result.reasons.join('; '), /Invalid bit/);+});++test('legacy calculated-column helper fails before attempting mutation', () => {+ const script = path.resolve(__dirname, '..', 'create-calculated-column.js');+ const result = spawnSync(process.execPath, [+ script,+ 'https://example.crm.dynamics.com',+ '--table', 'cr1_order',+ '--column', 'cr1_total_calc',+ '--type', 'decimal',+ '--formula', 'cr1_parentid.cr1_total',+ ], { encoding: 'utf8' });+ assert.strictEqual(result.status, 2);+ const output = JSON.parse(result.stdout);+ assert.strictEqual(output.status, 'BLOCKED');+ assert.strictEqual(output.code, 'UNSUPPORTED_FORMULA_DEFINITION_API');+});diff --git a/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js b/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.jsnew file mode 100644index 000000000..3c2a22965--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js@@ -0,0 +1,40 @@+'use strict';++const childProcess = require('node:child_process');+const fs = require('node:fs');++const originalExecFileSync = childProcess.execFileSync;++childProcess.execFileSync = function fakeAzExecFileSync(command, args, options) {+ if (command !== 'az') {+ return originalExecFileSync.call(this, command, args, options);+ }++ const cliArgs = Array.isArray(args) ? args : [];+ if (process.env.FAKE_AZ_LOG) {+ fs.appendFileSync(process.env.FAKE_AZ_LOG, `${cliArgs.join(' ')}\n`);+ }++ if (cliArgs[0] === 'account' && cliArgs[1] === 'show') {+ return `${process.env.FAKE_AZ_ACCOUNT_TENANT || ''}\n`;+ }++ if (cliArgs[0] === 'account' && cliArgs[1] === 'get-access-token') {+ const tenantIndex = cliArgs.indexOf('--tenant');+ const tenant = tenantIndex === -1 ? '' : cliArgs[tenantIndex + 1];+ const failing = (process.env.FAKE_AZ_FAIL_TENANTS || '').split(',').filter(Boolean);+ if (tenant && failing.includes(tenant)) {+ const error = new Error(`Fake Azure CLI rejected tenant ${tenant}`);+ error.status = 1;+ throw error;+ }+ if (process.env.FAKE_AZ_STATIC_TOKEN) {+ return `${process.env.FAKE_AZ_STATIC_TOKEN}\n`;+ }+ return `token-for:${tenant || 'active-account'}\n`;+ }++ const error = new Error(`Unexpected fake Azure CLI arguments: ${cliArgs.join(' ')}`);+ error.status = 1;+ throw error;+};diff --git a/plugins/mobile-apps/scripts/update-entity-offline-flags.js b/plugins/mobile-apps/scripts/update-entity-offline-flags.jsindex 50f8474ca..8a3c178c8 100644--- a/plugins/mobile-apps/scripts/update-entity-offline-flags.js+++ b/plugins/mobile-apps/scripts/update-entity-offline-flags.js@@ -28,6 +28,7 @@// 1 — bad args, auth failure, network failure after retriesconst { getAuthToken, makeRequest } = require('./lib/validation-helpers');+const { retryAfterDelayMs } = require('./dataverse-request');function parseArgs() {const argv = process.argv.slice(2);@@ -195,8 +196,7 @@ async function main() {}if (res.statusCode === 429 && attempt < maxRetries) {- const retryAfter = res.headers?.['retry-after'];- const delayMs = retryAfter ? parseInt(retryAfter, 10) * 1000 : 30000;+ const delayMs = retryAfterDelayMs(res.headers?.['retry-after'], 30000);process.stderr.write(`429 rate-limited — waiting ${delayMs / 1000}s\n`);await new Promise((r) => setTimeout(r, delayMs));continue;diff --git a/plugins/mobile-apps/scripts/validate-derived-metadata.js b/plugins/mobile-apps/scripts/validate-derived-metadata.jsnew file mode 100755index 000000000..40c93c0f9--- /dev/null+++ b/plugins/mobile-apps/scripts/validate-derived-metadata.js@@ -0,0 +1,46 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { compareDerivedMetadata } = require('./lib/derived-metadata');++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ if (argv[index] === '--expected') args.expected = argv[++index];+ else if (argv[index] === '--actual') args.actual = argv[++index];+ }+ return args;+}++function readJson(filePath, label) {+ if (!filePath) throw new Error(`${label} path is required`);+ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) throw new Error(`${label} path not found: ${resolved}`);+ return JSON.parse(fs.readFileSync(resolved, 'utf8'));+}++function main() {+ const args = parseArgs(process.argv);+ const expected = readJson(args.expected, '--expected');+ const actual = readJson(args.actual, '--actual');+ const results = compareDerivedMetadata(expected.columns || expected, actual.columns || actual);+ const incompatible = results.filter((result) => !result.compatible);+ process.stdout.write(`${JSON.stringify({+ status: incompatible.length === 0 ? 'VALID' : 'BLOCKED',+ results,+ }, null, 2)}\n`);+ return incompatible.length === 0 ? 0 : 2;+}++if (require.main === module) {+ try {+ process.exitCode = main();+ } catch (error) {+ process.stderr.write(`${error.message}\n`);+ process.exitCode = 1;+ }+}++module.exports = { main, parseArgs, readJson };diff --git a/plugins/mobile-apps/shared/references/data-performance.md b/plugins/mobile-apps/shared/references/data-performance.mdindex 02f6145d6..360bebfa4 100644--- a/plugins/mobile-apps/shared/references/data-performance.md+++ b/plugins/mobile-apps/shared/references/data-performance.md@@ -124,61 +124,63 @@ Whenever a UI field on a screen displays data sourced from an entity OTHER than- Inspection detail shows "Inspector email" → email lives on `systemuser`, screen fetches `cr3e9_inspection` → cross-entity read- Order detail shows "Customer phone" → phone lives on `contact`, screen fetches `salesorder` → cross-entity read-### Why two patterns exist (calculated column AND chained fetch)+### Supported read pathsThe Power Apps SDK's `IGetAllOptions` / `IGetOptions` interfaces have **no `expand` field**. Passing `$expand` is silently dropped at runtime — the related fields come back `undefined`, the screen renders `—`, and the user thinks the data is missing. So the standard OData answer ("just expand the lookup") doesn't work.-Two patterns remain. Their cost profiles are very different, so the right pick depends on **screen archetype × relationship cardinality**:+Use one of these supported paths:-- **Calculated column** — denormalize the related field onto the parent table at the data-model layer. One round trip per page load, no N+1, no per-row jank. Best for hot paths (lists, dashboards, tab roots).-- **Chained fetch** — call a second `Service.get(...)` inside the screen's load step. One extra network round trip per screen load. Acceptable for cold paths (a single detail screen). Disastrous on lists (one extra fetch per row × 50 rows = N+1 fetch storm).+- **Formatted lookup annotation** — when the UI needs only the primary display+ name of a direct lookup already present on the fetched record, use+ `lookupName(record, '<lookupLogicalName>')` / `formattedValue(...)`. This+ adds no schema mutation and no additional request.+- **Chained fetch** — call a second `Service.get(...)` once in a detail load, or+ `Service.getAll(...)` for a bounded related collection.+- **External projection required** — for a hot list/dashboard field that is not+ the direct lookup display name. Omit the field until the user creates a+ supported server-owned projection outside this workflow.++Dataverse exposes formula metadata, but Microsoft does not support defining+calculated, rollup, or formula expressions through code. Never synthesize+workflow XAML or formula serialization.### Decision table (the rule)| Screen archetype | Relationship | Action ||---|---|---|-| **List** (`top ≥ 5`), **Tab-root**, **Dashboard** | 1:1 (N:1 lookup chain) | **REFUSE to scaffold the field.** Recommend the user re-run `/setup-datamodel` (or `/add-dataverse` for existing apps) to add a calc column on the parent entity. Do NOT scaffold N+1 chained fetches on list screens — visible jank on a list of 50. |+| **List** (`top ≥ 5`), **Tab-root**, **Dashboard** | Direct N:1 lookup primary display name | Use the formatted lookup annotation. |+| **List** (`top ≥ 5`), **Tab-root**, **Dashboard** | Any other related field | Mark `external-projection-required` and omit it. Do NOT scaffold N+1 reads or synthesize a formula definition. || **Detail** (single record, cold path) | 1:1 (N:1 lookup chain) | Scaffold a chained fetch in the screen's load step. One extra round trip is fine for a single record. |-| **Any screen** | 1:many or M:N | Scaffold a chained `*Service.getAll(...)` with `_<parentid>_value eq '${id}'` filter. **Calc columns CANNOT traverse 1:many or M:N** — Dataverse only supports calc-column formulas across N:1 (single-valued) navigation properties. |--Verification: every UI field on a screen spec must end up with EITHER a `select` entry (covered by primary fetch or calc column) OR a chained fetch path (separate `Service.get` / `Service.getAll`). If neither, fail with `BLOCKED: <field> on <screen> has no fetch path`.--### Pattern A: Calculated column (preferred for list / hot path)+| **List**, **Tab-root**, **Dashboard** | 1:many or M:N per-row field/aggregate | Mark `external-projection-required`; never fetch once per row. |+| **Detail/Form/Modal** | 1:many | Scaffold a bounded chained `*Service.getAll(...)` with `_<parentid>_value eq '${id}'` filter. |+| **Detail/Form/Modal** | M:N | Mark `external-projection-required` unless the plan names a generated intersect-table service and its exact bounded query contract. Never apply an N:1 lookup filter to an M:N table. |-A calculated column lives on the parent entity and resolves its value via a dotted-path formula traversing N:1 lookups. The Dataverse server computes it at read time, so the screen sees it as an ordinary column in `select: [...]`.+Verification: every UI field must have a primary `select`, formatted lookup, or+bounded chained fetch. Otherwise return+`BLOCKED: <field> on <screen> requires an external projection`.-**Naming convention:** `<prefix>_<resolved_field>_calc` — e.g. `cr3e9_gatename_calc`, `cr3e9_flightnumber_calc`. The `_calc` suffix is mandatory; it tells the screen-builder this is a denormalized read-only field (never write to it, never put it in a create/update payload).+### Pattern A: Formatted lookup annotation-**Adding the column:** done by the data-model-architect in its Step 6a Cross-entity Read Audit (writes a row to the `### Cross-entity Reads` subsection of `_dm_section.md`), then created by `/setup-datamodel` Phase 6.1b (or `/add-dataverse` Phase 6.1b for existing apps) via `scripts/create-calculated-column.js`.--**Screen-builder consumption** — once the calc column exists in `src/generated/models/<Entity>Model.ts`, just add it to `select`:+For the primary display value of a direct lookup, select the lookup ID and read+the formatted annotation already returned by Dataverse:```typescript-// Before — gate name unavailable, renders "—"const res = await Cr3e9_inspectionsService.getAll({select: ['cr3e9_inspectionid', 'cr3e9_status', '_cr3e9_flightid_value'],top: 50,});-// After — calc column added at data-model layer, one round trip-const res = await Cr3e9_inspectionsService.getAll({- select: [- 'cr3e9_inspectionid',- 'cr3e9_status',- '_cr3e9_flightid_value',- 'cr3e9_gatename_calc', // ← from calc column- 'cr3e9_flightnumber_calc', // ← from calc column- ],- top: 50,-});--// In renderItem-<Text>{record.cr3e9_gatename_calc ?? '—'}</Text>+import { lookupName } from '@/utils';+<Text>{lookupName(record, 'cr3e9_flightid') ?? '—'}</Text>```-### Pattern B: Chained fetch (preferred for detail / cold path)+### Pattern B: Chained fetch-A chained fetch is a second `Service.get(...)` (for 1:1) or `Service.getAll(...)` (for 1:many / M:N) inside the screen's load step. Use only on detail screens (one record on screen) or for collections that genuinely need a parent-id filter.+A chained fetch is a second `Service.get(...)` (for 1:1) or+`Service.getAll(...)` (for 1:many) inside the screen's load step. Use only on+detail screens (one record on screen) or for collections that genuinely have a+parent lookup field. M:N reads require an explicit intersect-table service+contract; otherwise they are blocked as `external-projection-required`.**1:1 chain (detail screen only):**@@ -198,7 +200,7 @@ import { lookupName } from '@/utils';<Text>{lookupName(flightResult?.data, 'cr3e9_gateid') ?? '—'}</Text>```-**1:many or M:N chain (any screen — calc columns can't traverse this):**+**1:many chain:**```typescript// app/(app)/inspections/[id]/index.tsx — list defects belonging to this inspection@@ -209,23 +211,31 @@ const defectsResult = await Cr3e9_defectsService.getAll({});```-**Hard rule — NEVER chain inside a list `map()` / `FlatList renderItem`.** That's the N+1 trap: 50 list rows × 1 extra fetch each = 50 extra network calls per page load. Visible scroll jank. Battery drain on mobile. If a list needs cross-entity data, it needs a calc column — not a chained fetch.+**Hard rule — NEVER chain inside a list `map()` / `FlatList renderItem`.**+That is the N+1 trap. Use the direct lookup annotation or omit the field until+an external projection exists.### Limits-- **Calc columns can only traverse N:1** (single-valued navigation properties). 1:many and M:N must use chained fetch.-- **Calc columns cannot reference other calc columns** in the same formula chain (Dataverse limitation — a calc on a calc is rejected at create time).-- **Calc columns are read-only** — never include them in a create/update payload (Dataverse 400s on write).-- **`$filter` on calc columns is restricted** — some operators (`contains`, `startswith`) work, others may not. If a screen needs to filter / sort on a calc-resolved field, query the `microsoft-learn` MCP server first to confirm the exact operator support, or fall back to a chained fetch + client-side filter.-- **Don't denormalize fields that change frequently** — the resolution happens at read time so the value is technically live, but indexes on calc columns may not refresh as fast as the source.+- Formatted lookup annotations expose only the direct lookup's primary display+ value, not arbitrary related columns.+- Chained reads must be bounded and executed once per screen load, never per row.+- A formula/calculated column created manually in Power Apps can be reused only+ when Step 4a validates its source type and exact `FormulaDefinition`.+- This workflow never creates or updates formula definitions through code.### How the screen-builder applies this-The screen-builder's "Cross-entity Field Resolution" rule (in `agents/screen-builder.md`) walks every UI field in its assigned spec, checks for a `<prefix>_<field>_calc` column on the primary entity model, and either selects the calc column OR scaffolds a chained fetch OR returns `BLOCKED` based on the decision table above. See `agents/screen-builder.md` for the exact algorithm.+The screen-builder walks every cross-entity field and selects a formatted+lookup, scaffolds one bounded chained fetch, or returns `BLOCKED` for an+external projection.### How the data-model-architect proposes this-The screen-planner emits a `related_entity_fields` block in each per-screen spec (in `_screens_section.md`) with cardinality + archetype + recommendation. The data-model-architect's Step 6a Cross-entity Read Audit reads that block, derives calc columns for every entry tagged `recommends: calc-column`, and adds them to the `### Cross-entity Reads` subsection of `_dm_section.md`. The orchestrator presents this to the user at Gate 1. See `agents/data-model-architect.md` Step 6a and `agents/screen-planner.md` Step 4 (per-screen spec shape).+The screen-planner emits a `related_entity_fields` block with cardinality,+archetype, and one of `formatted-lookup`, `chained-fetch`, or+`external-projection-required`. The data-model architect audits that every+field has a supported read path; it does not synthesize formula metadata.---@@ -238,9 +248,10 @@ The screen-planner emits a `related_entity_fields` block in each per-screen spec| Filter server-side | `filter` | `contains(name, 'foo')` || Sort | `orderBy` | `['createdon desc', 'cr123_id asc']` || Reduce payload | `select` | `['id', 'name', 'status']` |-| Cross-entity field (list / hot) | calc column | `cr3e9_gatename_calc` in `select` |+| Direct lookup display (list / hot) | formatted lookup annotation | `lookupName(record, 'cr3e9_gateid')` |+| Other cross-entity field (list / hot) | external projection required | omit until supplied || Cross-entity field (detail / cold) | chained `Service.get` | `Cr3e9_flightsService.get(flightId)` after primary fetch |-| expand/join fields | NOT SUPPORTED in current generated options | use calc column or chained fetch — see Cross-entity Reads above |+| expand/join fields | NOT SUPPORTED in current generated options | use formatted lookup or bounded chained fetch |---@@ -249,5 +260,5 @@ The screen-planner emits a `related_entity_fields` block in each per-screen spec- `shared/references/mobile-ui-patterns.md` — pagination is a required rule for List screens that query unbounded tables- `screen-planner` — flags `pagination: cursor` in per-screen spec for List archetypes with unbounded data; emits `related_entity_fields` block per screen- `screen-builder` — applies pagination pattern when spec says `pagination: cursor`; applies the Cross-entity Field Resolution rule on every UI field-- `data-model-architect` — Step 6a Cross-entity Read Audit reads planner's `related_entity_fields` blocks and proposes calc columns-- `/setup-datamodel` and `/add-dataverse` — Phase 6.1b creates calc columns via `scripts/create-calculated-column.js`+- `data-model-architect` — Step 6a verifies every related field has a supported read path+- `/setup-datamodel` and `/add-dataverse` — never synthesize formula definitions; they validate any user-supplied computed dependency before reusediff --git a/plugins/mobile-apps/shared/samples/src/utils/dataverse.ts b/plugins/mobile-apps/shared/samples/src/utils/dataverse.tsindex 21b05b577..05f0746dd 100644--- a/plugins/mobile-apps/shared/samples/src/utils/dataverse.ts+++ b/plugins/mobile-apps/shared/samples/src/utils/dataverse.ts@@ -69,6 +69,19 @@ export function containsFilter(columnLogicalName: string, searchText: string): sreturn `contains(${columnLogicalName}, '${escapeODataString(trimmed)}')`;}+/**+ * Normalizes Dataverse record IDs without enforcing RFC UUID version bits.+ * Dataverse sequential GUIDs can contain values such as `f111` in the third+ * group and remain valid record identifiers.+ */+export function normalizeDataverseGuid(value: string | undefined | null): string | undefined {+ if (!value) return undefined;+ const normalized = value.replace(/[{}]/g, '').toLowerCase();+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(normalized)+ ? normalized+ : undefined;+}+/*** Pre-generate a Dataverse primary-key GUID for create-then-navigate flows.* The Power Apps SDK's `*Service.create()` returns 204 No Content on successdiff --git a/plugins/mobile-apps/shared/samples/src/utils/index.ts b/plugins/mobile-apps/shared/samples/src/utils/index.tsindex 1d4398971..7f0eb2e24 100644--- a/plugins/mobile-apps/shared/samples/src/utils/index.ts+++ b/plugins/mobile-apps/shared/samples/src/utils/index.ts@@ -6,7 +6,7 @@* truncate, pluralize,* choiceLabel, STATUS_TONES,* lookupName, formattedValue, extractSkipToken,- * escapeODataString, containsFilter, newId } from '@/utils';+ * escapeODataString, containsFilter, normalizeDataverseGuid, newId } from '@/utils';*/export { formatDate, formatDateTime, formatRelative } from './formatters';@@ -20,5 +20,6 @@ export {extractSkiptoken,escapeODataString,containsFilter,+ normalizeDataverseGuid,newId,} from './dataverse';diff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.mdindex 419f68a65..257135793 100644--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md@@ -17,7 +17,7 @@ Two paths:## Workflow-1. Verify project & auth → 2. Resolve plan → 3. Setup Dataverse Web API auth → 4. Review existing tables → 5. Create / extend tables → 5d. Create alternate keys → 6. Add data sources → 6b. Publish customizations → 6c. Verify tables → 6d. Write manifest → 7. Inspect generated files → 8. Type-check → 8.5. Offline profile reconciliation → 9. Summary+1. Verify project & auth → 2. Resolve plan/operation manifest → 3. Setup Dataverse Web API auth → 4. Validate manifest or reconcile live metadata → 5. Execute sequential metadata phases → 6. Add data sources → 6b. Publish fallback customizations → 6c. Verify tables → 6d. Write manifest → 7. Inspect generated files → 8. Type-check → 8.5. Offline profile reconciliation → 9. Summary---@@ -40,10 +40,26 @@ Look for `native-app-plan.md` in the project root:test -f native-app-plan.md```-**If present:** read the `## Data Model` section. Extract:-- The reuse / extend / create table+Before reading plan content, inspect `$ARGUMENTS` for the five fast-path+artifact flags in Step 2a. When all are present, only confirm+`native-app-plan.md` exists for hash validation; do not parse its Data Model+section or build operations/service lists from Markdown.++**If present and `<operation_manifest_mode> = fallback`:** read the+`## Data Model` section. Extract:+- The target reconciliation table (`reuse` / `extend` / `create` / `adapt` / `defer` decisions and evidence)- The Mermaid ER diagram (informational)- The "Creation Order" tier list+- Every table referenced by `## Screens`, identity resolution, related-entity fields, forms, dashboards, or shared hooks, including standard reused tables such as `systemuser`, `contact`, and `account`++Build `SERVICE_REQUIRED_TABLES` as the union of:+1. every non-deferred row in Target Reconciliation (`reuse`, `extend`, `create`, or `adapt`);+2. every table in Creation Order;+3. every table named by screen/hook data requirements.++**Hard rule:** `reuse` means "do not mutate schema"; it does **not** mean "skip generated service." If app code reads or writes a reused table, that table must be in `SERVICE_REQUIRED_TABLES`.++Carry forward any `adapt` (auto-renamed) and `defer` (out-of-scope this run) decisions with their recorded reasons, and apply the alias map to every name you use. A data-modelling conflict never halts this skill — it resolves to `adapt` or `defer` and is reported in Step 9.**If absent:** check `$ARGUMENTS` for diagram hints (`*.png`, `*.jpg`, `*.jpeg` filename, `erDiagram` keyword, `||--o{` cardinality syntax).@@ -58,6 +74,32 @@ test -f native-app-plan.mdDefault the answer to (b) so empty/cancel input auto-proceeds. The 99% case (user gave a description but no diagram) skips this prompt entirely.+#### Step 2a — Approved operation-manifest fast path++When `$ARGUMENTS` supplies all five paths below, record+`<operation_manifest_mode> = candidate`:++- `--schema-contract <working_dir>/.tmp/dataverse-schema-contract.json`+- `--approval-receipt <working_dir>/.tmp/mobile-plan-status.json`+- `--execution-reconciliation <working_dir>/.tmp/dataverse-execution-reconciliation.json`+- `--operation-manifest <working_dir>/.tmp/dataverse-operation-manifest.json`+- `--publish-checkpoint <working_dir>/.tmp/dataverse-publish-pending.json`++Do not reconstruct tables, columns, relationships, keys, payloads, tiers, or+service requirements from Markdown on this path. The gate-owned approval receipt binds+the exact structured contract content/hash, final plan hash, and final+screen/service dependency list; `native-app-plan.md` remains the human review+artifact.++An entirely absent fast-path handoff means+`<operation_manifest_mode> = fallback` and preserves the standalone workflow+below, beginning with Step 2 initialization. A partially supplied handoff, or+a supplied manifest/contract/reconciliation/checkpoint that is malformed, stale,+incomplete, or bound to different context/files, must fail closed: print the+exact validation errors and return control to the orchestrator. Never jump to+Step 4 without Step 2 initialization, partially trust a candidate, or mix its+operations with agent-derived operations.+### Step 2.5 — Path A: Parse user-provided diagramUsed when the user has an existing diagram from another tool (Visio, dbdiagram.io, screenshot, hand-drawn).@@ -134,7 +176,9 @@ If empty, instruct `az login` and stop.**Script invocation contract — read this once, all subsequent calls in this skill follow it:**```bash-node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> <METHOD> <apiPath> [--body '<json>'] [--include-headers]+node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> <METHOD> <apiPath> \+ [--body '<json>'] [--include-headers] \+ --tenant-id '<tenantId-from-resolve-environment>'```- Three positional args, in order: `<envUrl>`, `<METHOD>` (GET / POST / PATCH / DELETE), `<apiPath>` (everything after `/api/data/v9.2/`).@@ -142,16 +186,25 @@ node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> <METHOD>- `--include-headers` adds response headers (needed for `OData-EntityId` after a record create).- Output is JSON: `{ "status": <code>, "data": <body> }`. Token refresh on 401 and back-off on 429 are automatic — never wrap with manual retry.+**Pass the resolved tenant explicitly (HARD — saves discovery and survives fresh shells).** `resolve-environment.js` already returned `tenantId` in Step 1. Substitute that literal value into every `--tenant-id` argument; do not rely on an exported or shell-local variable because separate tool executions may use fresh shells.++If the tenant is unknown, omit `--tenant-id` — discovery still works, it is just slower.+Acquire a Dataverse access token and verify connectivity:```bash-node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET WhoAmI+node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET WhoAmI \+ --tenant-id '<tenantId-from-resolve-environment>'```+The explicit tenant is also reused for token refresh after a 401 and takes+priority over shell environment variables and Azure account discovery.+`WhoAmI` is the Dataverse identity endpoint — capital W/A/I (case-sensitive). The response gives `UserId`, `BusinessUnitId`, `OrganizationId` but **does NOT include the publisher prefix**. To get the publisher prefix, query the solution's publisher (defaults to `Default`; pass a different solution name if the env uses a custom solution):```bash-node "${CLAUDE_SKILL_DIR}/../../scripts/detect-publisher-prefix.js" <envUrl> [solutionName]+node "${CLAUDE_SKILL_DIR}/../../scripts/detect-publisher-prefix.js" <envUrl> [solutionName] \+ --tenant-id '<tenantId-from-resolve-environment>'# solutionName defaults to "Default" if omitted```@@ -162,33 +215,302 @@ Capture `customizationprefix` from the solution's publisher (typical value: `cr1Requires the user to hold **System Administrator** or **System Customizer** in this environment.-### Step 4 — Review existing tables+When `<operation_manifest_mode> = candidate`, validate the manifest now against+the resolved environment, tenant (when available), publisher, solution, current+plan bytes, structured-schema bytes, and fresh reconciliation bytes:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --validate "<operation-manifest-path>" \+ --contract "<schema-contract-path>" \+ --approval-receipt "<approval-receipt-path>" \+ --reconciliation "<execution-reconciliation-path>" \+ --plan "<working_dir>/native-app-plan.md" \+ --environment-id "<environmentId>" \+ --env-url "<envUrl>" \+ --tenant-id "<tenantId>" \+ --publisher-prefix "<customizationprefix>" \+ --solution "<solution-uniquename>" \+ --publish-checkpoint "<publish-checkpoint-path>" \+ --require-executable+```++Validation deterministically rebuilds the expected manifest from the bound+structured schema, fresh reconciliation, plan, context, and pending-publish checkpoint, then+compares the complete decisions, services, aliases, phases, API paths, and+bodies. If validation fails, print every reported mismatch and fail closed to+the orchestrator. Do not execute or salvage individual operations and do not+switch a supplied candidate to the standalone fallback.++Validate with `--require-executable`. Step 8 already performed the one fresh+bounded reconciliation for every approved exact table and all of its+columns/relationships/keys, including the child/parent/M:N relationship+capability managed properties. Missing capability evidence fails closed. If+the manifest remains non-executable, report its+verification conflicts to the orchestrator. Do not add another read loop,+change an approved decision, or enter fallback mode. A non-executable+candidate authorizes no metadata write.++If validation with `--require-executable` succeeds, set+`<operation_manifest_mode> = valid` and continue directly to Step 5's manifest+execution branch. This is the fast-v2 path: it skips the repeated+agent-driven full reconciliation, not any safety check.++### Step 4 — Reconcile every planned table and column against the target++If `<operation_manifest_mode> = valid`, print:++> `✓ Approved operation manifest validated — complete fresh reconciliation and derived metadata coverage are bound to this environment.`++Use its `decisions` as the reconciliation matrix and skip the remainder of+Step 4/4a. Continue to Step 5. A valid manifest has no `unverified` items; its+explicit `reuse`, `adapt`, and `defer` rows remain visible in the final+summary.**Print before starting:**-> "→ Querying existing custom tables in the environment…"+> "→ Reconciling every planned table and column against live target metadata before any write…"-Always query before creating:+Do not use the custom-table list as the source of truth, and do not issue one request per table. Fetch **every** plan entry (`Reuse`, `Extend`, or `Create`) — including standard and managed dependencies — in a **single** filtered query that also expands their columns:```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions?\$filter=IsCustomEntity eq true&\$select=SchemaName,LogicalName,DisplayName"+ "EntityDefinitions?\$select=MetadataId,LogicalName,SchemaName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes,PrimaryIdAttribute,PrimaryNameAttribute&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'&\$expand=Attributes(\$select=MetadataId,LogicalName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName,SourceType,SourceTypeMask)" \+ --tenant-id '<tenantId-from-resolve-environment>'```-For each plan entry classified `Reuse` or `Extend`, fetch the table's columns to confirm the match:+Build the `$filter` by OR-ing every planned logical name. This is the [documented way to query multiple table definitions at once](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#basic-retrievemetadatachanges-example), and it replaces 2N requests (one entity GET plus one attributes GET per table) with one. Keep the `$expand` `$select` list to base `AttributeMetadata` properties only — a single query [cannot cast to a derived column type](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#evaluate-other-options-to-retrieve-schema-definitions), so fetch `OptionSet` details separately for the rare column that needs them.-```bash-node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=LogicalName,AttributeType,RequiredLevel"+Read the results as follows:++- **A planned name present in `value[]`** — the table exists. Cache its expanded `Attributes` as that table's **attribute snapshot** for Steps 5a and 5b.+- **A planned name absent from `value[]`** — the table does not exist. This is the equivalent of a 404 in the matrix below.+- Interpret `IsCustomizable` and `CanCreateAttributes` as managed properties and read their `.Value` fields.++If the batched query itself fails (non-2xx), retry it once; if it fails again, split it into per-table queries so one unreadable name cannot hide the rest. Any name still unreadable after that is `unverified`: STOP before writes for that reconciliation scope. Authentication, permission, timeout, and malformed-response failures are not evidence that a name is free. If the URL would exceed a practical length with very many tables, split it into a few filtered queries — still far fewer than one request per table.++**Only if the plan contains alternate keys or M:N relationships**, add the matching expands so Steps 5b and 5d never need their own per-item probes. `EntityDefinitions` also supports expanding [`Keys`, `ManyToManyRelationships`, `ManyToOneRelationships`, and `OneToManyRelationships`](https://learn.microsoft.com/power-apps/developer/data-platform/query-schema-definitions#evaluate-other-options-to-retrieve-schema-definitions):++```text+&$expand=Attributes($select=...),Keys($select=SchemaName,KeyAttributes,EntityKeyIndexStatus),ManyToManyRelationships($select=SchemaName)```-Schema divergence handling is in Step 5b's per-column pre-flight (not a Step 4 prompt). The pre-flight auto-skips columns that already exist with the same type, and STOPs only on incompatible type drift — no separate confirmation needed here.+Do not add these expands when the plan has no keys or M:N relationships — they enlarge the response for no benefit, and standard tables carry many of both.++#### Step 4a — Targeted derived-metadata barrier++The base attribute snapshot is sufficient for ordinary columns, but it cannot+prove that a same-named lookup, choice, Boolean, or computed column has the same+semantics. Before classifying any such existing column as compatible:++1. Write the planned derived-column contract to+ `<working_dir>/.tmp/derived-metadata-expected.json`. Each row contains:+ `table`, `logicalName`, `kind`, `type`, `sourceType`, plus:+ - `lookupTarget` for lookups;+ - exact integer/label `options` for Choice, MultiSelect Choice, and Boolean;+ - exact `sourceTypeMask` and serialized `formulaDefinition` for an explicitly+ approved, maker-created computed dependency.+2. Build one `BATCH-METADATA` GET operation list for the affected existing+ tables only. Reuse one process/token and query:+ - `ManyToOneRelationships` once per child table containing planned lookups;+ - the applicable derived attribute collections+ (`PicklistAttributeMetadata`, `MultiSelectPicklistAttributeMetadata`,+ `BooleanAttributeMetadata`) once per table/type, expanding `OptionSet`;+ - the applicable typed attribute collection once per table/type for any+ explicitly reused computed column, selecting+ `LogicalName,SourceType,SourceTypeMask,FormulaDefinition`.++ Do not issue one process per column and do not scan every customizable table.+ The exact planned names from Step 4 are the scope.+ Write the operation array to+ `<working_dir>/.tmp/derived-metadata-operations.json`, then run:++ ```bash+ node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> \+ BATCH-METADATA derived-reconciliation \+ --operations "$(cat <working_dir>/.tmp/derived-metadata-operations.json)" \+ --tenant-id '<tenantId-from-resolve-environment>'+ ```++ Do not pass `--continue-on-error`; the first unreadable required metadata+ collection must stop the barrier.+3. Any non-2xx response, missing result slot, malformed option metadata, absent+ lookup target, or unavailable `FormulaDefinition` makes that scope+ `unverified`. **STOP before writes.** Authentication, throttling, permission,+ and parse failures are never compatibility evidence.+4. Normalize the live results into+ `<working_dir>/.tmp/derived-metadata-live.json`. Each row uses:+ `table`, `logicalName`, `type`, `sourceType`, `sourceTypeMask`,+ `lookupTargets`, `options: [{ value, label }]`, and `formulaDefinition`.+ Lookup target arrays must contain exactly the approved target. Choice+ mappings must be non-empty with unique integer values and non-empty labels;+ Boolean mappings must contain exactly values 0 and 1. Then run:++ ```bash+ node "${PLUGIN_ROOT}/scripts/validate-derived-metadata.js" \+ --expected "<working_dir>/.tmp/derived-metadata-expected.json" \+ --actual "<working_dir>/.tmp/derived-metadata-live.json"+ ```++5. A lookup is compatible only when its complete target set matches. Planned choice+ values must exist with the same labels; extra live values are allowed.+ Ordinary planned columns require `SourceType` 0. A maker-created computed+ dependency is reusable only when its source type, source-type mask, and exact+ `FormulaDefinition` match the approved artifact; the `Invalid` mask bit+ always blocks reuse.++This phase is read-only and uses the V2 long-lived executor. It must not add+per-column child-process/token overhead back into the fast path.++Build and print a reconciliation matrix before Step 5:++| Target result | Table decision | Column decisions | Action |+|---|---|---|---|+| Present; all planned base and derived metadata compatible | `reuse` | existing columns `reuse` | No schema write. |+| Present; custom columns missing; table customizable and can create attributes | `extend` | compatible `reuse`; absent custom `create` | Queue missing ordinary columns for sequential creation; relationships remain Pass 2. |+| Absent; plan says Create; logical name uses the verified publisher prefix | `create` | ordinary columns `create` inline; lookups deferred | Create once after the complete-payload self-check. |+| Absent; plan says Reuse/Extend or dependency is standard/managed/required-existing | `defer` | dependent columns `defer` | Never recreate a standard or managed table. Drop the dependent lookups/columns from this run, continue with everything else, and list them under Deferred in Step 9. |+| Present; same-name column has incompatible `AttributeType` / `AttributeTypeName.Value` | `extend` | incompatible column `adapt` | Auto-rename the planned column via the probe sequence below, record it in the alias map, and create it alongside the existing one. Never modify or delete the existing column. |+| Present; columns missing but `IsCustomizable.Value=false` or `CanCreateAttributes.Value=false` | `reuse` | missing columns `defer` | The target cannot be extended by this workflow. Reuse the columns that do exist, drop the rest from this run, and list them under Deferred in Step 9. |+| Batched query failed (non-2xx) after retry and per-table split | `unverified` | unknown | STOP before writes for the affected reconciliation scope and surface the concrete environment/auth/permission error. |++`replace` is not an automatic state in this workflow. Replacing a table or column requires an explicitly approved migration with dependency analysis and data movement, so a conflict resolves to `adapt` (rename beside it) or `defer` (leave it out) instead — both of which leave existing data untouched.++**Decide-before-write barrier (HARD):** finish reconciliation for every table and column before the first metadata write. Every item must come out of Step 4 as `reuse`, `extend`, `create`, `adapt`, or `defer` — never as an unresolved conflict. Deciding renames up front is what keeps relationships, screens, and sample data pointing at the same names.++**No dead ends (HARD):** a data-modelling conflict must never stop the run. Adapt it (rename beside the existing object) or defer it (drop it from this run), then keep going and report it in Step 9. Only environment faults stop this skill — failed auth, an environment mismatch, or a target the user has no privilege to write to. Those are not data-modelling problems and the user cannot resolve them by editing the plan.++**Idempotency criterion (HARD):** re-running this skill against an already-applied plan MUST perform **zero** metadata writes. Every table, column, relationship, key, and calc column resolves to `reuse` or an "already exists, skipped" outcome from the Step 4 snapshot. If a re-run issues any POST, the reconciliation missed something — report it rather than writing. Use this as the acceptance check after any change to Steps 4, 5, or 5a–5d.### Step 5 — Create / extend tables+#### Valid operation-manifest execution branch++When `<operation_manifest_mode> = valid`, do not have an agent rebuild request+bodies. Read `execution.phases` in this fixed order:++1. `tableCreates` — dependency-tier table creates with all ordinary columns+ inline;+2. `extensions` — missing ordinary columns on existing tables;+3. `relationships` — lookups/1:N and M:N after both endpoints exist;+4. `alternateKeys` — after target tables and columns exist;+5. `publish` — one `PublishXml` operation only when earlier phases contain+ writes or a bound publish-pending checkpoint requires retry.++For each non-empty phase, write just that phase's `operations` array to+`<working_dir>/.tmp/dataverse-operation-phase-<name>.json`. Read+`integritySha256` and `binding.reconciliationSha256` from the validated+manifest, then execute every phase with the same project-local atomic journal:++```bash+EXECUTION_JOURNAL="<working_dir>/.tmp/dataverse-metadata-execution-journal.json"+ALL_MANIFEST_OPERATIONS="<working_dir>/.tmp/dataverse-operation-all.json"+# Write the flattened operations from every manifest phase to ALL_MANIFEST_OPERATIONS once.++node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> \+ BATCH-METADATA "manifest-<phase-name>" \+ --operations "$(cat <working_dir>/.tmp/dataverse-operation-phase-<name>.json)" \+ --solution "<solution-uniquename>" \+ --tenant-id "<tenantId>" \+ --journal "$EXECUTION_JOURNAL" \+ --manifest-file "$OPERATION_MANIFEST" \+ --manifest-hash "<manifest.integritySha256>" \+ --reconciliation-hash "<manifest.binding.reconciliationSha256>" \+ --manifest-operations "$(cat "$ALL_MANIFEST_OPERATIONS")"+```++Wait for the entire phase to finish before starting the next. This executor is+not OData `$batch`; it sends one request at a time, reuses one token, preserves+manifest order, and stops on the first non-2xx response. Never pass+`--continue-on-error`, never parallelize phases or operations, and never+execute `service.requiredTables` through BATCH-METADATA.+The runner verifies the manifest file's integrity hash, requires the supplied+operation array to equal one complete manifest phase byte-for-byte, and rejects+that phase until every operation in preceding phases is journal-complete.++The runner atomically writes `inFlight` before each request and records each+successful operation before moving to the next. Completed fingerprints are+based on stable request identity, not the positional index; the complete+manifest's unique zero-based order is validated separately. Completed+fingerprints are skipped on an exact resume. If a process may have exited after Dataverse+accepted a request but before the journal completion write, the runner fails+with `UNCERTAIN_METADATA_OPERATION`; do not replay the old operation array.+Transport loss during a metadata mutation is immediately uncertain and is+never retried in-process; reads may retain transport retry behavior.+Perform a new bounded exact reconciliation, rebuild and revalidate the full+manifest, then resume with both new hashes. The runner mechanically treats an+uncertain operation omitted by the new manifest as already applied/superseded,+or retries it only when the fresh reconciliation proves it is still required.++If `summary.metadataOperationCount` is zero, issue **zero metadata POSTs** and+print `↻ Dataverse schema already fully applied — zero metadata writes.` This+is the required idempotent rerun behavior after successful publish. A manifest+with zero schema operations but one checkpoint-driven `PublishXml` operation+must run that publish retry; it is not a zero-write completion.++The manifest builder writes+`<working_dir>/.tmp/dataverse-publish-pending.json` before any schema POST when+publish will be required. Leave this checkpoint in place after any schema or+publish failure. Delete it only after the validated `publish` phase returns+success. The next build validates its environment/solution/plan/contract+binding and integrity, merges its table list into the publish phase, and+therefore retries `PublishXml` even when every schema create is now+idempotently skipped.++On a hidden POST-time name collision, stop at the failed operation and discard+all not-yet-run phase arrays. The execution script must not choose `Adapt` or a+rename. Return to the existing planning revision path so the structured schema+artifact carries the approved `Adapt` names. Then perform a fresh bounded+reconciliation and regenerate the complete aliases, downstream relationship+and key bodies, service-required names, phases, manifest hashes, and phase+files. Revalidate before resuming through the journal. Never continue an old+array after a rename. Any non-collision failure stops the metadata path with+its exact result.++Before overwriting the old manifest, preserve its path. After the revised plan+and structured schema are approved through the existing flow, the top-level+planner/orchestrator must refresh the structured service dependencies and+`mobile-plan-status.json` receipt. This skill cannot create or restamp it.+Bind the contract through that pre-existing receipt, then roll the existing+publish checkpoint forward:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --roll-forward-checkpoint "$PUBLISH_CHECKPOINT" \+ --previous-manifest "$OPERATION_MANIFEST" \+ --journal "$EXECUTION_JOURNAL" \+ --contract "$SCHEMA_CONTRACT" \+ --approval-receipt "$APPROVAL_RECEIPT" \+ --plan "<working_dir>/native-app-plan.md" \+ --output "$PUBLISH_CHECKPOINT" \+ --environment-id "<environmentId>" \+ --env-url "<envUrl>" \+ --tenant-id "<tenantId>" \+ --publisher-prefix "<customizationprefix>" \+ --solution "<solution-uniquename>"+```++This retains prior checkpoint bindings/tables as integrity-protected history,+keeps earlier successful tables publication-pending, and maps only the+journal-proven failed collision table to its revised in-contract alias. It+fails closed if a completed write would disappear from the revised contract or+change definition: completed tables/inline columns, extension columns,+relationships (including cascade behavior), and alternate keys must each map+to an equivalent revised structured component. It also rejects any unrelated+out-of-contract publish target. Only after this succeeds may Step 8 overwrite+the operation manifest.++The manifest builder never emits calculated/rollup/formula creation. Reused+computed dependencies have already crossed the exact derived-metadata barrier;+unsupported projections are explicit `defer` rows. After the `publish` phase succeeds, delete the publish checkpoint and continue+to Step 6. When there were zero writes and no checkpoint, continue without+deleting anything. Skip the+fallback mutation instructions in Steps 5a–5d and skip Step 6b because publish+was already part of the validated phase order.+**Print before starting:**> "→ Creating/extending <N> tables in tier order (sequential — Dataverse serializes metadata writes). For each: pre-flight check, then 'Creating <table>…' before the POST and '✓ <table>' on 2xx response."-> **⚠️ Concurrency rule — do not violate.** All Dataverse metadata operations in Steps 5, 6, and 6b are **strictly sequential**: issue one HTTP request, wait for a 2xx response, then issue the next. Do NOT batch, parallelize, or fire concurrent requests. Dataverse serializes metadata writes via an exclusive lock; parallel calls return `429 TooManyRequests`, `MetadataLockHeldException`, or `404 EntityNotFound` for lookups whose parent hasn't committed yet.+> **⚠️ Concurrency rule — do not violate.** All Dataverse metadata operations in Steps 5, 6, and 6b are **strictly sequential**: issue one HTTP request, wait for a 2xx response, then issue the next. Do NOT parallelize or use OData `$batch`. Dataverse serializes metadata writes via an exclusive lock; parallel calls return `429 TooManyRequests`, `MetadataLockHeldException`, or `404 EntityNotFound` for lookups whose parent hasn't committed yet.>> Specifically:> - **Within a tier:** create tables one at a time.@@ -196,35 +518,62 @@ Schema divergence handling is in Step 5b's per-column pre-flight (not a Step 4 p> - **Lookups:** POST to `/RelationshipDefinitions` only **after** both endpoint tables exist and have returned 2xx.> - **Extensions:** column POSTs to an existing table are also serial — same lock applies.-#### Step 5a — Pre-flight collision check (per table, before each POST)+For multiple already-reconciled operations, prefer the local `BATCH-METADATA`+executor. It is **not** OData `$batch`: one Node process reuses one token and+issues requests strictly one at a time in array order, stopping on the first+non-2xx response by default.-Step 4 listed *known* custom tables you intend to reuse. Step 5a probes for *unknown* problems on a per-create basis: name-prefix collisions from stale solutions, soft-deleted tombstones, and reserved system names. Skipping this check costs ~1 minute per failed POST (Dataverse takes its time returning the conflict error) and can leave Tier 0 partially created when a Tier 1 lookup fails on a phantom parent.+```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> \+ BATCH-METADATA schema-writes \+ --operations '<ordered-json-array>' \+ --solution '<solution-uniquename-from-memory-bank>' \+ --tenant-id '<tenantId-from-resolve-environment>'+```++Each operation is `{ "index", "method", "apiPath", "body" }`; an operation may+override the command-level `solution`. Build the array only after the full+metadata snapshot and desired/live diff. Preserve dependency order: new tables+with ordinary columns inline, extension columns, relationships, projections,+then alternate keys. Never pass `--continue-on-error` for schema creation. The+result includes per-operation `status` and `durationMs`; after a failure,+reconcile that component and resume with only the remaining operations.++#### Step 5a — Pre-flight collision check (from the Step 4 snapshot)-**For every `Create` entry, before its POST, probe the target logical name:**+Before each create, confirm the target name is actually free: name-prefix collisions from stale solutions, reserved system names, and soft-deleted tombstones all fail the POST, and Dataverse takes ~1 minute to return the conflict error. A failure here can leave Tier 0 partially created and make a Tier 1 lookup fail on a phantom parent. Step 4 already collected this evidence for every planned name, so this step reads it rather than re-querying.++**For every `Create` entry, resolve its target state from the Step 4 batch — do not re-query per table.** Step 4 already fetched every planned logical name, so reuse that result:++| Step 4 result for this name | Meaning | Action |+|---|---|---|+| **Absent from `value[]`** | Name is free | Proceed with POST. |+| **Present** + `IsCustomEntity: true` + `MetadataId` matches memory-bank | We created this earlier — idempotent re-run | Skip the POST, mark as created, continue. |+| **Present** + `IsCustomEntity: true` + `MetadataId` *not* in memory-bank | Foreign collision | Reconcile live columns and customization properties below; never auto-extend an uncustomizable target. |+| **Present** + `IsCustomEntity: false` | Reserved system table name | Auto-recover via rename (see below). |++Only re-probe a single name when Step 4's batch did not cover it (for example a rename candidate generated later in this step):```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions(LogicalName='<prefix>_<table>')?\$select=MetadataId,LogicalName,IsCustomEntity"+ "EntityDefinitions(LogicalName='<prefix>_<table>')?\$select=MetadataId,LogicalName,IsCustomEntity,IsManaged,IsCustomizable,CanCreateAttributes" \+ --tenant-id '<tenantId-from-resolve-environment>'```-Branch on the response:+Tombstones and hidden collisions are **not** reliably visible to either form — Dataverse can report a name as free and still reject the POST minutes later. Those are caught by the POST-time collision rescue below, which is the real safety net:-| Status / body | Meaning | Action |+| POST response | Meaning | Action ||---|---|---|-| **404 NotFound** | Name is free | Proceed with POST. |-| **200 OK** + `IsCustomEntity: true` + `MetadataId` matches memory-bank | We created this earlier — idempotent re-run | Skip the POST, mark as created, continue. |-| **200 OK** + `IsCustomEntity: true` + `MetadataId` *not* in memory-bank | Foreign collision | Auto-recover (see below) — do NOT prompt. |-| **200 OK** + `IsCustomEntity: false` | Reserved system table name | Auto-recover via rename (see below). || **5xx** with `0x80060890` or message `"object with same name exists in solution"` | Tombstone (soft-deleted, ~30 min purge TTL) | Auto-recover via rename (see below). |-| **400** with `0x80044363`, `"schema name ... is not unique"`, or `"same name already exists"` | Hidden Dataverse collision / recent-delete tombstone not visible to `EntityDefinitions` GET | Auto-recover via rename (see below), then retry the POST once. |+| **400** with `0x80044363`, `"schema name ... is not unique"`, or `"same name already exists"` | Hidden Dataverse collision / recent-delete tombstone | Auto-recover via rename (see below), then retry the POST once. |-**Important:** Step 5a is a best-effort preflight, not the final authority. Dataverse can return 404 for a recently deleted table and still reject the create POST minutes later because the schema name remains reserved internally. Treat that POST-time 400 as a recoverable name collision, not a data-model failure.+**Important:** treat a POST-time collision as a recoverable name conflict, not a data-model failure — the schema name can stay reserved internally after a delete even when metadata reports it as free.#### Auto-recovery — reuse/extend first, rename as last resort**Priority order when Step 5a hits a name collision:**-1. **Adopt as Extend (preferred)** — if the existing table's `Attributes` overlap with the planned columns by ≥50%, or the existing table is the same conceptual entity: add only the missing columns via per-column POST (Step 5b Extend path). No prompt needed — extend automatically and log `→ Extending existing <original> with <N> missing columns.`+1. **Adopt as Extend (preferred)** — only if the existing table is the same concept, every same-name column is type-compatible, planned missing columns are custom additions, and live `IsCustomizable.Value` plus `CanCreateAttributes.Value` both permit extension. Add only the missing columns via Step 5b and log `→ Extending existing <original> with <N> missing columns.`2. **Adopt as Reuse** — if the existing table's schema already covers all planned columns: skip Step 5b for this entry, keep it in Step 6 for service generation. No prompt. Log `→ Reusing existing <original> (all required columns present).`3. **Rename and Create (last resort)** — only when the existing table is a fundamentally different entity (e.g., planned table is an inspection log but existing `<original>` is a payroll record — incompatible concept, incompatible columns). Prompt the user before proceeding.@@ -232,8 +581,9 @@ Branch on the response:| Situation | Action ||---|---|-| Foreign collision + schema overlap ≥50% | Auto-Extend (no prompt) |+| Foreign collision + compatible concept/schema + extension allowed | Auto-Extend (no prompt) || Foreign collision + all planned columns present | Auto-Reuse (no prompt) |+| Foreign collision + incompatible column or extension forbidden | Auto-rename the conflicting column beside it, or defer it (no prompt) || Foreign collision + incompatible concept | Prompt (see below) || Reserved system name | Auto-rename (no prompt) || Tombstone (0x80060890 / same-name-exists) | Auto-rename (no prompt) |@@ -243,11 +593,11 @@ Branch on the response:```| Option | What it means ||---|---|-| Extend existing (default) | Add required columns to <original>. Safer — avoids duplicate tables. |-| Rename and Create | Auto-renamed to <new>. Existing table left untouched. |+| Rename and Create (default) | Use a free custom logical name for the genuinely different entity. Existing table stays untouched. |+| Reuse existing as-is | Point the generated services at the existing table and skip the planned columns it lacks. |```-Default to "Extend existing" so an empty answer auto-proceeds. Rename-and-Create is the opt-in exception, not the default.+Never offer Extend for an incompatible concept or column shape. This prompt is a preference, not a gate: an empty, skipped, or unanswered response defaults to **Rename and Create** so the run always proceeds.Maintain a run-level logical-name alias map for every auto-rename. Example:@@ -267,7 +617,7 @@ For each candidate in order, GET `EntityDefinitions(LogicalName='<candidate>')?$- 404 → free, **take it**, stop probing.- 200 or 5xx (collision) → next candidate.-If all 4 probes collide, surface a `BLOCKED: cannot find a free alternative for <original>` and stop.+If all 4 collide, keep probing `<original>3`, `<original>4`, … through `<original>20`. This sequence is designed never to dead-end: if even those collide, use `<original><4-char run token>`, which is unique to this run. Never abandon a table for want of a free name.**On a successful auto-rename, do these in order BEFORE the POST:**@@ -289,21 +639,28 @@ If the Step 5b table POST fails after a 404 preflight with any Dataverse name-co- message contains `same name already exists`- message contains `object with same name exists in solution`-First attempt auto-Extend: re-GET the existing table's attributes and compare with the plan. If ≥50% overlap, switch to Extend path (add missing columns). Otherwise, run the auto-rename probe sequence, update `native-app-plan.md`, `## Screens`, `memory-bank.md`, and the run-level alias map, then retry the table POST exactly once with the resolved name. Print:+First attempt auto-Extend: compare the plan against that table's attribute snapshot from Step 4 (re-fetch only if it is absent). If ≥50% overlap, switch to Extend path (add missing columns). Otherwise, run the auto-rename probe sequence, update `native-app-plan.md`, `## Screens`, `memory-bank.md`, and the run-level alias map, then retry the table POST exactly once with the resolved name. Print:> `→ Dataverse still has <original> reserved from a recent delete/hidden collision. Using <new> and continuing.`-If the retry also returns a collision signature, continue probing the remaining candidates. If all candidates collide, return `BLOCKED: cannot find a free alternative for <original>`.+If the retry also returns a collision signature, continue probing the remaining candidates, then the numeric tail, then the run-token form described above.**On successful POST**, immediately re-GET to capture the server-assigned `MetadataId` and write it to memory-bank (Step 6d updates `.datamodel-manifest.json`; you also append to `memory-bank.md` under "Created tables" with the GUID and solution name). This lets future `/add-dataverse` runs distinguish "we own this" from "name collision."#### Step 5b — Create / extend+Run this step in two explicit passes:++1. **Pass 1 — tables + ordinary columns:** create every new table with all planned non-lookup columns inline, then extend existing tables with any missing non-lookup columns. Computed formula definitions are never synthesized by this workflow.+2. **Pass 2 — lookups + relationships:** only after Pass 1 has succeeded for every tier, create the planned `RelationshipDefinitions`. A lookup is created by its relationship and must not appear in a table's initial `Attributes` array.++Both passes remain strictly sequential. Do not use `$batch` for metadata writes.+For each `Create` decision, in **tier order** (Tier 0 → Tier 1 → Tier 2 → …), POST a new EntityDefinition. Skip if Step 5a returned a known-self match (idempotent).> **⚠️ Inline ALL planned columns into the Create POST body — do NOT POST columns individually.**>-> Dataverse processes the `Attributes: [...]` array atomically with the table create. Inline form: 1 round trip, ~3-8s. Per-column form: N+1 round trips, each ~3-8s. For a 5-column table that's 24s saved per table on the lock-serialized metadata path.+> Dataverse accepts all non-lookup columns in the initial table's `Attributes: [...]` array. Inline form: 1 round trip, ~3-8s. Per-column form: N+1 round trips, each ~3-8s. For a 5-column table that's roughly 24s saved on the lock-serialized metadata path. Do not describe this metadata create as transactionally atomic: if the request fails after Dataverse starts processing it, the table or some attributes may remain, which is why the recovery path below exists.>> **Wrong** (N round trips):> ```json@@ -334,9 +691,20 @@ For each `Create` decision, in **tier order** (Tier 0 → Tier 1 → Tier 2 →```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> POST EntityDefinitions \--body '<json-body-with-all-columns-inline>' \- --solution '<solution-uniquename-from-memory-bank>'+ --solution '<solution-uniquename-from-memory-bank>' \+ --tenant-id '<tenantId-from-resolve-environment>'```+**Complete-payload self-check (HARD — do this before the POST, no extra tooling):** re-read the body you just built against the plan and confirm all five statements. If any fails, fix the body and re-check; never POST a partial table and repair it with per-column POSTs.++1. **Every planned ordinary column is present** — String, Memo, Integer, BigInt, Decimal, Money, DateTime, Boolean, Choice, MultiSelect Choice, Image, and File. Count `Attributes[]` and compare with the plan's column count for this table.+2. **No lookup metadata is inline** — no `LookupAttributeMetadata`, `CustomerAttributeMetadata`, or `OwnerAttributeMetadata`. Those are created by their relationship in Pass 2.+3. **No deferred or server-owned column is inline** — no primary-id column and no calculated/rollup column (Step 5c owns those).+4. **Exactly one `IsPrimaryName: true` attribute exists**, and `PrimaryNameAttribute` matches its `SchemaName` (lowercased logical form).+5. **No duplicate `SchemaName`** in `Attributes[]` (compare case-insensitively).++Microsoft documents both halves of this contract: [ordinary columns may be included when the table is created](https://learn.microsoft.com/power-apps/developer/data-platform/webapi/create-update-column-definitions-using-web-api#create-columns), while a [lookup is created with its one-to-many relationship](https://learn.microsoft.com/power-apps/developer/data-platform/webapi/create-update-entity-relationships-using-web-api#create-a-one-to-many-relationship). `dataverse-request.js` stays the only script in this path — it already owns auth, retry, `--solution` routing, and 401/429 handling.+Body skeleton — **all planned columns inline in `Attributes: [...]`** (this example shows primary + 3 additional; expand the array to fit every column from the plan):> **⚠️ `IsAvailableOffline` + `ChangeTrackingEnabled` MUST be set to `true` at create time** for any table the app intends to make available offline. Without these two flags the table cannot be added to a `mobileofflineprofile`, and `/setup-offline-profile` will have to fix them via a separate metadata PUT (the `/enable-tables-offline` skill handles that, but it doubles the metadata-lock-serialized round trips). Empirically verified 2026-05-18 in the chanel-rm demo: 7 custom tables created without these flags caused 7 prereq-revert drift entries; fixed by post-hoc enablement. Default these to `true` for all UserOwned tables created by `/add-dataverse` unless the user has explicitly opted out of offline support. The flags are no-ops at runtime for apps that don't use offline profiles.@@ -398,36 +766,38 @@ Body skeleton — **all planned columns inline in `Attributes: [...]`** (this exFor each `Extend` decision, POST a new column to the existing table.-> **⚠️ Per-column pre-flight (HARD — required for idempotent re-runs).** Before each column POST, probe whether the column already exists. This catches:-> - Partial failures from a prior `EntityDefinitions` POST that created the table + some columns but not all (the body is non-atomic — server commits each Attribute one at a time).-> - User re-runs after fixing a typo in one column's metadata.-> - Re-applying a plan after a network drop mid-Step-5b.->-> Without this check, the second POST returns `400: attribute already exists` (`0x80044153`) and the run aborts mid-tier.+> **⚠️ Table-level pre-flight (HARD — required for idempotent re-runs).** Reuse the complete attribute snapshot fetched for this table in Step 4. If the table was discovered only during collision recovery, or no current snapshot exists, fetch all attributes exactly once:>> ```bash> node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \-> "EntityDefinitions(LogicalName='<table>')/Attributes(LogicalName='<column>')?\$select=LogicalName,AttributeType"+> "EntityDefinitions(LogicalName='<table>')/Attributes?\$select=MetadataId,LogicalName,SchemaName,AttributeType,AttributeTypeName,RequiredLevel,IsManaged,IsCustomizable,IsPrimaryId,IsPrimaryName" \+> --tenant-id '<tenantId-from-resolve-environment>'> ```>-> | Status | Meaning | Action |-> |---|---|---|-> | **404** | Column doesn't exist | Proceed with POST. |-> | **200** + `AttributeType` matches the spec | Already created (idempotent re-run) | Skip the POST, log `↻ <column> (already exists, skipped)`, continue. |-> | **200** + `AttributeType` differs from the spec | Schema drift — column type was changed manually OR plan changed since last run | **STOP** and surface to user: "Column `<column>` exists but is `<existingType>`, plan expected `<plannedType>`. Dataverse does NOT allow column-type changes via API — you must delete the column manually and re-run." Do NOT silently overwrite. |+> Build a local `{ lowerCaseLogicalName → { AttributeType, AttributeTypeName, IsManaged, IsCustomizable } }` map and classify **every** planned non-lookup column before issuing any POST. Prefer `AttributeTypeName.Value` when `AttributeType` is `Virtual`, so File and Image columns are not incorrectly treated as compatible generic virtual attributes:+>+> | Snapshot result | Action |+> |---|---|+> | Name exists and `AttributeType` matches | Skip it and log `↻ <column> (already exists, skipped)`. |+> | Name exists and `AttributeType` differs | Dataverse does not allow column-type changes via API, so **auto-rename the planned column** using the same probe sequence (`<column>v2` → `<column>v3` → `<column>2` → …), add it to the alias map, and create it beside the existing one. Log `→ <column> exists as <existingType>; created <newName> as <plannedType> instead.` Never modify or delete the existing column. |+> | Name is absent | Add it to the ordered missing-column queue. |+>+> This single snapshot catches partial creates, corrected re-runs, and network-drop recovery without paying one GET round trip per column.-After pre-flight returns 404, POST the column (always pass `--solution`):+After the complete comparison passes, POST the missing-column queue **one column at a time, sequentially** (no `$batch`; always pass `--solution`):```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> POST \"EntityDefinitions(LogicalName='<table>')/Attributes" \--body '<column-json>' \- --solution '<solution-uniquename-from-memory-bank>'+ --solution '<solution-uniquename-from-memory-bank>' \+ --tenant-id '<tenantId-from-resolve-environment>'```-**The same pre-flight applies inside Create POSTs that include initial Attributes.** If a Create POST partially failed earlier (table + some columns committed), the retry path is to do **per-column** pre-flight + POST instead of re-POSTing the whole `EntityDefinitions` body — re-POSTing returns `0x80060888 entity already exists`. After Step 5a says "table exists with our MetadataId" (idempotent re-run match), iterate the planned `Attributes` and pre-flight each one against `/Attributes(LogicalName='<column>')`, then POST only the missing ones.+**Recovery after a partial Create:** do not re-POST the whole `EntityDefinitions` body because the table now exists and Dataverse returns `0x80060888`. Fetch that table's complete attribute snapshot once, run the same local comparison, and sequentially POST only the missing non-lookup columns. This is the only time a table originally classified as Create should use the per-column path.Column shapes that have non-obvious gotchas (handle carefully):+- **Pass-2 barrier (HARD)** — do not create any lookup or relationship while Pass 1 is still creating or extending tables. Accumulate relationship definitions, wait until every table and ordinary column has returned 2xx, then process the relationships sequentially in dependency order.- **Lookup** — POST to `/RelationshipDefinitions`, not `/Attributes`.> **⚠️ Do NOT improvise the body. Copy the skeleton below verbatim and replace only the placeholders in `<>` brackets.**@@ -470,9 +840,20 @@ Column shapes that have non-obvious gotchas (handle carefully):node "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> POST \RelationshipDefinitions \--body '<json-body-from-skeleton-above>' \- --solution '<solution-uniquename-from-memory-bank>'+ --solution '<solution-uniquename-from-memory-bank>' \+ --tenant-id '<tenantId-from-resolve-environment>'```+ **Pre-flight the lookup (HARD — required for idempotent re-runs).** A lookup can only pre-exist if the **referencing (child) table** already existed at Step 4, so when the child was created in this run, skip the probe and POST. Otherwise look for the lookup's foreign-key column — the lowercased `Lookup.SchemaName`, e.g. `<prefix>_<parent>id` — in that child table's Step 4 attribute snapshot:++ | Snapshot result | Action |+ |---|---|+ | Present with `AttributeType: Lookup` | Skip the POST and log `↻ <SchemaName> (relationship already exists, skipped)`. |+ | Present with any other `AttributeType` | A non-lookup column already owns that name. Auto-rename the lookup's `Lookup.SchemaName` via the probe sequence, record it in the alias map, and POST the relationship with the new name. Never overwrite the existing column. |+ | Absent | POST the relationship. |++ This costs no extra round trip: the referencing attribute is an ordinary attribute on the child table, so it is already in the snapshot Step 4 fetched. Without this check a re-run POSTs a duplicate relationship and fails the run mid-Pass-2.+- **Many-to-Many (M:N)** — also POST to `/RelationshipDefinitions`, but with `ManyToManyRelationshipMetadata`. Dataverse creates an auto-named intersect table.> **⚠️ Do NOT improvise the body.** Required fields: `SchemaName`, `Entity1LogicalName`, `Entity2LogicalName`, `IntersectEntityName`, and the two `AssociatedMenuConfiguration` blocks. Do not include lookup or cascade fields — those are 1:N concepts.@@ -499,9 +880,9 @@ Column shapes that have non-obvious gotchas (handle carefully):}```- **Pre-flight M:N:** GET `RelationshipDefinitions(SchemaName='<prefix>_<table1>_<table2>')?$select=SchemaName` — 404 → proceed; 200 → skip (already exists).+ **Pre-flight M:N:** a relationship can only pre-exist on a table that already existed at Step 4. If **either** endpoint was just created in this run, skip the probe — nothing can be there. Otherwise read `ManyToManyRelationships` from that table's Step 4 snapshot: present → skip (already exists); absent → proceed. Query `RelationshipDefinitions(SchemaName='<prefix>_<table1>_<table2>')?$select=SchemaName` only when the snapshot did not cover it.- **In the generated service:** M:N relationships are queried via the intersect entity name (e.g., `cr123_tag_inspection`) — the SDK does not expose a direct M:N navigation helper; the screen-builder must query the intersect table directly or via a calculated column approach. Flag this in the Step 7 summary if any M:N relationships are created.+ **In the generated service:** M:N relationships are queried via the intersect entity name (e.g., `cr123_tag_inspection`) — the SDK does not expose a direct M:N navigation helper; the screen-builder must query the intersect table directly. Flag this in the Step 7 summary if any M:N relationships are created.- **Column `@odata.type` and required fields — reference table (verified against Dataverse OData API):**@@ -547,38 +928,24 @@ If the column type is not a simple string/int/boolean, surface a one-line confirAfter all mutations, re-run the existing-tables query (Step 4) to confirm everything landed.-### Step 5c — Create calculated columns from `### Cross-entity Reads`--**Print before starting:**-> "→ Creating calculated columns from the plan's ### Cross-entity Reads subsection (one HTTP call per row). Skip if the subsection is absent."--**Run condition:** the planner / data-model-architect emits a `### Cross-entity Reads (auto-derived from screen plan)` subsection inside `## Data Model` of `native-app-plan.md` when the screen plan reads any field from a related entity. Parse that subsection. If absent or empty, **skip Step 5c entirely** — proceed to Step 6.+### Step 5c — Enforce the supported computed-column boundary-This step exists because of the runtime constraint documented at [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads): the SDK has no `$expand`, so cross-entity fields on hot paths (lists, dashboards, tab roots) MUST be denormalized via calculated columns at the data-model layer. The `### Chained-fetch fields (informational)` subsection (if present) is documentation only — the screen-builder handles those at scaffold time, no schema change.+Dataverse metadata exposes `FormulaDefinition`, but Microsoft explicitly does+not support defining calculated, rollup, or formula expressions through code.+Legacy workflow XAML and generated formula serialization must not be synthesized.-**Algorithm:**+- Do not invoke `create-calculated-column.js`; it is a fail-closed guard for+ legacy callers.+- Cross-entity fields must use a supported formatted lookup annotation or+ bounded chained fetch as documented in `data-performance.md`.+- For a hot list field that cannot use either path, mark it+ `external-projection-required` and omit it from this mutation run. The user+ may create a formula column in Power Apps or supply another server-owned+ projection outside this PR, then rerun Step 4a to validate and reuse it.+- Never create an ordinary copied field without an explicit refresh owner.-1. Parse the `### Cross-entity Reads` table. Each row has columns: `Calc column | On table | Type | Resolves | Driven by`.-2. **Run AFTER all regular columns + relationships from Step 5b have been created** (the formula chain references real columns + lookups; creating the calc column before its dependencies returns HTTP 400 from Dataverse).-3. **Per row**, invoke the helper:-- ```bash- node "${PLUGIN_ROOT}/scripts/create-calculated-column.js" <envUrl> \- --table <on-table> \- --column <calc-column-logical-name> \- --type <Type column verbatim: string|datetime|decimal|integer|boolean> \- --formula "<dotted path from Resolves column, e.g. cr3e9_flightid.cr3e9_gateid.cr3e9_gatename>" \- --display "<human-friendly label inferred from the column name minus _calc suffix>" \- --solution '<solution-uniquename-from-memory-bank>'- ```--4. **One at a time, sequentially.** Calc-column creation is metadata mutation — same concurrency rule as table creation. Print `✓ <calc-column>` after each success.-5. **On failure** — the helper script prints the OData error inline. Common cases:- - `400 — formula references unknown attribute` → the relationship or column the formula needs has not been created yet. Verify Step 5b finished cleanly before retrying.- - `400 — calculated formula not allowed on this navigation` → the dotted path tries to traverse 1:many or M:N. The architect should have caught this at Step 6a; flag in summary, skip the row, continue.- - Surface non-recoverable errors to the user with the offending row, then proceed to the next row. Do NOT abort the whole step on one bad row.--6. After all rows are processed, the publish step (Step 6b) below picks up calc columns automatically — no extra publish call needed.+Reference:+https://learn.microsoft.com/power-apps/developer/data-platform/specialized-columns### Step 5d — Create alternate keys for unique business identifiers@@ -595,7 +962,8 @@ This step exists because of the runtime constraint documented at [`shared/referenode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> POST \"EntityDefinitions(LogicalName='<table>')/Keys" \--body '<entity-key-json>' \- --solution '<solution-uniquename-from-memory-bank>'+ --solution '<solution-uniquename-from-memory-bank>' \+ --tenant-id '<tenantId-from-resolve-environment>'```Body skeleton:@@ -609,11 +977,12 @@ Body skeleton:}```-**Pre-flight each key before POST** so re-runs are idempotent:+**Pre-flight each key before POST** so re-runs are idempotent. A key can only pre-exist on a table that already existed at Step 4, so for a table created in this run, skip straight to the POST. Otherwise read `Keys` from that table's Step 4 snapshot. Query it directly only when the snapshot did not cover that table:```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions(LogicalName='<table>')?\$select=LogicalName&\$expand=Keys(\$select=SchemaName,KeyAttributes,EntityKeyIndexStatus)"+ "EntityDefinitions(LogicalName='<table>')?\$select=LogicalName&\$expand=Keys(\$select=SchemaName,KeyAttributes,EntityKeyIndexStatus)" \+ --tenant-id '<tenantId-from-resolve-environment>'```| Existing key state | Action |@@ -637,7 +1006,12 @@ Add alternate keys to `.datamodel-manifest.json` for the table:**Print before starting:**> "→ Generating TypeScript services for <N> tables via `npx power-apps add-data-source` (sequential). Print '✓ <table>Service.ts' after each."-For each table the app will use (regardless of reuse/extend/create), generate the TS layer from the app root. The CLI reads the environment ID from `power.config.json`; pass the environment URL resolved earlier in the skill:+When `<operation_manifest_mode> = valid`, set `SERVICE_REQUIRED_TABLES` from+`service.requiredTables[].logicalName`. Keep the manifest's resolved adapted+names and exclude only explicit deferred rows. Service generation remains+sequential outside BATCH-METADATA.++For each table in `SERVICE_REQUIRED_TABLES` (regardless of reuse/extend/create), generate the TS layer from the app root. Do not derive this list from Creation Order alone because reused tables are intentionally absent from creation tiers. The CLI reads the environment ID from `power.config.json`; pass the environment URL resolved earlier in the skill:```bashnpx power-apps add-data-source --api-id dataverse --org-url <envUrl> --resource-name <table-logical-name>@@ -645,8 +1019,19 @@ npx power-apps add-data-source --api-id dataverse --org-url <envUrl> --resource-Run **one at a time — sequentially**, not in parallel. The Power Apps CLI writes `src/generated/connectorSchemas.ts` and other generated files non-atomically; concurrent invocations corrupt them.+After generation, verify each required table appears in `power.config.json` `databaseReferences.default.cds.dataSources` and that a matching file exists in `src/generated/services/`. If any reused or custom table is missing, STOP before screen generation:++```text+BLOCKED: required Dataverse service missing for <logical-name>. Schema action=<reuse|extend|create>; app usage=<screens/hooks that require it>.+```+### Step 6b — Publish customizations+When `<operation_manifest_mode> = valid`, skip this step: the validated+manifest's final `publish` phase already ran and its pending checkpoint was+deleted, or the manifest proved there were zero metadata writes and no pending+publish retry.+**Print before starting:**> "→ Publishing customizations (PublishXml) so new tables/columns become queryable. ~5–20 seconds."@@ -655,7 +1040,8 @@ Only after **every** Step 5 metadata POST and **every** Step 6 `npx power-apps a```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> POST \"PublishXml" \- --body "{\"ParameterXml\":\"<importexportxml><entities><entity>cr123_table1</entity><entity>cr123_table2</entity></entities></importexportxml>\"}"+ --body "{\"ParameterXml\":\"<importexportxml><entities><entity>cr123_table1</entity><entity>cr123_table2</entity></entities></importexportxml>\"}" \+ --tenant-id '<tenantId-from-resolve-environment>'```Build the entity list from all tables that were **created or extended** in Steps 4–5. Skip reused-as-is tables — they don't need republishing.@@ -664,15 +1050,16 @@ If the publish call returns a non-2xx status, report the error and stop — do n### Step 6c — Verify tables exist-For each created or extended table, confirm it is queryable after publish:+Confirm every created or extended table is queryable after publish with **one** filtered query, not one request per table:```bashnode "${CLAUDE_SKILL_DIR}/../../scripts/dataverse-request.js" <envUrl> GET \- "EntityDefinitions(LogicalName='<table>')?\\$select=LogicalName,DisplayName"+ "EntityDefinitions?\$select=LogicalName,DisplayName&\$filter=LogicalName eq '<table1>' or LogicalName eq '<table2>'" \+ --tenant-id '<tenantId-from-resolve-environment>'```-- **200** → confirmed.-- **404** → table missing after publish — report and stop.+- **Every expected name present in `value[]`** → confirmed.+- **Any expected name missing** → that table did not survive publish — report which ones and stop.### Step 6d — Write `.datamodel-manifest.json`@@ -808,6 +1195,9 @@ Environment : <envUrl>Tables reused : <list>Tables extended: <list (columns added)>Tables created : <list (in tier order)>+Adapted : <renamed table/column → new name, and why. Omit the line if none.>+Deferred : <items left out of this run and why, e.g. "cr123_note (target not customizable)". Omit the line if none.>+Operation manifest: <validated path, operation count, or "standalone fallback">Generated services:src/generated/services/<Table>Service.ts × N@@ -852,9 +1242,13 @@ After printing the summary, **offer one-click sample-data seeding** — but only- Result data lives at `result.data`, not `result` itself.- Don't edit files under `src/generated/` — they are regenerated on every `npx power-apps add-data-source`.- Picklist (Choice) fields, virtual fields, lookups, and file/image columns each have non-obvious gotchas. Keep `references/dataverse-reference.md` aligned with this skill.+- A valid operation manifest removes repeated agent reconciliation; it does not+ change Dataverse's serialized metadata-lock latency. Real matched A/B runs+ remain required before claiming an end-to-end timing range.- **When a Dataverse Web API behavior is uncertain (lookup write syntax, `$expand` nav property names, choice column shape, batch semantics, error format), query the `microsoft-learn` MCP server before guessing.** See [shared/shared-instructions.md → Microsoft Learn MCP](../../shared/shared-instructions.md#microsoft-learn-mcp-authoritative-microsoft-docs). Guessed Dataverse syntax silently 400s.## Reference- [`scripts/dataverse-request.js`](../../scripts/dataverse-request.js) — bundled in this plugin+- [`scripts/build-dataverse-operation-manifest.js`](../../scripts/build-dataverse-operation-manifest.js) — deterministic contract/snapshot reconciliation, binding, validation, and ordered BATCH-METADATA phase generation- [shared/references/offline-profile-reconciliation.md](../../shared/references/offline-profile-reconciliation.md) — Step 8.5 offline delta check + reconciliation flowdiff --git a/plugins/mobile-apps/skills/add-dataverse/references/dataverse-reference.md b/plugins/mobile-apps/skills/add-dataverse/references/dataverse-reference.mdindex ec00ff501..e85f26674 100644--- a/plugins/mobile-apps/skills/add-dataverse/references/dataverse-reference.md+++ b/plugins/mobile-apps/skills/add-dataverse/references/dataverse-reference.md@@ -2,6 +2,62 @@Critical patterns for working with Dataverse in Power Apps code apps. **Read this before writing any Dataverse code.**+## Approved operation manifests++Fast-v2 create flows use+`scripts/build-dataverse-operation-manifest.js` to reconcile the normalized+schema contract against a fresh bounded execution reconciliation performed in+Step 8. The foreground planning snapshot is evidence only and never authorizes+writes. The manifest is bound to the environment, tenant when available,+publisher, solution, plan hash, structured-schema hash, reconciliation+hash/timestamp, approved-contract hash, gate-owned approval-receipt hash, and+manifest version. The planner/orchestrator initializes+`.tmp/mobile-plan-status.json` when data-model approval is accepted and+advances it only as the existing later gates approve the final plan and+screen/service dependencies. Step 8 can only consume and verify this receipt;+the manifest tool exposes no receipt-creation/restamping mode. Any changed plan+or contract must return through the affected existing approval gate before the+orchestrator refreshes the receipt. Validate it with+`--require-executable` immediately before writes. Validation deterministically+rebuilds the expected manifest and compares all decisions, services, aliases,+phases, API paths, and bodies; a recomputed integrity hash cannot legitimize+tampering. Step 8 verifies both the fully approved plan content hash and+approved contract content hash before recording their binding in the+normalized schema artifact; no free-form Markdown semantic parser is used.+This assumes the existing non-adversarial local-filesystem workflow trust+model: hashes detect stale, accidental, or out-of-workflow replacement, but+are not signatures against a malicious local process able to rewrite every+artifact.++Its phases are fixed and sequential: table creates with ordinary columns+inline → extensions → relationships/lookups → alternate keys → publish.+Execution uses `BATCH-METADATA`, which is one-process sequential HTTP, never+OData `$batch`. Service generation remains separate and sequential. Any stale,+mismatched, incomplete, or `unverified` supplied manifest is non-executable+and fails closed. Only an absent fast-path handoff uses standalone+reconciliation. A non-executable candidate permits no writes. Approved+`Reuse`, `Adapt`, and `Defer` decisions come only from the structured schema;+the script verifies them mechanically and never parses free-form Markdown into+operations. Calculated/rollup/formula creation remains unsupported.+Lookup/1:N and M:N creation also requires fresh managed-property evidence for+the relevant endpoint relationship capabilities; missing evidence is not+treated as permission to write.+File and Image attributes are canonicalized from Dataverse's base+`AttributeType=Virtual` plus `AttributeTypeName=FileType|ImageType` before+compatibility checks. Their typed size/dimension evidence must still match;+another virtual type remains incompatible.++Before schema writes, persist the manifest's bound+`.tmp/dataverse-publish-pending.json`. Keep it on any failure and delete it+only after `PublishXml` succeeds. A rerun may therefore contain zero schema+creates but still execute one required publish retry; after successful publish+and checkpoint deletion, a fully applied rerun emits zero metadata POSTs.+`BATCH-METADATA` also journals `inFlight` and completed operation fingerprints+atomically. An uncertain resume requires a new bounded reconciliation and a+fully regenerated manifest before the runner will continue. All request paths+share the awaited `Retry-After` parser for both numeric seconds and HTTP-date+values, with a bounded fallback for malformed or missing headers.+## Choice/Picklist Fields - CRITICALChoice fields (`PicklistType`) store **integer values**, not string labels. The schema defines both:@@ -239,10 +295,14 @@ The lookup POST will 404 unless **both** endpoint tables already exist. Ensure:Lookup properties (`_fieldname_value`) are **read-only**. To set a relationship, use the **single-valued navigation property** with `@odata.bind`:```typescript-// CORRECT - Use @odata.bind for lookup fields-const newRecord: any = {+// CORRECT for generated services: copy the exact key from the generated model.+type CreateFields = Pick<+ Parameters<typeof ExampleService.create>[0],+ 'prefix_name' | '[email protected]' | 'prefix_status'+>;+const newRecord: CreateFields = {'prefix_name': 'My Record',- '[email protected]': `/accounts(${accountGuid})`,+ '[email protected]': `/accounts(${accountGuid})`,'prefix_status': 100000000};@@ -250,6 +310,12 @@ const newRecord: any = {{ '_prefix_parentaccountid_value': accountGuid } // May fail on create```+Raw Dataverse Web API examples often use a case-sensitive navigation-property schema name. Generated Power Apps services instead expose their accepted write key in `src/generated/models/<Entity>Model.ts`. For generated services, that model declaration is authoritative; never convert it to PascalCase or hide an unverified key inside `Record<string, unknown>`.++For filtering across lookups, avoid `lookupNavigation/relatedColumn eq ...` in generated mobile-service options. Resolve the related row through its generated service, then open the source generated model and copy the exact declared read lookup property corresponding to the planned lookup logical column (for example `_new_systemuserid_value` for `new_systemuserid`). Never substitute generic placeholders such as `_lookup_value` or `_systemuserlookup_value` into generated code.++Dynamic route IDs used in Dataverse calls must be normalized with the shared `normalizeDataverseGuid` helper from `@/utils`. Do not generate an inline RFC UUID regex: Dataverse sequential GUIDs may not contain RFC version bits even though their hexadecimal `8-4-4-4-12` structure is valid.+The `@odata.bind` value must be an entity set path with the GUID: `/<entitysetname>(<guid>)`## Alternate Keys (Metadata API) - CRITICALdiff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.mdindex 6e40fda1b..c72b8fb5c 100644--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md@@ -158,8 +158,13 @@ If `resolve-environment.js` cannot get tokens, run `az login --tenant <env-tenanDetect the publisher prefix for the env's Default solution so the planner uses the correct prefix rather than assuming `cr_`.+**Deferred execution:** do not run the query at this point. Step 2b.4 first+classifies the run as `required` or `connector-only`; only `required` runs+execute the block below. Connector-only runs set+`$DETECTED_PUBLISHER_PREFIX = ""` and make no Dataverse prefix query.+```bash-node "${CLAUDE_SKILL_DIR}/../../scripts/detect-publisher-prefix.js" "$ACTIVE_ENV_URL"+node "${CLAUDE_SKILL_DIR}/../../scripts/detect-publisher-prefix.js" "$ACTIVE_ENV_URL" --tenant-id "$ACTIVE_TENANT_ID"```Output is one line of JSON, e.g.:@@ -305,6 +310,28 @@ Do not ask for confirmation here — the user agreed to this when their prompt s**Auto-proceed after `yes` (or after auto-plan transparency log).** Fall through directly to Step 2c (plan preview). Do NOT add a separate "Proceed to planning?" prompt — the brief confirmation IS the planning go-ahead. The only abort gate after this is Step 2c's `proceed/edit/abort` block, which is intentionally distinct because it shows the rough cost estimate.+Classify Dataverse planning before Step 2c and stash+`<dataverse_planning_mode>`:++- `connector-only` only when every record source and write target is an+ explicit non-Dataverse connector/system of record, and the app needs no+ app-owned persistent rows, Dataverse offline data, retained File/Image+ artifact, existing Dataverse table, or Dataverse-backed native capability.+- `required` for every other case, including ambiguity. Do not infer+ connector-only merely because the brief names a connector.++Also stash `<exact_target_facts_required> = yes` when planning depends on any+existing/standard/managed table, reuse or extension decision, proposed-name+collision decision, relationship target, computed column, or target+customizability fact. Otherwise set it to `no`. This flag controls only safe+planning degradation; it never relaxes `/add-dataverse` reconciliation.++Now execute the deferred Step 1.7 publisher-prefix detection only when+`<dataverse_planning_mode> = required`. For `connector-only`, set+`$DETECTED_PUBLISHER_PREFIX = ""`, print+`↷ Publisher-prefix discovery skipped — connector-only planning.`, and do not+call `detect-publisher-prefix.js`.+**Design decisions are deferred to Step 6.75** — `/design-system` (ships with this plugin) handles brand inputs, the style picker, and visual companion preference in one flow after the project is scaffolded. Do NOT ask design questions here.Set tentative defaults (used by Step 3b before `/design-system` runs):@@ -327,7 +354,7 @@ Set tentative defaults (used by Step 3b before `/design-system` runs):| Tables | Distinct nouns in confirmed brief | `count(unique_nouns) × [0.7, 1.3]` rounded | low — architect may merge or split || Connectors | Step 2b inferred connector list | `len(inferred)` (already exact) | high || Screens | Confirmed features in brief | `count(features) × [2, 3]` | low — depends on navigation choice |-| Planning min | Tables + screens | `tables × 0.3 + screens × 0.4 + 2` | low |+| Planning min | Tables + screens | lower bound `max(10, tables × 0.3 + screens × 0.4 + 2)`; upper bound `max(15, computed upper)` | low — protects the quality-first Gate 1 budget || Scaffold min | Fixed | `1-2` (template preparation + npm install already happened before skill invocation) | high || Build min | Screens, parallel cap of 5 | `ceil(screens / 5) × 0.6` | medium || Extra prompts | `<industry_confidence>` + `<design_vibe_opt_in>` | `+1 if low-confidence industry; +1 if vibe-opt-in == yes` | high |@@ -345,7 +372,7 @@ Scope (proxy estimates — actual numbers come from architects):Approval gates 4 ← fixed (data model, native, connectors, screen plan)Time (rough — agent time only, excludes your approval latency at gates):- Planning ~<low>-<high> min ← architects + your gate approvals add to this+ Planning ~<low>-<high> min ← includes the quality-first 10–15 min data-model target; approvals add latencyScaffolding ~1-2 min ← validates prepared template + runs power-apps initScreen build ~<low>-<high> min ← parallel, capped at 5 concurrent@@ -377,13 +404,19 @@ Proceed, edit brief, or abort? [proceed/edit/abort]- Forced calibration: every run produces the `<estimate, actual>` data we need for v0.x model routing decisions. Skipping drops calibration data.**Set expectations before handing off to the planner:**-> "Brief locked in. Planning surfaces 4 approval prompts (data model → native capabilities → connectors → screens). Total time is 5–12 minutes:-> • Gate 1 (data model) — ~60–90s+> "Brief locked in. Planning surfaces 4 approval prompts (data model → native capabilities → connectors → screens). Data-model readiness is quality-first, with a 10–15 minute target:+> • Gate 1 (data model) — budget 10–15 min for verified reuse/extend/create decisions, ER columns, relationships, tiers, and risks> • Gate 2 (native capabilities) — ~10s (quick)> • Gate 3 (connectors) — ~30–60s> • Gate 4 (screens + design) — **3–8 minutes** (this is the heavy one: design vibe picker if opted in, then per-screen specs and HTML preview generation)>-> Between gates the spinner will sit quiet — sub-agents can't stream their progress to this view. If a gate hasn't surfaced after 12 minutes, something is stuck and you should interrupt."+> For Dataverse-required apps, factual foreground milestones will show+> environment, inventory, candidate, detail, and timing counts within 30+> seconds. Connector-only apps skip those metadata milestones. While the+> architect runs, new milestone IDs from+> `.tmp/data-model-planning-status.json` are rendered without inventing+> percentages. If Gate 1 has not surfaced after 15 minutes, inspect the last+> applicable milestone before interrupting."### Step 2d — Template-only mode@@ -391,12 +424,126 @@ No background scaffold pipeline is used. The template is already present in `<wo### Step 3 — Plan (planner agent + 4 approval gates)-First, create the empty working directory so the planner has a place to write:+First, create the working and planning-artifact directories:```bash-mkdir -p <working_dir>+mkdir -p <working_dir> <working_dir>/.tmp```+### Step 3.0 — Foreground Dataverse planning snapshot and evidence++Planning stays read-only. Branch on `<dataverse_planning_mode>`:++- `connector-only` — skip every command in this section. Set `SNAPSHOT_PATH`+ and `EVIDENCE_PATH` to empty/not supplied, print+ `↷ Foreground planning snapshot skipped — the confirmed brief is connector-only.`, and+ continue to planner dispatch. Connector-only planning does not perform+ Dataverse metadata reads; the skill's existing global prerequisites remain+ unchanged.+- `required` — resolve the already selected environment again in the+ foreground and create one normalized foreground planning snapshot as below. Do not make the+ nested planner or architect rediscover the tenant.++```bash+PLANNING_ENV_JSON=$(node "${CLAUDE_SKILL_DIR}/../../scripts/resolve-environment.js" "$ACTIVE_ENV_ID")+ACTIVE_ENV_URL=$(node -e "const j=JSON.parse(process.argv[1]); console.log(j.environmentUrl || '')" "$PLANNING_ENV_JSON")+ACTIVE_TENANT_ID=$(node -e "const j=JSON.parse(process.argv[1]); console.log(j.tenantId || '')" "$PLANNING_ENV_JSON")+test -n "$ACTIVE_ENV_URL" -a -n "$ACTIVE_TENANT_ID" || {+ echo "✗ Foreground planning snapshot requires a resolved Dataverse URL and tenant."; exit 2;+}+echo "✓ Planning environment resolved: $ACTIVE_ENV_URL (tenant $ACTIVE_TENANT_ID)"+```++Build `<DATAVERSE_CONCEPTS>` from **every domain noun and workflow family** in+the approved brief, not a sample. Preserve multiword/header-child families such+as `medical assessments`, `care activities`, `release events`, `custody+transfers`, `test results`, and `evidence attachments`. Add known standard or+required-existing logical names to `<EXPLICIT_TABLES>`. Build+`<PROPOSED_TABLES>` from the detected publisher prefix for every clearly+proposed custom table so collisions and missing names are explicit; leave a+name out rather than inventing it when the concept is not yet stable.++Detailed advisory discovery is quality-bounded:++- Keep the complete customizable-table inventory and ranking.+- Required exact-name tables are always detailed and do not consume advisory+ capacity.+- A concept credibly covered by an exact table does not receive speculative+ advisory alternatives.+- Every unresolved concept receives its best advisory candidate first.+- Only then allocate second/third candidates, with at most 3 per concept and a+ target ceiling of 40 unique advisory tables.+- When more than 40 unresolved concepts have distinct best candidates, exceed+ 40 only enough to preserve one candidate per concept. Quality coverage takes+ priority over the target ceiling.+- Inventory-only alternatives remain available for the existing one-time+ bounded exact-name expansion.++```bash+SNAPSHOT_PATH="<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json"+EVIDENCE_PATH="<working_dir>/.tmp/dataverse-planning-evidence.md"++node "${CLAUDE_SKILL_DIR}/../../scripts/create-dataverse-snapshot.js" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --output "$SNAPSHOT_PATH" \+ --concepts "<DATAVERSE_CONCEPTS>" \+ --tables "<EXPLICIT_TABLES>" \+ --proposed-tables "<PROPOSED_TABLES>"++node "${CLAUDE_SKILL_DIR}/../../scripts/render-dataverse-planning-evidence.js" \+ --snapshot "$SNAPSHOT_PATH" \+ --output "$EVIDENCE_PATH"++node -e '+ const s=require(process.argv[1]);+ const t=s.timings;+ const d=s.detailLoadSummary;+ console.log(`✓ Dataverse inventory: ${s.inventoryFacts.customizableTables} customizable + ${s.inventoryFacts.exactNameTables} bounded exact-name discoveries (${s.inventoryFacts.requiredExactNameTables} required, ${s.inventoryFacts.proposedCollisionTables} proposed collisions) (${t.inventoryRetrievalMs} ms)`);+ console.log(`✓ Candidate selection: ${s.candidateRanking.length} concepts → ${d.attemptedCandidates} detailed candidates (${d.requiredCandidates || 0} required, ${d.advisoryCandidates || 0} advisory, ${d.exactCoveredConcepts || 0} exact-covered concepts; ${t.candidateSelectionMs} ms)`);+ console.log(`✓ Detail loading: ${d.attemptedCandidates} attempted, ${d.loadedCandidates} loaded, ${d.failedCandidates} failed; ${s.tables.reduce((n,x)=>n+x.facts.columnCount,0)} columns, ${s.tables.reduce((n,x)=>n+x.facts.relationshipCount,0)} relationships, ${s.tables.reduce((n,x)=>n+x.facts.keyCount,0)} keys (${t.detailLoadingMs} ms)`);+ console.log(`✓ Exact names: requested [${s.exactNameResolution.requestedTables.join(", ")}], loaded [${s.exactNameResolution.loadedTables.join(", ")}], unavailable [${s.exactNameResolution.unavailableTables.join(", ")}]`);+ console.log(`✓ Proposed names: ${s.proposedNameChecks.collisions.length} collisions, ${s.proposedNameChecks.missing.length} missing; foreground planning snapshot total ${t.totalDurationMs} ms`);+' "$SNAPSHOT_PATH"+echo "✓ Planning evidence: $EVIDENCE_PATH"+```++If environment resolution, token acquisition, inventory, required exact-name+metadata/detail loading, parsing, or evidence rendering fails, surface the+exact failure and **do not** treat an unreadable response as an empty inventory:++- For every `required` Dataverse plan, stop planning with a visible+ `BLOCKED: Dataverse planning metadata unavailable for exact target decisions`+ result. Do not dispatch a snapshot-only architect and do not proceed toward+ Dataverse mutation. The mutation workflow does not accept an unresolved+ `Unverified` plan as an executable contract.+- A concept-selected candidate is advisory unless it is also named by+ `--tables`. If advisory detail metadata is unsupported, abstract, or+ inaccessible, keep the snapshot, record it in `detailLoadFailures`, list it+ in the evidence appendix, and continue. Explicit `--tables` and bounded+ exact-name expansions remain required and fail closed.+- `--proposed-tables` performs collision checks only. Missing proposed names+ are not required-table failures and must never be selected for detail loading+ solely because they were proposed.++The snapshot script emits factual `DATAVERSE_SNAPSHOT_PROGRESS` lines after+inventory, candidate selection, and detail loading. Print them immediately;+never replace them with estimates or percentages. Once the architect starts,+watch `<working_dir>/.tmp/data-model-planning-status.json` and print each new+milestone ID once with its counts and elapsed time. The first environment or+snapshot milestone must be visible within 30 seconds. The foreground+orchestrator owns this rendering; the architect only owns the status artifact.++For `required`, pass `SNAPSHOT_PATH` and `EVIDENCE_PATH` verbatim to the planner+prompt and every direct `data-model-architect` fallback/revision. A supplied+matching snapshot activates the architect's `snapshot-only` path: no Bash+discovery and no live Dataverse calls inside the agent. For `connector-only`,+pass the mode explicitly and state that both paths are not supplied; never+provide placeholder file paths.++Benchmark method and acceptance criteria:+[`references/dataverse-planning-benchmark.md`](references/dataverse-planning-benchmark.md).+**Hard rule — planner writes are restricted during Step 3.** The planner (and any sub-agents it spawns) is permitted to write to **only**:- `<working_dir>/native-app-plan.md`@@ -412,7 +559,8 @@ If the planner needs to record a `DONE_WITH_CONCERNS` from a sub-agent (data-mod**Planner preflight (silent).** Before the full Task spawn, do a no-op `Task` probe for `mobile-app:native-app-planner` (same pattern as Step 11.0). If the probe fails with `Agent type … not found`, `tool unavailable`, or the host clearly cannot route nested agents, fall through to **inline-gate mode** (described below) without prompting. The orchestrator has the full tool surface itself — it can run the gates directly. Do not retry, do not ask the user.**Announce the handoff before the Task call** (so the user isn't staring at a blank screen while the planner spins up):-> "→ Spawning planner agent. First prompt (data model) appears in ~60–90 seconds while the data-model architect analyzes your requirements. Later gates take longer — see the timing breakdown above."+- `required`: > "→ Spawning planner agent from the verified foreground planning snapshot. Gate 1/data-model readiness is quality-first with a 10–15 minute target. I will print each factual `data-model-planning-status.json` milestone and elapsed count as it lands."+- `connector-only`: > "→ Spawning planner agent in connector-only mode; a foreground planning snapshot and data-model mutation are not required."Then spawn the `mobile-app:native-app-planner` agent via `Task` (the plugin name `mobile-app:` prefix is required — without it `Task` returns `Agent type not found`):@@ -432,12 +580,23 @@ Prompt:Wizard answers: <Step 2 answers>Working directory: <absolute path of <working_dir>>Plugin root: ${CLAUDE_SKILL_DIR}/../../+ Dataverse planning mode: <required | connector-only>+ Dataverse planning failure reason: none+ Normalized Dataverse foreground planning snapshot: <absolute SNAPSHOT_PATH verbatim for required; otherwise NOT SUPPLIED>+ Dataverse planning evidence: <absolute EVIDENCE_PATH verbatim for required; otherwise NOT SUPPLIED>+ Structured schema contract: <absolute+ `<working_dir>/.tmp/dataverse-schema-contract.json` for required; otherwise+ NOT SUPPLIED>Publisher prefix (detected from env): <DETECTED_PUBLISHER_PREFIX from Step 1.7, e.g. "cr8142a" — use literally as `<prefix>_<entity>` in all logical names. If empty/NOT DETECTED, fall back to `cr` placeholder and surface a `DONE_WITH_CONCERNS` note that Dataverse will normalize at create time.>Follow native-app-planner.md. Run all 4 approval gates. On terminal return, emit one of `DONE` / `DONE_WITH_CONCERNS:` / `NEEDS_CONTEXT:` / `BLOCKED:` as the literal first line per AGENTS.md rule #10.```The planner runs gates internally for data model → native capabilities → connectors → screen plan, and writes `<working_dir>/native-app-plan.md`. Wait for it to return before continuing — do not proceed on a partially-approved plan.+On a successful `required` return, require both+`.tmp/dataverse-schema-contract.json` and `.tmp/mobile-plan-status.json`+before continuing. If the receipt is missing, STOP as `BLOCKED`; this+orchestrator must not synthesize it after the planner has returned.#### 3.0a — Inline-gate fallback (planner unavailable OR returned `BLOCKED: tool surface missing`)@@ -454,8 +613,19 @@ Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:- Before `phase: graph`: `> "→ [Gate 4a] Spawning screen-planner phase=graph (~2 min for ${N} screens)…"`- Before `phase: specs`: `> "→ [Gate 4b] Spawning screen-planner phase=specs (~1 min/screen, ~${N} min for ${N} screens). Progress markers will appear inline."`+ **MUST forward the Dataverse planning mode in the direct architect prompt.**+ In `required`, also forward `SNAPSHOT_PATH` and `EVIDENCE_PATH` verbatim and+ do not resolve the environment or run Dataverse discovery again. In+ `connector-only`, state that both paths are not supplied; never invent+ placeholder artifacts.+**MUST forward `$DETECTED_PUBLISHER_PREFIX` from Step 1.7 in the architect prompt** — same line as the planner prompt at Step 3 line 1034: *"Publisher prefix (detected from env): `<DETECTED_PUBLISHER_PREFIX>` — use literally as `<prefix>_<entity>` in all logical names. If empty/NOT DETECTED, fall back to `cr` placeholder and surface a `DONE_WITH_CONCERNS` note that Dataverse will normalize at create time."* Without this, the architect defaults to `cr_` and the whole plan needs a post-hoc sweep when the real prefix is something else (e.g. `cr3e9`).+ In `required`, also require the direct architect to write and normalize+ `<working_dir>/.tmp/dataverse-schema-contract.json` per its agent contract.+ A draft Markdown section without that sidecar is not an executable Gate 1+ result.+**Why this works even though the planner just returned BLOCKED for tool surface:** the orchestrator (this skill, running in the user's slash-command session) always has the full tool surface — Task, EnterPlanMode, ExitPlanMode, AskUserQuestion, Read, Write, Bash. What's missing is the surface inside *nested* agent contexts (the `native-app-planner` agent runs in a sandbox without EnterPlanMode/AskUserQuestion, which is why its Step 0 preflight returned BLOCKED). The leaf agents `data-model-architect` and `screen-planner` only need Read/Write/Bash to draft markdown — they don't need EnterPlanMode/AskUserQuestion themselves. Spawn them; the orchestrator owns the gates.3. **Run the gates yourself** — use `EnterPlanMode` four times (data model → native caps + connectors merged → screen graph 4a → screen specs 4b). Same gate prompts as the planner agent would use. Gate 4 is a markdown screen-graph review only — design picking happens unconditionally at Step 6.75 via `/design-system` (no separate style-picker handoff at Gate 4 even in inline mode).@@ -467,7 +637,18 @@ Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:- Discovery failure notes (e.g. `az login` on the wrong tenant, 401 from `dataverse-request.js`, all entities classified Create) go to `<working_dir>/memory-bank.md` under `## Discovery Notes`, NOT into the plan. Keep at most a single one-line breadcrumb in `## Data Model` like `> Discovery skipped — see memory-bank.md.` if relevant.- Sample data notes, immutability plug-in notes, file-column setup notes, dispatch-block server rules go under a single `### Notes` subsection in `## Data Model`. Cap each at 2 sentences; link to `post-deployment-tasks.md` for longer write-ups instead of inlining.-If the orchestrator's OWN `Task` tool is unavailable (rare — would mean even leaf agents can't be spawned), fall further to fully-inline mode: orchestrator drafts the data model from a Dataverse OData probe (`resolve-environment.js` + table list filter on the brief's domain keywords), drafts native caps + connectors heuristically, drafts the screen graph + specs against `shared/references/screen-templates.md`, and runs the four gates against the user. This is the last-resort path — functional but slower because the orchestrator does work the architects normally parallelize.+5. **Record the same structured approval receipt as the planner path.** At+ data-model acceptance, initialize+ `<working_dir>/.tmp/mobile-plan-status.json` with the exact normalized+ contract content/hash. After each later gate is accepted, update only that+ gate's approval record and the current plan hash; after Gate 4b, record the+ final structured service dependencies and integrity hash. Follow+ `agents/native-app-planner.md` Step 6 exactly. Never call the operation+ manifest builder to create or restamp this receipt. A changed approved+ section invalidates its record until the existing inline gate approves it+ again.++If the orchestrator's OWN `Task` tool is unavailable (rare — would mean even leaf agents can't be spawned), fall further to fully-inline mode. In `required`, draft the data model from `SNAPSHOT_PATH` plus `EVIDENCE_PATH` with no live OData probe and write/normalize the same structured schema contract required by `agents/data-model-architect.md`. In `connector-only`, write an explicit zero-table/no-Dataverse `## Data Model` section and no contract. Then draft native caps + connectors heuristically, draft the screen graph + specs against `shared/references/screen-templates.md`, and run the four gates against the user. This is the last-resort path — functional but slower because the orchestrator does work the architects normally parallelize.**Hard rule:** never silently skip a gate just because the planner couldn't run. The user MUST approve each section through `EnterPlanMode` before any mutation step (Step 8 onwards) executes.@@ -475,6 +656,70 @@ If the orchestrator's OWN `Task` tool is unavailable (rare — would mean even lUse the plugin-wide protocol in [`AGENTS.md`](${CLAUDE_SKILL_DIR}/../../AGENTS.md) rule #10 for every `Task` return in this skill: planner, parallel screen-builders, and future agent spawns. Parse the literal first line and branch: `DONE` continues; `DONE_WITH_CONCERNS:` surfaces + records in `memory-bank.md`; `NEEDS_CONTEXT:` re-dispatches with missing context, capped at 2 retries; `BLOCKED:` stops and records under `## Blocks`. Unknown first lines are malformed and must be treated as `BLOCKED`.+**Data-model exact-name expansion:** when the planner or direct architect+returns exactly+`NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>`, sort and+de-duplicate those names. This signal is valid only in `required` mode with a+validated base snapshot, whether it came from the planner or the direct+architect fallback; receiving it in `connector-only` mode is `BLOCKED`.+Perform one bounded foreground expansion. Reuse the existing snapshot+inventory, issue at most one exact-name metadata query for requested names+absent from it, and do not run another broad inventory query:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/create-dataverse-snapshot.js" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --base-snapshot "$SNAPSHOT_PATH" \+ --output "$SNAPSHOT_PATH" \+ --tables "<exact comma-separated logical names>"++node "${CLAUDE_SKILL_DIR}/../../scripts/render-dataverse-planning-evidence.js" \+ --snapshot "$SNAPSHOT_PATH" \+ --output "$EVIDENCE_PATH"++node -e '+ const s=require(process.argv[1]);+ const x=s.expansion;+ const d=s.detailLoadSummary;+ console.log(`✓ Expansion requested: [${x.requestedTables.join(", ")}]`);+ console.log(`✓ Expansion loaded: [${x.loadedTables.join(", ")}]`);+ console.log(`✓ Expansion unavailable: [${x.unavailableTables.join(", ")}]`);+ console.log(`✓ Expansion details: ${d.attemptedCandidates} attempted, ${d.loadedCandidates} loaded, ${d.failedCandidates} failed`);+ console.log(`✓ Expansion timing: metadata ${s.timings.inventoryRetrievalMs} ms, selection ${s.timings.candidateSelectionMs} ms, details ${s.timings.detailLoadingMs} ms, total ${s.timings.totalDurationMs} ms`);+' "$SNAPSHOT_PATH"+```++Print the expansion's requested/loaded/unavailable names and timings+immediately, then re-dispatch the same planner or architect once with the same+snapshot/evidence paths. A second detailed-metadata signal is `BLOCKED`; do not+loop, broaden concepts, or defer exact validation to mutation.++**Data-model proposed-name expansion:** when the planner or direct architect+returns exactly+`NEEDS_CONTEXT: proposed-dataverse-names:<logical names>`, sort and de-duplicate+those names. This signal is valid only in `required` mode with a validated+snapshot. Perform one collision-only foreground expansion:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/create-dataverse-snapshot.js" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --base-snapshot "$SNAPSHOT_PATH" \+ --output "$SNAPSHOT_PATH" \+ --proposed-tables "<exact comma-separated logical names>"++node "${CLAUDE_SKILL_DIR}/../../scripts/render-dataverse-planning-evidence.js" \+ --snapshot "$SNAPSHOT_PATH" \+ --output "$EVIDENCE_PATH"+```++This expansion checks collisions only; it does not treat absent proposed names+as required existing tables or load their details. Re-dispatch once. A second+proposed-name signal is `BLOCKED`. If a collision is found and the architect+needs compatibility facts, it may then use the separate one-time+`detailed-dataverse-metadata` expansion for that existing table.+Planner-only early-return signals are handled before the status switch: `INDUSTRY_CONFIRM_REQUESTED:` routes to Step 3.0a; `DESIGN_VIBE_REQUESTED:` routes to Step 3a. After the handoff, re-spawn the planner and process its new first line through this switch.#### Step 3.0a — Industry confirmation handoff (orchestrator-owned)@@ -596,6 +841,22 @@ fiIf mismatches are reported, sweep `native-app-plan.md` (and any auxiliary files like `.datamodel-manifest.json` if already written) replacing the wrong prefix with `${DETECTED_PUBLISHER_PREFIX}_` before Step 4. Do NOT proceed to Step 5 with a wrong-prefix plan — the sweep cost grows ~500 occurrences once services are generated.+For `required`, apply the same prefix correction to+`.tmp/dataverse-schema-contract.json`, then normalize it. Before Step 4, require+both approved artifacts:++```bash+test -f "$WORKING_DIR/native-app-plan.md"+test -f "$WORKING_DIR/.tmp/dataverse-schema-contract.json"+node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --normalize-contract "$WORKING_DIR/.tmp/dataverse-schema-contract.json" \+ --output "$WORKING_DIR/.tmp/dataverse-schema-contract.json"+```++Do not fall back to parsing the Markdown ER diagram when the sidecar is missing+or malformed; route through the existing planner/direct-architect revision+path.+### Step 4 — Auth & environment selection```bash@@ -1148,12 +1409,109 @@ Do NOT touch `src/playerConfig.ts` — auth identifiers live in `auth.config.jso### Step 8 — Apply data model+If `<dataverse_planning_mode> = connector-only`, verify the approved+`## Data Model` says zero Dataverse tables and no `.datamodel-manifest.json`+exists, print `↷ Step 8 skipped — connector-only app has no Dataverse data model.`,+skip Step 8.5 as well, and continue to Step 9. A non-empty Dataverse plan in+this mode is a planning mismatch and must be corrected before continuing.+**Print before starting:**-> "→ [Step 8/13] Invoking /add-dataverse to create/extend tables and generate TypeScript services. This is the longest single phase — expect 2–5 minutes for a typical 4–6 table model."+> "→ [Step 8/13] Preparing the approved Dataverse operation manifest, then invoking /add-dataverse for sequential metadata writes and service generation. Dataverse write time varies by environment; local manifest preparation is deterministic, not a wall-clock promise."**Environment pre-check (before invoking /add-dataverse):** Verify that `.resolved-environment.json` / `power.config.json` match the environment captured in Step 1. If they differ, warn the user immediately — creating tables in the wrong environment is the #1 silent breakage in this step. `/add-dataverse` Step 3a does its own check, but catching it here saves a failed attempt.-Read the `## Data Model` section from `native-app-plan.md`. Invoke `/add-dataverse` with the working directory and a flag to skip its own planning (since the plan section is already approved):+For the fast-v2 `required` path, keep the foreground planning snapshot as+planning evidence only. It never authorizes a write. Without changing any+approval gate, Step 8 must perform one fresh bounded reconciliation for every+exact table in the approved structured schema; each existing table reloads+ordinary typed columns, lookups, M:N/1:N relationships, and alternate keys.+Create/adapt table reruns also reload and compare creation-significant table+behavior: ownership, activities, notes, offline availability, change tracking,+labels/schema identity, and primary-name identity.+The exact/proposed scope also includes every effective M:N intersect entity+name, and 1:N reuse requires complete matching `CascadeConfiguration`+evidence. An absent or colliding intersect name, or missing/mismatched cascade+evidence, is non-executable.+Step 8 also binds the structured artifact to the current fully approved plan+content hash and the gate-owned approval receipt's exact contract hash and+service dependencies. Step 8 cannot create or refresh this receipt. Use+resolved context and these structured artifacts, never values inferred from+free-form Markdown:++```bash+SCHEMA_CONTRACT="<working_dir>/.tmp/dataverse-schema-contract.json"+APPROVAL_RECEIPT="<working_dir>/.tmp/mobile-plan-status.json"+FOREGROUND_PLANNING_SNAPSHOT="<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json"+RECONCILIATION_SCOPE="<working_dir>/.tmp/dataverse-reconciliation-scope.json"+EXECUTION_RECONCILIATION="<working_dir>/.tmp/dataverse-execution-reconciliation.json"+OPERATION_MANIFEST="<working_dir>/.tmp/dataverse-operation-manifest.json"+PUBLISH_CHECKPOINT="<working_dir>/.tmp/dataverse-publish-pending.json"+ACTIVE_SOLUTION_UNIQUE_NAME="Default"++test -f "$SCHEMA_CONTRACT" -a -f "$APPROVAL_RECEIPT" \+ -a -f "$FOREGROUND_PLANNING_SNAPSHOT" \+ -a -f "<working_dir>/native-app-plan.md"++node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --bind-plan "$SCHEMA_CONTRACT" \+ --approval-receipt "$APPROVAL_RECEIPT" \+ --plan "<working_dir>/native-app-plan.md" \+ --output "$SCHEMA_CONTRACT"++node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --reconciliation-scope "$SCHEMA_CONTRACT" \+ --output "$RECONCILIATION_SCOPE"++EXACT_TABLES=$(node -e "console.log(require(process.argv[1]).exactTables.join(','))" "$RECONCILIATION_SCOPE")+PROPOSED_TABLES=$(node -e "console.log(require(process.argv[1]).proposedTables.join(','))" "$RECONCILIATION_SCOPE")++node "${CLAUDE_SKILL_DIR}/../../scripts/create-dataverse-snapshot.js" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --solution "$ACTIVE_SOLUTION_UNIQUE_NAME" \+ --tables "$EXACT_TABLES" \+ --proposed-tables "$PROPOSED_TABLES" \+ --reconcile-exact \+ --output "$EXECUTION_RECONCILIATION"++node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --contract "$SCHEMA_CONTRACT" \+ --approval-receipt "$APPROVAL_RECEIPT" \+ --reconciliation "$EXECUTION_RECONCILIATION" \+ --plan "<working_dir>/native-app-plan.md" \+ --output "$OPERATION_MANIFEST" \+ --environment-id "$ACTIVE_ENV_ID" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --publisher-prefix "$DETECTED_PUBLISHER_PREFIX" \+ --solution "$ACTIVE_SOLUTION_UNIQUE_NAME" \+ --publish-checkpoint "$PUBLISH_CHECKPOINT"+```++The manifest builder mechanically verifies the approved `Reuse`, `Extend`,+`Create`, `Adapt`, `Defer`, and `Unverified` decisions. It must not invent or+change architecture decisions. Any mismatch is a non-executable verification+conflict and returns to the orchestrator; do not add another opportunistic read+loop or fall back to agent reconciliation. No operation may execute until:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/build-dataverse-operation-manifest.js" \+ --validate "$OPERATION_MANIFEST" \+ --contract "$SCHEMA_CONTRACT" \+ --approval-receipt "$APPROVAL_RECEIPT" \+ --reconciliation "$EXECUTION_RECONCILIATION" \+ --plan "<working_dir>/native-app-plan.md" \+ --environment-id "$ACTIVE_ENV_ID" \+ --env-url "$ACTIVE_ENV_URL" \+ --tenant-id "$ACTIVE_TENANT_ID" \+ --publisher-prefix "$DETECTED_PUBLISHER_PREFIX" \+ --solution "$ACTIVE_SOLUTION_UNIQUE_NAME" \+ --publish-checkpoint "$PUBLISH_CHECKPOINT" \+ --require-executable+```++Invoke `/add-dataverse` with the working directory, approved plan, and exact+artifact paths:```Invoke skill: /add-dataverse@@ -1161,10 +1519,27 @@ Invoke skill: /add-dataverseArguments:--working-dir <working_dir>--plan-section <native-app-plan.md#data-model>+ --schema-contract <working_dir>/.tmp/dataverse-schema-contract.json+ --approval-receipt <working_dir>/.tmp/mobile-plan-status.json+ --execution-reconciliation <working_dir>/.tmp/dataverse-execution-reconciliation.json+ --operation-manifest <working_dir>/.tmp/dataverse-operation-manifest.json+ --publish-checkpoint <working_dir>/.tmp/dataverse-publish-pending.json--skip-planning (the planner already ran)```-`/add-dataverse` creates Tier 0 → N tables, applies extensions, runs `npx power-apps add-data-source --api-id dataverse --org-url <envUrl> --resource-name <name>` per table from the app root, type-checks, returns.+`/add-dataverse` validates the bindings and consumes valid phases immediately.+Any supplied artifact/binding failure returns to this orchestrator; it must+not silently enter standalone reconciliation. A non-executable manifest+authorizes no metadata writes.+The publish checkpoint is retained across schema/PublishXml failure and+deleted only after successful publish, so a rerun retries pending publication+even when schema writes are already idempotent.+It creates Tier 0 → N tables, applies extensions, runs+`npx power-apps add-data-source --api-id dataverse --org-url <envUrl>+--resource-name <name>` per service-required table from the app root,+type-checks, and returns. Real matched A/B runs are still required to quantify+the end-to-end time saved; do not present local manifest timing as a guaranteed+1–3 minute Dataverse result.After `/add-dataverse` returns, run the **Dataverse/generated-services gate**:@@ -1312,6 +1687,12 @@ Build two lists from the classification:**Sanity check before writing anything:** if any folder has children but no `index.tsx` row in the Screen Map, STOP and report: `BLOCKED: folder app/(app)/<folder>/ has children (<list>) but no index.tsx row in the Screen Map. The screen-planner must emit an index.tsx row for every folder.` This catches a planner mistake that would render the folder unreachable from the outer tab.+Normalize every Screen Map file to its Expo route (strip `.tsx`, collapse trailing `/index`, preserve dynamic segments). If two files normalize to the same route, STOP before writing layouts. In particular, reject `<parent>/[id].tsx` together with `<parent>/[id]/<child>.tsx`; move the detail contract to `<parent>/[id]/index.tsx`.++```text+BLOCKED: duplicate Expo route <route> from <file-a> and <file-b>. Use [id]/index.tsx when a dynamic detail route owns child screens.+```+#### Step 10b.2 — Write per-folder inner `_layout.tsx` files (if any folders exist)For each entry in the Inner stacks list, create the folder if missing and write `app/(app)/<folder>/_layout.tsx` with this template:@@ -1334,7 +1715,7 @@ Rules:- `headerShown: false` at the Stack level — each screen sets its own header inline via `<Stack.Screen options={{...}}>` at the top of its component (the Expo Router idiom).- `<Stack.Screen name="index" />` is required — without it, the folder root won't render.- `presentation: 'modal'` and `presentation: 'formSheet'` come from the Screen Map's Presentation column. Skip the `options` prop entirely for `default` presentation.-- `name` for `[id].tsx` is literally `[id]` (with brackets).+- `name` for `[id].tsx` is literally `[id]` (with brackets). When `[id]` owns child routes, create `<folder>/[id]/_layout.tsx` with `<Stack.Screen name="index" />` and child entries; do not register both `[id].tsx` and a `[id]/` folder.- Folder name in the function name is PascalCase (e.g. `InspectionsLayout`).**Why this must run BEFORE Step 11:** screen-builders write their files in parallel, multiple builders may target the same folder, and any of them creating `_layout.tsx` would race. The orchestrator owns these files.@@ -1796,6 +2177,14 @@ Common wave-gate repair classes to batch instead of fixing line-by-line:**After all waves return and the last wave gate is clean**, run one final `npx tsc --noEmit` before Step 12 to catch cross-screen issues that only appear when all screens exist. If it fails, use the same consolidated batch-repair flow.+Then run the canonical route-contract gate from the app root:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/check-routes.js"+```++This gate is required even when TypeScript passes. It detects duplicate normalized routes, `[id].tsx` plus `[id]/<child>.tsx` file/folder collisions, and sender/destination parameter drift. If it fails, repair the affected route files or re-spawn their screen builders with the consolidated findings, then rerun once. Do not continue to Step 11.4 or start Metro while route findings remain.+**Sticky tsc/build error policy (run-level).** The first time a `tsc` or `npm run build` failure surfaces in this run, ask the user once:> "tsc found <N> error(s) in <files>. Patch + continue, or stop and let me investigate?"diff --git a/plugins/mobile-apps/skills/create-mobile-app/references/dataverse-planning-benchmark.md b/plugins/mobile-apps/skills/create-mobile-app/references/dataverse-planning-benchmark.mdnew file mode 100644index 000000000..3b30f8bf7--- /dev/null+++ b/plugins/mobile-apps/skills/create-mobile-app/references/dataverse-planning-benchmark.md@@ -0,0 +1,31 @@+# Dataverse planning benchmark++Run the deterministic fixture evaluation with:++```bash+node plugins/mobile-apps/scripts/benchmark-dataverse-planning.js+```++It runs the real `createSnapshot` and `renderPlanningEvidence` implementations+against injected Dataverse responses for wildlife rehabilitation and laboratory+sample chain-of-custody. It reports selected candidates, actual fixture request+counts, relationship/computed extraction, proposed-name checks, evidence+output, and local processing time. It does not score model decisions or claim+agent timing improvements. Matched agent A/B runs are still required for model+decision and timing claims.++## Acceptance criteria++- Same required entity, column, and relationship decisions as the legacy path.+- No weaker reuse or extend decision; every selected existing table has detailed target evidence.+- No missing cross-entity projection or risk notes.+- First factual progress milestone appears within 30 seconds.+- Gate 2/data-model readiness targets 10–15 minutes, quality first.+- Any inventory-only required candidate triggers one bounded exact-name snapshot expansion.+- Every unresolved concept keeps at least its best detailed advisory candidate.+- Exact-covered concepts do not receive unnecessary advisory alternatives.+- Advisory detail loading uses at most 3 candidates per concept and targets 40+ unique advisory tables globally; it may exceed 40 only to preserve one+ candidate for each unresolved concept.+- Required exact-name tables are reported separately and never consume the+ advisory target.diff --git a/plugins/mobile-apps/skills/edit-app/SKILL.md b/plugins/mobile-apps/skills/edit-app/SKILL.mdindex 01ad1200f..dda4cc010 100644--- a/plugins/mobile-apps/skills/edit-app/SKILL.md+++ b/plugins/mobile-apps/skills/edit-app/SKILL.md@@ -447,6 +447,7 @@ Before spawning builders:Navigation/layout algorithm:- Read the approved `## Screens` Screen Map and Navigation Contracts.+- Normalize every target file to its Expo route before editing. Reject duplicate normalized routes, especially `<parent>/[id].tsx` together with `<parent>/[id]/<child>.tsx`; move the detail contract to `<parent>/[id]/index.tsx` before builders run.- For every new route, create the parent folder and inner `_layout.tsx` when the route is nested.- For modal/formSheet/detail routes, add the correct `<Stack.Screen name="..." options={{ presentation: 'modal' | 'formSheet' }} />` in the owning folder layout.- For tab/root changes, patch only the route list in `app/(app)/_layout.tsx`; preserve auth/provider logic and imports not related to route registration.diff --git a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md b/plugins/mobile-apps/skills/setup-datamodel/SKILL.mdindex 0c34bebae..86106df82 100644--- a/plugins/mobile-apps/skills/setup-datamodel/SKILL.md+++ b/plugins/mobile-apps/skills/setup-datamodel/SKILL.md@@ -140,7 +140,12 @@ Arguments:`/add-dataverse` creates tables in tier order, runs `npx power-apps add-data-source --api-id dataverse --org-url <envUrl> --resource-name <name>` per table from the app root, publishes customizations, writes `.datamodel-manifest.json`, and type-checks. Wait for it to return before Phase 6.-**Calculated columns from the screen plan** — if `## Data Model` in the plan includes a `### Cross-entity Reads (auto-derived from screen plan)` subsection (the `data-model-architect`'s Step 6a addendum, approved at the Gate 1 addendum during planning), `/add-dataverse` Step 5c creates each row as a calculated column on the parent table via `scripts/create-calculated-column.js`. No additional action needed in this skill — `/add-dataverse` handles it. If the subsection is absent, Step 5c is silently skipped. See [`shared/references/data-performance.md` § Cross-entity Reads](${PLUGIN_ROOT}/shared/references/data-performance.md#cross-entity-reads) for why this matters.+**Cross-entity reads from the screen plan** — the approved+`### Cross-entity Reads` subsection contains formatted lookups, bounded chained+fetches, or `external-projection-required` blockers. `/add-dataverse` never+synthesizes calculated/formula definitions through code. A user-supplied,+maker-created computed column is validated as an existing dependency during+reconciliation before it can be reused.Skip if Phase 2 chose Path C (no Dataverse).