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
feat(mobile-apps): make Dataverse planning deterministic (#507)
Shubham Agarwal3958f93054d5
diff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.mdindex 19b7bd947..4b02ff3b2 100644--- a/plugins/mobile-apps/agents/data-model-architect.md+++ b/plugins/mobile-apps/agents/data-model-architect.md@@ -4,6 +4,7 @@ description: Use when an orchestrator needs a Dataverse data model proposed (exiuser-invocable: falsecolor: cyanmodel: sonnet+tools:- Read- Write@@ -22,10 +23,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.+- **Normalized Dataverse foreground planning snapshot path (validation only)** —+ an absolute path to+ `<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json`. Do not read+ this large artifact into model context.+- **Compact architect evidence path (preferred)** — an absolute path to the+ hash-bound JSON sidecar rendered from that foreground planning snapshot.- **Dataverse planning mode** — `required`. Connector-only planning is owned by`native-app-planner` and must not dispatch this agent.- **Approved native capabilities** (create flow, when supplied) — the exact@@ -43,12 +46,14 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that in- **Reuse-first and target-grounded.** Use exact target metadata for everyproposed 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+ compact architect sidecar. Don't propose a `cr123_customer` table if a verifiedtarget `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.** This agent runs only for Dataverse-required planning. A- run with unreadable metadata is blocked by the foreground orchestrator before- dispatch.+ run without a trustworthy foreground snapshot returns to the orchestrator's+ bounded environment, authentication, inventory, or artifact recovery before+ dispatch. Individual table-detail failures inside a valid snapshot are not+ blockers; classify the affected table as `Defer`.- **Connectivity intent ownership.** Follow[`shared/references/connectivity-intent-ownership.md`](../shared/references/connectivity-intent-ownership.md)when deriving schema.@@ -56,7 +61,7 @@ You will be invoked by `native-app-planner` or `/edit-app` with a prompt that inapproved native capture and retention targets when selecting Image, File,location, or child evidence storage. Do not create a Dataverse duplicate of a connector-owned entity;model only app-owned data or explicit Dataverse projections approved at Gate 1.-- **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.+- **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, on the legacy live-discovery path only, `Unverified` (discovery could not run at all). A `detailLoadFailures` entry in a valid foreground snapshot is always `Defer`, never `Unverified`. 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.@@ -103,45 +108,64 @@ the explicit zero-table connector-only section.## Snapshot-only fast path-In `required` mode, both snapshot and planning-evidence paths must be supplied.-Validate before planning:+In `required` mode, both the full snapshot validation path and compact architect+evidence path must be supplied. Before planning, validate their hash, environment,+table facts, candidate order, and top-three cap without reading the full snapshot:++```bash+node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \+ --snapshot "<foreground snapshot path>" \+ --output "<compact architect evidence path>" \+ --validate-only+```-- 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.+The compact sidecar must have `schemaVersion: 1`, the foreground environment URL+and tenant, and a valid `sourceSnapshotSha256`. A non-zero validation result is+`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`.If validation succeeds, this path is mandatory:-1. Read the snapshot once and the evidence appendix once.+1. Read the compact architect evidence once. Do not use `Read`, `Grep`, or shell+ output to load the full snapshot into model context; its path is only for the+ deterministic validation command above and the post-contract decision gate.2. Skip Steps 1–3 environment resolution, access verification, and broaddiscovery. 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+4. Use `concepts[].topCandidates` for concept selection, `selectedTables` 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+ Treat candidates with `detailStatus: inventory-only` or `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:+ describe them as detailed. A selected table with `detailLevel: core` lacks+ decision-bearing enrichment and cannot authorize Reuse, Extend, or Adapt.+ Proposed-name checks are collision evidence, not required existing-table discovery.+ If the prompt includes `NEEDS_REVISION: dataverse-plan-validation`, revise+ the conflicting decisions from this same evidence. Do not request another+ metadata read or user answer merely because the previous contract proposed+ an unavailable name.+5. If a Reuse, Extend, or Adapt candidate, relationship target, or+ standard/managed dependency is absent from `selectedTables`, is represented+ only by a top candidate, or has `detailLevel: core`, 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.+ Sort and de-duplicate the names. The foreground performs an exact,+ incremental expansion for names that have not already been attempted. Do+ not downgrade a viable decision or perform another broad scan. If a name+ was already attempted and remains unavailable, classify the dependency+ `Defer` rather than requesting the same metadata again.6. Before emitting any `Create` or `Adapt` decision, verify its final logicalname appears in `proposedNameChecks.checked`. If one or more final names areabsent, 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.+ Sort and de-duplicate the names. The foreground runs an incremental+ collision-only expansion for names that have not already been checked. Do+ not infer absence from an unchecked name, and do not request a name again+ once its present/missing result is available.If either required artifact is missing, invalid, or mismatched, return`NEEDS_CONTEXT: matching-dataverse-snapshot-and-evidence`. Do not fall back to@@ -170,7 +194,7 @@ 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), 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.+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 data-model review; `/add-dataverse` re-queries live metadata and blocks any mutation it cannot verify.## Step 2 — Verify Dataverse Access@@ -242,8 +266,8 @@ count and elapsed time.> "→ 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+compact architect evidence", run no live Dataverse command, and use+`selectedTables` plus its selection evidence. Before assigning any decision on thelegacy live path, resolve every required entity — including `contact`,`account`, `incident`, other standard tables, and managed-solutiondependencies — in a **single** filtered query that also expands their columns:@@ -255,7 +279,7 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET \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).-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.+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. On the legacy live-discovery path only, if the batched query itself fails before a trustworthy snapshot exists, mark the affected entities `Unverified` rather than `Create`. In snapshot-only mode, an attempted table-detail failure is `Defer`.For each required entity, classify it as exactly one of:@@ -264,7 +288,7 @@ For each required entity, classify it as exactly one of:- **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+- **Unverified** — legacy live-discovery mode only: discovery could not run for this entity before a trustworthy foreground snapshot existed. Never use this state for a `detailLoadFailures` entry; that entry is `Defer`Classify every planned column before finalizing its table decision:@@ -272,7 +296,7 @@ Classify every planned column before finalizing its table decision:- **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.+- **Unverified** — legacy live-discovery mode only: column discovery could not run before a trustworthy foreground snapshot existed. A column affected by a snapshot `detailLoadFailures` entry is `Defer`.`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.@@ -283,7 +307,7 @@ Classify every planned column before finalizing its table decision: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. **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.+6. **Adapt / Defer / Unverified** → incompatible custom schema becomes Adapt when a safe app-owned alias preserves semantics; missing/incompatible standard, managed, required-existing, or attempted-but-unavailable snapshot metadata becomes Defer. Unverified is reserved for the legacy path where trustworthy discovery never ran. 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:>@@ -291,9 +315,9 @@ Classify every planned column before finalizing its table decision:> 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 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.+> **Default is Reuse or Extend only when compatibility is proven.** Adapt is the exceptional path, not the fallback. Request incremental detailed expansion only when the candidate is inventory-only or core-only and has not already been fully attempted. If a valid snapshot records the detail read as unavailable, classify Defer. Use Unverified only on the legacy path where discovery never ran. 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`.+> Surfacing the collision at PLAN time (not at create time) prevents the user from approving the data model with a name that will explode at Step 5a of `/add-dataverse`.Build a table:@@ -307,7 +331,7 @@ Build a table:```In snapshot-only mode, keep `Target evidence` concise: cite the relevant-concept/table anchor in the planning evidence appendix and state only the+concept/table anchor in the compact architect evidence and state only thedecision-bearing fact (for example, "appendix: `contact`; customizable=yes;2/2 required columns present"). Do not restate raw inventory, option lists, orfull column payloads.@@ -427,8 +451,8 @@ Write the section to a file in the working directory named `_dm_section.md` (the### Planning Evidence-- Deterministic appendix: `<relative planning evidence path>`-- Environment and generated timestamp match the validated snapshot.+- Compact hash-bound sidecar: `<relative architect evidence path>`+- Environment and source snapshot hash passed deterministic validation.### Target Reconciliation@@ -635,7 +659,7 @@ or written business/status column needed by the app, and each shown lookupnames for Create/Extend schema. Mechanically verify that no relationshipendpoint 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.+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 data-model approval (Gate 2 in `/create-mobile-app`) 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 milestonediff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.mdindex dc32cd018..f67017943 100644--- a/plugins/mobile-apps/agents/native-app-planner.md+++ b/plugins/mobile-apps/agents/native-app-planner.md@@ -25,8 +25,9 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:- Wizard answers collected by the skill (target users + device, aesthetic, features); target platforms are always iOS and Android- 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+- The foreground-generated normalized Dataverse planning snapshot path for+ deterministic validation, when available+- The compact hash-bound Dataverse architect evidence sidecar path, when available- Dataverse planning mode: `required` or `connector-only` in `complete` phase- Architecture phase: `gate-only` or `complete`- Approved architecture artifact path for `complete` phase@@ -51,17 +52,19 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:the Dataverse model only when required, then spawn `screen-planner` with everyapproved dependency.- **Application Insights is outside the plan gates.** Treat requests to enable telemetry for the generated app as host/runtime configuration owned by the `/setup-app-insights` skill (standalone or via `/edit-app`). Do not model Application Insights in the data model, native-capability matrix, connector list, or as a telemetry-specific screen. In particular, never propose the deprecated Azure Application Insights connector or a custom connector for telemetry ingestion. When the user explicitly names custom events, preserve them as `Custom events` annotations on the corresponding normal business-screen specs; this records behavior without turning telemetry into a planning gate or data source.-- **Dataverse planning forwarding is verbatim.** In `complete` phase, for every `required`- `data-model-architect` dispatch and revision, pass the planning mode and both- planning-snapshot/evidence absolute paths unchanged. Never dispatch the- architect in `connector-only` mode and never invent placeholder artifact+- **Dataverse planning forwarding is verbatim.** In `complete` phase, pass the+ planning mode to every `required` `data-model-architect` dispatch and revision,+ with both full-snapshot validation and compact-evidence absolute paths unchanged.+ The architect may read only the compact sidecar; the full snapshot is an opaque+ input to deterministic validators. Never dispatch the architect in+ `connector-only` mode and never invent placeholder artifactpaths. Do notresolve the environment, verify Dataverse access, run broad discovery, orissue any live Dataversequery 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+ rationale, ER diagram, tiers, and risks verbatim. Keep the compact sidecar as areferenced artifact; do not paste candidate rankings, raw columns, or timingtables into `native-app-plan.md`.- **Connectivity intent ownership.** Follow@@ -334,21 +337,43 @@ architecture inputs:> Working directory: [absolute path]> Plugin root: ${PLUGIN_ROOT}> Dataverse planning mode: required-> Normalized Dataverse foreground planning snapshot: [absolute path supplied by foreground verbatim]-> Dataverse planning evidence: [absolute path supplied by foreground verbatim]+> Normalized Dataverse foreground planning snapshot (validator input only; do not read into model context): [absolute path supplied by foreground verbatim]+> Compact Dataverse architect evidence: [absolute path supplied by foreground verbatim]> Structured schema contract output: `<working_dir>/.tmp/dataverse-schema-contract.json`+The architect validates the compact evidence against the full snapshot before+reading it, then writes and normalizes the contract covering every proposed+table, column, relationship, and alternate key. It does not resolve the+environment or run live discovery. Retained PDFs use approved File storage, not+long text/base64; connector-owned storage remains owned by that connector.+The architect must account for approved capture/storage targets and avoidduplicating entities owned by approved connectors. Wait for its return andapply the standard status switch:- `DONE` or `DONE_WITH_CONCERNS:` — require `_dm_section.md` and the normalized- schema contract, then continue.+ `.tmp/dataverse-schema-contract.json`, then run+ `validate-dataverse-planning-decisions.js --contract <contract> --snapshot <snapshot>`.+ Exit `3` must preserve the validator's exact stderr first line:+ `NEEDS_CONTEXT: detailed-dataverse-metadata:<sorted-logical-names>` or+ `NEEDS_CONTEXT: proposed-dataverse-names:<sorted-logical-names>`. Do not+ rewrite one signal as the other. Exit `4` begins with+ `NEEDS_REVISION: dataverse-plan-validation`; re-spawn the architect with the+ validator's safe error lines, the approved architecture, and the same+ snapshot/compact-evidence paths. This is an automatic decision revision:+ do not request more metadata or ask the user. If the revised contract repeats+ the same validation conflict, return+ `NEEDS_CONTEXT: dataverse-plan-revision:<short-safe-classification>` for the+ foreground's inline revision fallback. Exit `2` is reserved for an invalid+ contract/snapshot artifact and is `BLOCKED`; only exit `0` permits+ embedding and Gate 2. A missing sidecar is `BLOCKED`, not a Markdown-parsing+ fallback. Propagate any architect concerns after the same validation.- `NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>` or`NEEDS_CONTEXT: proposed-dataverse-names:<logical names>` — return the exactsignal to the foreground for one bounded expansion.- Other `NEEDS_CONTEXT:` — re-dispatch once with the missing context and the- same approved architecture sections.+ same approved architecture sections and snapshot/compact-evidence paths.+ If the second return also needs context, propagate the unresolved blocker.- `BLOCKED:` — propagate as a substantive planner block.## Design Planning@@ -453,6 +478,12 @@ dispatch or re-dispatch `data-model-architect`, and do not create a schemacontract or data-model approval receipt. Mark the Data Model section`not applicable — no Dataverse` and continue to screen planning.+In `required` mode, Gate 2 has a mechanical precondition: the most recent+`validate-dataverse-planning-decisions.js` run for the current normalized schema+contract and foreground snapshot exited `0`. Never show Gate 2 while a Reuse,+Extend, or Adapt decision is backed only by missing or `core` detail. Gate 1+architecture acceptance does not satisfy this data-model precondition.+For `required` mode, call `EnterPlanMode` and present:```@@ -473,8 +504,9 @@ Call `ExitPlanMode` to request approval.This receipt is written by this gate-owning planner, never by the Step 8manifest builder. Continue to screen planning.- **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+ the original planning-snapshot/compact-evidence paths verbatim, regenerate that section, and+ regenerate/normalize the structured sidecar, then rerun Step 5's decision+ validation before re-entering plan mode. Loopuntil approved; do not run discovery during a revision. Every revision mustretain the Gate 1-approved native capabilities and connectors as architectinputs.diff --git a/plugins/mobile-apps/scripts/benchmark-dataverse-planning.js b/plugins/mobile-apps/scripts/benchmark-dataverse-planning.jsdeleted file mode 100644index 7bd460aaf..000000000--- a/plugins/mobile-apps/scripts/benchmark-dataverse-planning.js+++ /dev/null@@ -1,520 +0,0 @@-#!/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.jsindex 407d0ed89..d14a4f17b 100644--- a/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js+++ b/plugins/mobile-apps/scripts/build-dataverse-operation-manifest.js@@ -1090,6 +1090,10 @@ function expectedColumnConstraints(column) {['canStoreFullImage', column.canStoreFullImage !== false, 'CanStoreFullImage',(actual, expected) => Boolean(actual) === expected],);+ if (hasOwn(column, 'isPrimaryImage')) {+ constraints.push(['isPrimaryImage', Boolean(column.isPrimaryImage), 'IsPrimaryImage',+ (actual, expected) => actual === expected]);+ }} else if (type === 'file') {constraints.push(['maxSizeInKB', Number(column.maxSizeInKB ?? 32768), 'MaxSizeInKB',@@ -1857,7 +1861,7 @@ function operationAffectedPublishTables(operation) {function revisedEquivalentOperation(previousOperation, previousManifest, normalized, context) {const expectedItemType = String(previousOperation?.id || '').startsWith('create-table:')? 'table'- : String(previousOperation?.id || '').startsWith('extend-column:')+ : /^(extend-column|configure-image):/.test(String(previousOperation?.id || ''))? 'column': String(previousOperation?.id || '').startsWith('create-relationship:')? 'relationship'@@ -1926,6 +1930,41 @@ function revisedEquivalentOperation(previousOperation, previousManifest, normaliconst effectiveColumn = normalizeName(column.adaptedLogicalName || column.logicalName,);+ if (String(previousOperation.id).startsWith('configure-image:')) {+ const definition = previousOperation.body;+ if (!isImageConfigurationPut(previousOperation)+ || normalizeColumnType(column.type) !== 'image'+ || ['defer', 'unverified'].includes(table.plannedDecision)+ || normalizeName(definition.LogicalName) !== effectiveColumn+ || normalizeName(definition.SchemaName)+ !== normalizeName(column.adaptedSchemaName || column.schemaName)) {+ return null;+ }+ const comparison = baseColumnCompatibility(column, {+ type: definition.AttributeType,+ typeName: metadataValue(definition.AttributeTypeName),+ sourceType: metadataValue(definition.SourceType) ?? null,+ requiredLevel: metadataValue(definition.RequiredLevel),+ primaryName: Boolean(definition.IsPrimaryName),+ maxSizeInKB: definition.MaxSizeInKB,+ canStoreFullImage: definition.CanStoreFullImage,+ isPrimaryImage: definition.IsPrimaryImage,+ });+ if (!comparison.compatible) return null;++ // The completed PUT is hash-bound evidence of the full image definition.+ // Preserve labels, immutable thumbnail fields, and any larger size already+ // applied; a create-column payload would discard that existing metadata.+ return operation(+ 0,+ `configure-image:${effectiveTable}:${effectiveColumn}`,+ 'extensions',+ `EntityDefinitions(LogicalName='${effectiveTable}')/Attributes(LogicalName='${effectiveColumn}')`,+ stableClone(definition),+ context.solutionUniqueName,+ 'PUT',+ );+ }return operation(0,`extend-column:${effectiveTable}:${effectiveColumn}`,@@ -3906,6 +3945,8 @@ module.exports = {contractApprovalContent,createPublishCheckpoint,declaredServiceRequiredTableNames,+ derivedExpected,+ isComputedColumn,normalizeColumnType,normalizedContract,parseArgs,diff --git a/plugins/mobile-apps/scripts/create-dataverse-snapshot.js b/plugins/mobile-apps/scripts/create-dataverse-snapshot.jsindex b5fa2b2cf..1e21cd9cd 100644--- a/plugins/mobile-apps/scripts/create-dataverse-snapshot.js+++ b/plugins/mobile-apps/scripts/create-dataverse-snapshot.js@@ -4,6 +4,11 @@const fs = require('node:fs');const path = require('node:path');const { createDataverseRequestExecutor } = require('./dataverse-request');+const {+ DEFAULT_TTL_MS,+ readInventoryCache,+ writeInventoryCache,+} = require('./dataverse-inventory-cache');const ENTITY_SELECT = ['LogicalName',@@ -48,6 +53,39 @@ const ATTRIBUTE_SELECT = ['IsLogical',].join(',');+const BASE_METADATA_COLLECTIONS = [+ {+ property: 'Attributes',+ result: 'attributes',+ select: ATTRIBUTE_SELECT,+ label: 'attributes',+ },+ {+ property: 'ManyToOneRelationships',+ result: 'manyToOneRelationships',+ select: 'SchemaName,ReferencingAttribute,ReferencedEntity,ReferencedAttribute,IsManaged,CascadeConfiguration',+ label: 'many-to-one relationships',+ },+ {+ property: 'OneToManyRelationships',+ result: 'oneToManyRelationships',+ select: 'SchemaName,ReferencingEntity,ReferencingAttribute,ReferencedAttribute,IsManaged,CascadeConfiguration',+ label: 'one-to-many relationships',+ },+ {+ property: 'ManyToManyRelationships',+ result: 'manyToManyRelationships',+ select: 'SchemaName,Entity1LogicalName,Entity1IntersectAttribute,Entity2LogicalName,Entity2IntersectAttribute,IntersectEntityName,IsManaged',+ label: 'many-to-many relationships',+ },+ {+ property: 'Keys',+ result: 'keys',+ select: 'LogicalName,SchemaName,KeyAttributes,EntityKeyIndexStatus,IsManaged',+ label: 'alternate keys',+ },+];+const CHOICE_TYPE_BY_ATTRIBUTE = {Boolean: 'BooleanAttributeMetadata',Picklist: 'PicklistAttributeMetadata',@@ -117,9 +155,33 @@ const GENERIC_CONCEPT_TOKENS = new Set(['workflows',]);+const LOW_INFORMATION_CONCEPT_TOKENS = new Set([+ 'current',+ 'date',+ 'document',+ 'expected',+ 'field',+ 'item',+ 'number',+ 'result',+]);++const CONCEPT_KINDS = new Set([+ 'action',+ 'attribute',+ 'constraint',+ 'entity',+ 'role',+ 'status',+]);+const MAX_TABLES_PER_CONCEPT = 3;const MAX_ADVISORY_DETAIL_TABLES = 40;const MAX_EXACT_NAME_TABLES = 50;+const MAX_STRONG_COLLISION_DETAILS = 10;+const MAX_READ_CONCURRENCY = 8;+const AMBIGUOUS_SCORE_GAP = 25;+const WEAK_MATCH_SCORE = 750;function parseArgs(argv) {const args = {};@@ -144,6 +206,111 @@ function parseList(value) {.filter(Boolean))];}+function parseReadConcurrency(value) {+ if (value === undefined || value === null || value === '') return 1;+ const parsed = Number(value);+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_READ_CONCURRENCY) {+ throw new Error(`read concurrency must be an integer from 1 to ${MAX_READ_CONCURRENCY}`);+ }+ return parsed;+}++function mapWithConcurrency(items, initialConcurrency, worker, {+ currentConcurrency = () => initialConcurrency,+} = {}) {+ if (!Array.isArray(items)) return Promise.reject(new Error('items must be an array'));+ parseReadConcurrency(initialConcurrency);+ if (typeof worker !== 'function') return Promise.reject(new Error('worker must be a function'));+ const results = new Array(items.length);+ if (items.length === 0) return Promise.resolve(results);+ return new Promise((resolve, reject) => {+ let active = 0;+ let nextIndex = 0;+ let firstError = null;++ function dispatch() {+ const cap = Math.max(1, Math.min(+ initialConcurrency,+ parseReadConcurrency(currentConcurrency()),+ ));+ while (!firstError && active < cap && nextIndex < items.length) {+ const index = nextIndex++;+ active += 1;+ Promise.resolve(worker(items[index], index))+ .then((result) => {+ results[index] = result;+ })+ .catch((error) => {+ firstError = firstError || error;+ })+ .finally(() => {+ active -= 1;+ if (active === 0 && (firstError || nextIndex >= items.length)) {+ if (firstError) reject(firstError);+ else resolve(results);+ return;+ }+ dispatch();+ });+ }+ }++ dispatch();+ });+}++function adaptiveReadRequest(request, initialConcurrency) {+ let concurrency = parseReadConcurrency(initialConcurrency);+ const reduceConcurrency = () => {+ concurrency = Math.max(1, Math.floor(concurrency / 2));+ };+ const receivesImmediateRateLimit = typeof request.onRateLimited === 'function';+ const unsubscribe = receivesImmediateRateLimit+ ? request.onRateLimited(reduceConcurrency)+ : null;+ return {+ currentConcurrency: () => concurrency,+ dispose: () => {+ if (typeof unsubscribe === 'function') unsubscribe();+ },+ request: async (...args) => {+ const response = await request(...args);+ if (response?.rateLimited && !receivesImmediateRateLimit) reduceConcurrency();+ return response;+ },+ };+}++function normalizeStructuredConcept(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error('Structured Dataverse concepts must be objects');+ }+ const phrase = String(value.phrase || '').trim();+ const kind = String(value.kind || '').trim().toLowerCase();+ if (!phrase) throw new Error('Structured Dataverse concept phrase is required');+ if (!CONCEPT_KINDS.has(kind)) {+ throw new Error(`Structured Dataverse concept kind is invalid: ${kind || '<missing>'}`);+ }+ return {+ phrase,+ kind,+ discoverTable: value.discoverTable === undefined+ ? kind === 'entity'+ : Boolean(value.discoverTable),+ evidence: value.evidence == null ? null : String(value.evidence),+ };+}++function parseConcepts(args, fileSystem = fs) {+ if (args['concepts-file'] && args.concepts) {+ throw new Error('--concepts and --concepts-file are mutually exclusive');+ }+ if (!args['concepts-file']) return parseList(args.concepts);+ const parsed = JSON.parse(fileSystem.readFileSync(path.resolve(args['concepts-file']), 'utf8'));+ if (!Array.isArray(parsed)) throw new Error('--concepts-file must contain a JSON array');+ return parsed.map(normalizeStructuredConcept);+}+function atomicWriteFile(file, content, fileSystem = fs) {fileSystem.mkdirSync(path.dirname(file), { recursive: true });const temporary = `${file}.tmp-${process.pid}-${Date.now()}`;@@ -173,6 +340,26 @@ function normalizeNextLink(nextLink) {return nextLink && markerIndex >= 0 ? nextLink.slice(markerIndex + marker.length) : nextLink;}+function metadataCollectionValues(data, label) {+ if (!data || typeof data !== 'object' || Array.isArray(data)+ || !Array.isArray(data.value)+ || data.value.some((item) => !item || typeof item !== 'object' || Array.isArray(item))) {+ throw new Error(`${label} must return an OData collection with an object-array value`);+ }+ if (data['@odata.nextLink'] != null+ && (typeof data['@odata.nextLink'] !== 'string' || !data['@odata.nextLink'].trim())) {+ throw new Error(`${label} returned an invalid OData continuation link`);+ }+ return data.value;+}++function requireEntityIdentities(entities, label) {+ if (entities.some((entity) => typeof entity?.LogicalName !== 'string'+ || !/^[A-Za-z][A-Za-z0-9_]*$/.test(entity.LogicalName))) {+ throw new Error(`${label} contains a missing or invalid table LogicalName`);+ }+}+async function requestCollection(request, apiPath, label, { optional = false } = {}) {const values = [];let next = apiPath;@@ -186,12 +373,78 @@ async function requestCollection(request, apiPath, label, { optional = false } =error.metadataError = detail;throw error;}- values.push(...(response.data?.value || []));+ values.push(...metadataCollectionValues(response.data, label));next = response.data?.['@odata.nextLink'] || null;}return values;}+async function requestCombinedBaseMetadata(request, root, logicalName) {+ const expand = BASE_METADATA_COLLECTIONS.map(+ (collection) => `${collection.property}($select=${collection.select})`,+ ).join(',');+ const response = await request('GET', `${root}?$select=LogicalName&$expand=${expand}`);+ if (response.status < 200 || response.status >= 300) {+ const detail = response.error || JSON.stringify(response.data || {}) || 'unknown error';+ const error = new Error(`${logicalName} combined base metadata failed (${response.status}): ${detail}`);+ error.status = response.status;+ error.metadataError = detail;+ throw error;+ }+ const result = {};+ for (const collection of BASE_METADATA_COLLECTIONS) {+ const initial = response.data?.[collection.property];+ if (!Array.isArray(initial)) {+ throw new Error(+ `${logicalName} combined base metadata omitted ${collection.property}`,+ );+ }+ const values = [...initial];+ let next = response.data?.[`${collection.property}@odata.nextLink`] || null;+ while (next) {+ const page = await request('GET', normalizeNextLink(next));+ if (page.status < 200 || page.status >= 300) {+ const detail = page.error || JSON.stringify(page.data || {}) || 'unknown error';+ const error = new Error(+ `${logicalName} ${collection.label} continuation failed (${page.status}): ${detail}`,+ );+ error.status = page.status;+ error.metadataError = detail;+ throw error;+ }+ if (!Array.isArray(page.data?.value)) {+ throw new Error(`${logicalName} ${collection.label} continuation omitted value`);+ }+ values.push(...page.data.value);+ next = page.data['@odata.nextLink'] || null;+ }+ result[collection.result] = values;+ }+ return result;+}++const unsupportedCombinedReadRequests = new WeakSet();++async function requestBaseMetadata(request, root, logicalName, combinedBaseRead = false) {+ if (combinedBaseRead && !unsupportedCombinedReadRequests.has(request)) {+ try {+ return await requestCombinedBaseMetadata(request, root, logicalName);+ } catch (error) {+ if (![400, 501].includes(error.status)) throw error;+ unsupportedCombinedReadRequests.add(request);+ }+ }+ const result = {};+ for (const collection of BASE_METADATA_COLLECTIONS) {+ result[collection.result] = await requestCollection(+ request,+ `${root}/${collection.property}?$select=${collection.select}`,+ `${logicalName} ${collection.label}`,+ );+ }+ return result;+}+function logicalNameOf(entity) {return String(entity?.LogicalName || entity?.logicalName || '');}@@ -219,47 +472,86 @@ function mergeEntitiesByLogicalName(entities, additions) {);}-async function resolveExactNameEntities(request, entities, requestedNames) {+async function resolveExactNameEntities(+ request,+ entities,+ requestedNames,+ { refreshRequested = false, refreshRequestedNames = null } = {},+) {const requestedTables = uniqueLogicalNames(requestedNames);const existingNames = new Set((entities || []).map((entity) => logicalNameOf(entity).toLowerCase()).filter(Boolean),);+ const refreshKeys = new Set(+ refreshRequestedNames == null+ ? refreshRequested+ ? requestedTables.map((name) => name.toLowerCase())+ : []+ : uniqueLogicalNames(refreshRequestedNames).map((name) => name.toLowerCase()),+ );const queriedTables = requestedTables.filter(- (logicalName) => !existingNames.has(logicalName.toLowerCase()),+ (logicalName) => (+ refreshKeys.has(logicalName.toLowerCase())+ || !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 || {})}`,- );+ const batches = [];+ for (const logicalName of queriedTables) {+ const candidate = [...(batches.at(-1) || []), logicalName];+ const filter = candidate+ .map((name) => `LogicalName eq '${odataString(name)}'`)+ .join(' or ');+ const apiPath = `EntityDefinitions?$select=${ENTITY_SELECT}&$filter=${filter}&LabelLanguages=1033`;+ if (candidate.length > MAX_EXACT_NAME_TABLES || apiPath.length > 8000) {+ if (candidate.length === 1) {+ throw new Error(`Exact-name metadata query exceeds the bounded URL budget: ${logicalName}`);+ }+ batches.push([logicalName]);+ } else if (batches.length === 0) {+ batches.push(candidate);+ } else {+ batches[batches.length - 1] = candidate;+ }}- if (response.data?.['@odata.nextLink']) {- throw new Error('Exact-name table metadata exceeded one bounded response page');+ for (const batch of batches) {+ const filter = batch+ .map((logicalName) => `LogicalName eq '${odataString(logicalName)}'`)+ .join(' or ');+ const apiPath = `EntityDefinitions?$select=${ENTITY_SELECT}&$filter=${filter}&LabelLanguages=1033`;+ 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 || {})}`,+ );+ }+ const exactEntities = metadataCollectionValues(response.data, 'Exact-name table metadata');+ requireEntityIdentities(exactEntities, 'Exact-name table metadata');+ if (response.data?.['@odata.nextLink']) {+ throw new Error('Exact-name table metadata exceeded one bounded response page');+ }+ const batchKeys = new Set(batch.map((name) => name.toLowerCase()));+ discovered.push(...exactEntities.filter(+ (entity) => batchKeys.has(logicalNameOf(entity).toLowerCase()),+ ));}- 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 refreshedKeys = new Set(+ queriedTables+ .map((name) => name.toLowerCase())+ .filter((name) => refreshKeys.has(name)),+ );+ // A cache hit may contain a table that was deleted or whose table-level+ // metadata changed. Live exact-name results are authoritative for every+ // requested name, including an empty response.+ const retainedEntities = (entities || []).filter(+ (entity) => !refreshedKeys.has(logicalNameOf(entity).toLowerCase()),+ );+ const mergedEntities = mergeEntitiesByLogicalName(retainedEntities, discovered);const availableNames = new Map(mergedEntities.map((entity) => [logicalNameOf(entity).toLowerCase(), logicalNameOf(entity)]),);@@ -330,18 +622,36 @@ function isVersionedName(logicalName) {}function conceptDescriptor(value) {- const raw = String(value || '').trim().toLowerCase();+ const structured = value && typeof value === 'object' && !Array.isArray(value)+ ? normalizeStructuredConcept(value)+ : null;+ const raw = String(structured?.phrase ?? value ?? '').trim().toLowerCase();const aliases = CONCEPT_ALIASES[raw] || [];const tokens = normalizedTokens(raw);const aliasTokens = aliases.flatMap(normalizedTokens);+ const kind = structured?.kind || 'legacy';+ const discoverTable = structured?.discoverTable ?? true;return {raw,+ kind,+ discoverTable,+ evidence: structured?.evidence || null,+ typed: Boolean(structured),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)),+ .filter((token) => token.length >= 3+ && !GENERIC_CONCEPT_TOKENS.has(token)+ && !(structured && LOW_INFORMATION_CONCEPT_TOKENS.has(token))),};}+function matchClassFromReasons(reasons) {+ for (const kind of ['exact', 'suffix', 'contains', 'token', 'partial-token']) {+ if (reasons.some((reason) => reason.startsWith(`${kind}:`))) return kind;+ }+ return 'none';+}+function scoreEntityForConcept(entity, descriptor) {const parts = entitySearchParts(entity);const compactParts = parts.map(compact);@@ -372,13 +682,14 @@ function scoreEntityForConcept(entity, descriptor) {}}- if (score === 0) return { score: 0, reasons: [] };+ if (score === 0) return { score: 0, reasons: [], matchClass: 'none' };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)] };+ const uniqueReasons = [...new Set(reasons)];+ return { score, reasons: uniqueReasons, matchClass: matchClassFromReasons(uniqueReasons) };}function compareCandidates(left, right, preferredFamily = null) {@@ -397,7 +708,7 @@ function compareCandidates(left, right, preferredFamily = null) {function rankCandidatesByConcept(entities, concepts) {const preliminary = concepts.map((concept) => {const descriptor = conceptDescriptor(concept);- const candidates = entities+ const candidates = descriptor.discoverTable ? entities.map((entity) => {const scored = scoreEntityForConcept(entity, descriptor);return {@@ -407,9 +718,10 @@ function rankCandidatesByConcept(entities, concepts) {versioned: isVersionedName(entity.LogicalName),score: scored.score,reasons: scored.reasons,+ matchClass: scored.matchClass,};})- .filter((candidate) => candidate.score > 0);+ .filter((candidate) => candidate.score > 0) : [];return { concept, descriptor, candidates };});@@ -452,9 +764,13 @@ function rankCandidatesByConcept(entities, concepts) {versioned: candidate.versioned,score: Number(candidate.score.toFixed(2)),reasons: candidate.reasons,+ matchClass: candidate.matchClass,}));return {- concept: entry.concept,+ concept: entry.descriptor.raw,+ conceptKind: entry.descriptor.kind,+ discoverTable: entry.descriptor.discoverTable,+ skippedReason: entry.descriptor.discoverTable ? null : `concept-kind:${entry.descriptor.kind}`,normalizedTokens: entry.descriptor.matchTokens,preferredPublisherFamily: preferredFamily,candidates,@@ -462,7 +778,7 @@ function rankCandidatesByConcept(entities, concepts) {});}-function selectDetailedCandidates(entities, tableNames, concepts) {+function selectLegacyDetailedCandidates(entities, tableNames, concepts) {const explicitNames = new Set(tableNames.map((value) => value.toLowerCase()));const rankings = rankCandidatesByConcept(entities, concepts);const selectedReasons = new Map();@@ -594,19 +910,232 @@ function selectDetailedCandidates(entities, tableNames, concepts) {};}+function typedCandidateIsAmbiguous(ranking) {+ const [primary, alternative] = ranking.candidates;+ if (!primary || !alternative) return false;+ const scoreGap = primary.score - alternative.score;+ return scoreGap <= AMBIGUOUS_SCORE_GAP+ || primary.score < WEAK_MATCH_SCORE+ || (primary.versioned && !alternative.versioned && scoreGap <= 300)+ || (+ primary.publisherFamily !== alternative.publisherFamily+ && primary.matchClass === alternative.matchClass+ && scoreGap <= AMBIGUOUS_SCORE_GAP+ );+}++function selectStrongProposedCollisions(+ entities,+ proposedTableNames,+ rankings,+ selectedReasons,+) {+ const entitiesByName = new Map(entities.map((entity) => [+ logicalNameOf(entity).toLowerCase(),+ entity,+ ]));+ const candidates = [];+ for (const logicalName of uniqueLogicalNames(proposedTableNames)) {+ if (selectedReasons.has(logicalName)) continue;+ const entity = entitiesByName.get(logicalName.toLowerCase());+ if (!entity || !managedValue(entity.IsCustomizable) || isVersionedName(logicalName)) continue;+ const displayTokens = normalizedTokens(labelText(entity.DisplayName))+ .filter((token) => token.length >= 3 && !GENERIC_CONCEPT_TOKENS.has(token));+ const displayCompact = displayTokens.join('');+ const matchingRanking = rankings.find((ranking) => {+ if (!ranking.discoverTable || ranking.conceptKind !== 'entity') return false;+ const ranked = ranking.candidates.find(+ (candidate) => candidate.logicalName.toLowerCase() === logicalName.toLowerCase(),+ );+ const rankOneExact = ranked?.rank === 1+ && ['exact', 'suffix'].includes(ranked.matchClass);+ const phraseCoverage = displayTokens.length >= 2+ && displayCompact.length >= 8+ && compact(ranking.concept).includes(displayCompact);+ return rankOneExact || phraseCoverage;+ });+ if (matchingRanking) candidates.push({ entity, concept: matchingRanking.concept });+ }+ const selected = candidates+ .sort((left, right) => logicalNameOf(left.entity).localeCompare(logicalNameOf(right.entity)))+ .slice(0, MAX_STRONG_COLLISION_DETAILS);+ for (const item of selected) {+ selectedReasons.set(+ logicalNameOf(item.entity),+ new Set(['proposed-collision:strong-concept-phrase', `concept:${item.concept}`]),+ );+ }+ return selected;+}++function selectTypedDetailedCandidates(+ entities,+ tableNames,+ concepts,+ { proposedTableNames = [], progressiveDetail = false } = {},+) {+ const explicitNames = new Set(tableNames.map((value) => value.toLowerCase()));+ const rankings = rankCandidatesByConcept(entities, concepts);+ const selectedReasons = new Map();+ const primaryNames = new Set();+ const ambiguityNames = new Set();+ let exactCoveredConcepts = 0;+ let unresolvedConcepts = 0;++ function addReason(logicalName, reason) {+ const current = selectedReasons.get(logicalName) || new Set();+ current.add(reason);+ selectedReasons.set(logicalName, current);+ }++ for (const entity of entities) {+ if (!explicitNames.has(logicalNameOf(entity).toLowerCase())) continue;+ addReason(logicalNameOf(entity), 'explicit-table');+ }++ for (const ranking of rankings) {+ if (!ranking.discoverTable || ranking.conceptKind !== 'entity'+ || ranking.candidates.length === 0) continue;+ const exactCoverage = ranking.candidates.find((candidate) => (+ explicitNames.has(candidate.logicalName.toLowerCase())+ && (candidate.rank === 1 || ['exact', 'suffix'].includes(candidate.matchClass))+ ));+ if (exactCoverage) {+ addReason(exactCoverage.logicalName, `concept:${ranking.concept}:exact-covered`);+ exactCoveredConcepts += 1;+ continue;+ }+ unresolvedConcepts += 1;+ const primary = ranking.candidates.find(+ (candidate) => !explicitNames.has(candidate.logicalName.toLowerCase()),+ );+ if (!primary) continue;+ addReason(primary.logicalName, `concept:${ranking.concept}:primary`);+ primaryNames.add(primary.logicalName);+ if (typedCandidateIsAmbiguous(ranking)) {+ const alternative = ranking.candidates.find((candidate) => (+ candidate.logicalName !== primary.logicalName+ && !explicitNames.has(candidate.logicalName.toLowerCase())+ ));+ if (alternative) {+ addReason(alternative.logicalName, `concept:${ranking.concept}:ambiguous-alternative`);+ ambiguityNames.add(alternative.logicalName);+ }+ }+ }++ const strongCollisions = selectStrongProposedCollisions(+ entities,+ proposedTableNames,+ rankings,+ selectedReasons,+ );+ const entityByName = new Map(entities.map((entity) => [logicalNameOf(entity), entity]));+ const selectedEntities = [...selectedReasons.keys()]+ .sort((left, right) => left.localeCompare(right))+ .map((logicalName) => entityByName.get(logicalName))+ .filter(Boolean);+ const selectedNames = new Set(selectedEntities.map(logicalNameOf));+ const consideredNames = new Set(rankings+ .filter((ranking) => ranking.discoverTable && ranking.conceptKind === 'entity')+ .flatMap((ranking) => ranking.candidates.slice(0, MAX_TABLES_PER_CONCEPT))+ .map((candidate) => candidate.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) || [])],+ })),+ }));+ const requiredCandidates = selectedEntities.filter((entity) => (+ selectedReasons.get(logicalNameOf(entity)).has('explicit-table')+ )).length;+ const advisoryCandidates = selectedEntities.length - requiredCandidates;+ const candidateByName = new Map();+ for (const candidate of rankings.flatMap((ranking) => ranking.candidates)) {+ const current = candidateByName.get(candidate.logicalName);+ if (!current || candidate.score > current.score) {+ candidateByName.set(candidate.logicalName, candidate);+ }+ }+ const detailLevels = new Map(selectedEntities.map((entity) => {+ const logicalName = logicalNameOf(entity);+ const reasons = selectedReasons.get(logicalName);+ const candidate = candidateByName.get(logicalName);+ const full = !progressiveDetail+ || reasons.has('explicit-table')+ || reasons.has('proposed-collision:strong-concept-phrase')+ || (+ candidate?.score >= WEAK_MATCH_SCORE+ && ['exact', 'suffix', 'contains'].includes(candidate.matchClass)+ );+ return [logicalName, full ? 'full' : 'core'];+ }));+ return {+ candidateRanking,+ selectedEntities,+ selectedEvidence: selectedEntities.map((entity) => ({+ logicalName: logicalNameOf(entity),+ reasons: [...selectedReasons.get(logicalNameOf(entity))].sort(),+ detailLevel: detailLevels.get(logicalNameOf(entity)),+ })),+ detailLevels,+ detailSelectionSummary: {+ requiredCandidates,+ advisoryCandidates,+ exactCoveredConcepts,+ unresolvedConcepts,+ advisoryLimit: Math.max(MAX_ADVISORY_DETAIL_TABLES, advisoryCandidates),+ primaryCandidates: primaryNames.size,+ ambiguityCandidates: [...ambiguityNames]+ .filter((logicalName) => !primaryNames.has(logicalName)).length,+ strongCollisionCandidates: strongCollisions.length,+ deferredCandidates: [...consideredNames]+ .filter((logicalName) => !selectedNames.has(logicalName)).length,+ coreCandidates: [...detailLevels.values()].filter((value) => value === 'core').length,+ fullCandidates: [...detailLevels.values()].filter((value) => value === 'full').length,+ },+ };+}++function selectDetailedCandidates(entities, tableNames, concepts, options = {}) {+ return concepts.some((concept) => concept && typeof concept === 'object')+ ? selectTypedDetailedCandidates(entities, tableNames, concepts, options)+ : selectLegacyDetailedCandidates(entities, tableNames, concepts);+}+function normalizeDetailLoadFailure(entity, reasons, error) {const status = Number(error?.status);+ const selectionReasons = [...reasons].sort();return {logicalName: entity.LogicalName,- selectionReasons: [...reasons].sort(),+ selectionReasons,status: Number.isInteger(status) && status >= 100 && status <= 599 ? status : null,error: String(error?.metadataError || error?.message || error || 'unknown error'),- required: false,+ required: selectionReasons.some(+ (reason) => reason === 'explicit-table' || reason === 'explicit-expansion',+ ),};}+function isPlanningAccessFailure(error) {+ const status = Number(error?.status);+ if (status === 0 || status === 401) return true;+ const message = String(+ error?.metadataError || error?.message || error || '',+ );+ return /failed to get .*token|token acquisition|run az login|not logged in|authentication required|etimedout|econnrefused|econnreset|enotfound|network error|socket hang up/i+ .test(message);+}+function applyDetailLoadOutcomes(candidateRanking, selectedEvidence, tables, failures) {- const loadedNames = new Set(tables.map((table) => table.logicalName.toLowerCase()));+ const loadedByName = new Map(tables.map((table) => [+ table.logicalName.toLowerCase(),+ table.detailLevel || 'full',+ ]));const failureByName = new Map(failures.map((failure) => [failure.logicalName.toLowerCase(), failure]),);@@ -616,18 +1145,20 @@ function applyDetailLoadOutcomes(candidateRanking, selectedEvidence, tables, faicandidates: ranking.candidates.map((candidate) => {const key = candidate.logicalName.toLowerCase();const failure = failureByName.get(key) || null;- const detailed = loadedNames.has(key);+ const detailLevel = loadedByName.get(key) || null;+ const detailed = Boolean(detailLevel);return {...candidate,detailed,detailStatus: detailed- ? 'loaded'+ ? detailLevel === 'core' ? 'loaded-core' : 'loaded': failure? 'unavailable': candidate.selectionEvidence?.length? 'pending': 'inventory-only',detailFailure: failure,+ detailLevel,};}),})),@@ -638,8 +1169,11 @@ function applyDetailLoadOutcomes(candidateRanking, selectedEvidence, tables, fai...item,required: item.reasons.includes('explicit-table')|| item.reasons.includes('explicit-expansion'),- detailStatus: loadedNames.has(key) ? 'loaded' : failure ? 'unavailable' : 'pending',+ detailStatus: loadedByName.has(key)+ ? loadedByName.get(key) === 'core' ? 'loaded-core' : 'loaded'+ : failure ? 'unavailable' : 'pending',detailFailure: failure,+ detailLevel: loadedByName.get(key) || null,};}),};@@ -719,54 +1253,46 @@ function relationshipCount(table) {+ (table.manyToManyRelationships?.length || 0);}-async function loadDetailedEntity(request, entity) {+async function loadDetailedEntity(request, entity, {+ detailLevel = 'full',+ combinedBaseRead = false,+} = {}) {+ if (!['core', 'full'].includes(detailLevel)) {+ throw new Error(`Unsupported detail level: ${detailLevel}`);+ }+ const fullDetail = detailLevel === 'full';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 {+ attributes,+ manyToOneRelationships,+ oneToManyRelationships,+ manyToManyRelationships,+ keys,+ } = await requestBaseMetadata(request, root, logicalName, combinedBaseRead);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),- });+ if (fullDetail) {+ 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 hasLookups = attributes.some((attribute) => attribute.AttributeType === 'Lookup');+ if (fullDetail && hasLookups) {const lookupMetadata = await requestCollection(request,`${root}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`,@@ -778,33 +1304,36 @@ async function loadDetailedEntity(request, entity) {const ordinaryConstraints = new Map();const imageUpdateDefinitions = 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,- type === 'ImageAttributeMetadata'- ? `${root}/Attributes/Microsoft.Dynamics.CRM.${type}`- : `${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]);+ if (fullDetail) {+ for (const type of ordinaryTypes) {+ const fields = ORDINARY_METADATA_FIELDS_BY_TYPE[type];+ const metadata = await requestCollection(+ request,+ type === 'ImageAttributeMetadata'+ ? `${root}/Attributes/Microsoft.Dynamics.CRM.${type}`+ : `${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);+ if (type === 'ImageAttributeMetadata') {+ imageUpdateDefinitions.set(item.LogicalName, item);}- }- ordinaryConstraints.set(item.LogicalName, constraints);- if (type === 'ImageAttributeMetadata') {- imageUpdateDefinitions.set(item.LogicalName, item);}}}const computedMetadata = new Map();- for (const attribute of attributes.filter(+ const computedAttributes = attributes.filter((item) => [1, 2, 3].includes(normalizeIntegerMetadata(item.SourceType)),- )) {+ );+ for (const attribute of fullDetail ? computedAttributes : []) {if (!attribute.MetadataId) {computedMetadata.set(attribute.LogicalName, {sourceType: normalizeIntegerMetadata(attribute.SourceType),@@ -891,6 +1420,13 @@ async function loadDetailedEntity(request, entity) {}}+ const missingDetailClasses = detailLevel === 'full' ? [] : [+ ...(choiceTypes.length ? ['choice-options'] : []),+ ...(hasLookups ? ['lookup-targets'] : []),+ ...(ordinaryTypes.length ? ['typed-constraints'] : []),+ ...(computedAttributes.length ? ['computed-metadata'] : []),+ ];+ const effectiveDetailLevel = missingDetailClasses.length === 0 ? 'full' : detailLevel;const table = {logicalName,schemaName: entity.SchemaName,@@ -920,6 +1456,8 @@ async function loadDetailedEntity(request, entity) {entity.CanBeRelatedEntityInRelationship,),canBeInManyToMany: managedValue(entity.CanBeInManyToMany),+ detailLevel: effectiveDetailLevel,+ missingDetailClasses: effectiveDetailLevel === 'full' ? [] : missingDetailClasses,columns: attributes.map((attribute) => {const computed = computedMetadata.get(attribute.LogicalName) || null;return {@@ -1086,6 +1624,58 @@ function validateSnapshot(snapshot, expected = {}) {}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?.tables)) {+ for (const [index, table] of snapshot.tables.entries()) {+ if (!isObject(table)) {+ errors.push(`tables[${index}] must be an object`);+ continue;+ }+ for (const field of ['logicalName', 'schemaName', 'entitySetName', 'primaryIdAttribute']) {+ if (typeof table[field] !== 'string' || !/^[A-Za-z][A-Za-z0-9_]*$/.test(table[field])) {+ errors.push(`tables[${index}].${field} must be a metadata identifier`);+ }+ }+ const detailLevel = table.detailLevel;+ const missingDetailClasses = table.missingDetailClasses;+ if (!['core', 'full'].includes(detailLevel)) {+ errors.push(`tables[${index}].detailLevel must be core or full`);+ }+ if (!Array.isArray(missingDetailClasses)+ || missingDetailClasses.some((value) => typeof value !== 'string' || !value)) {+ errors.push(`tables[${index}].missingDetailClasses must be a string array`);+ } else if (detailLevel === 'core' && missingDetailClasses.length === 0) {+ errors.push(`tables[${index}] core detail must identify missing metadata classes`);+ } else if (detailLevel === 'full' && missingDetailClasses.length > 0) {+ errors.push(`tables[${index}] full detail cannot list missing metadata classes`);+ }+ if (snapshot.purpose === 'execution-reconciliation' && detailLevel !== 'full') {+ errors.push(`tables[${index}] execution reconciliation requires full detail`);+ }+ for (const field of [+ 'columns', 'manyToOneRelationships', 'oneToManyRelationships',+ 'manyToManyRelationships', 'alternateKeys',+ ]) {+ if (!Array.isArray(table[field]) || table[field].some((item) => !isObject(item))) {+ errors.push(`tables[${index}].${field} must be an object array`);+ }+ }+ if (!isObject(table.facts)) {+ errors.push(`tables[${index}].facts must be an object`);+ } else {+ const counts = {+ columnCount: table.columns?.length,+ relationshipCount: relationshipCount(table),+ keyCount: table.alternateKeys?.length,+ };+ for (const [field, count] of Object.entries(counts)) {+ if (!Number.isInteger(table.facts[field]) || table.facts[field] < 0+ || table.facts[field] !== count) {+ errors.push(`tables[${index}].facts.${field} must match its metadata collections`);+ }+ }+ }+ }+ }if (!Array.isArray(snapshot?.candidateRanking)) errors.push('candidateRanking must be an array');if (!isObject(snapshot?.inventoryFacts)) {errors.push('inventoryFacts must be an object');@@ -1234,14 +1824,14 @@ function validateSnapshot(snapshot, expected = {}) {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(+ const hasRequiredReason = Array.isArray(failure.selectionReasons) && failure.selectionReasons.some((reason) => reason === 'explicit-table' || reason === 'explicit-expansion',- )) {- errors.push(`${prefix}.selectionReasons must be advisory`);- }+ );+ if (typeof failure.required !== 'boolean') {+ errors.push(`${prefix}.required must be a boolean`);+ } else if (failure.required !== Boolean(hasRequiredReason)) {+ errors.push(`${prefix}.required must match explicit selection reasons`);+ }}}if (snapshot?.detailLoadSummary === undefined) {@@ -1302,6 +1892,12 @@ async function createSnapshot({tableNames = [],proposedTableNames = [],concepts = [],+ progressiveDetail = false,+ combinedBaseRead = false,+ readConcurrency = 1,+ inventory = null,+ inventorySource = null,+ inventoryCacheAgeMs = null,request,nowMs = () => Date.now(),nowIso = () => new Date().toISOString(),@@ -1311,36 +1907,47 @@ async function createSnapshot({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 customizableEntities = Array.isArray(inventory)+ ? inventory.map((item) => (item.logicalName ? inventoryEntityToRaw(item) : item))+ : await requestCollection(+ request,+ [+ 'EntityDefinitions?',+ `$select=${ENTITY_SELECT}`,+ '&$filter=IsCustomizable/Value eq true',+ '&LabelLanguages=1033',+ ].join(''),+ 'Customizable-table inventory',+ );+ requireEntityIdentities(customizableEntities, '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 liveRefreshedExactNames = [...allExactCheckNames];const exactResolution = await resolveExactNameEntities(request,customizableEntities,allExactCheckNames,+ { refreshRequested: inventorySource === 'cache' },+ );+ const customizableInventoryKeys = new Set(+ customizableEntities.map((entity) => logicalNameOf(entity).toLowerCase()),);- const entities = exactResolution.entities;+ const boundedExactDiscoveryTables = exactResolution.discoveredTables.filter(+ (name) => !customizableInventoryKeys.has(name.toLowerCase()),+ );+ let 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(+ const requiredDiscoveredTables = boundedExactDiscoveryTables.filter((name) => requiredNameKeys.has(name.toLowerCase()),);- const proposedCollisionTables = exactResolution.discoveredTables.filter(+ const proposedCollisionTables = boundedExactDiscoveryTables.filter((name) => proposedNameKeys.has(name.toLowerCase())&& !requiredNameKeys.has(name.toLowerCase()),);@@ -1348,12 +1955,15 @@ async function createSnapshot({(name) => !availableEntityNames.has(name.toLowerCase()),);const proposedNameChecks = analyzeProposedNames(entities, proposedNames);+ let finalCustomizableEntities = entities.filter(+ (entity) => managedValue(entity.IsCustomizable) === true,+ );const inventoryCompletedAt = nowMs();onProgress({milestoneId: 'inventory-loaded',inventoryTables: entities.length,- customizableInventoryTables: customizableEntities.length,- exactNameTables: exactResolution.discoveredTables.length,+ customizableInventoryTables: finalCustomizableEntities.length,+ exactNameTables: boundedExactDiscoveryTables.length,requiredExactNameTables: requiredDiscoveredTables.length,requiredExactNameUnavailable: requiredUnavailableTables.length,exactNameUnavailable: requiredUnavailableTables.length,@@ -1362,7 +1972,10 @@ async function createSnapshot({elapsedMs: inventoryCompletedAt - totalStartedAt,});- const selection = selectDetailedCandidates(entities, requiredNames, concepts);+ const selection = selectDetailedCandidates(entities, requiredNames, concepts, {+ proposedTableNames: proposedNames,+ progressiveDetail,+ });const selectionCompletedAt = nowMs();onProgress({milestoneId: 'candidates-selected',@@ -1384,20 +1997,66 @@ async function createSnapshot({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 selectedIdentities = new Map(+ selection.selectedEntities.map((entity) => [logicalNameOf(entity).toLowerCase(), entity]),+ );+ if (inventorySource === 'cache') {+ const refreshedNames = new Set(allExactCheckNames.map((name) => name.toLowerCase()));+ const pendingNames = [...selectedIdentities.keys()].filter((name) => !refreshedNames.has(name));+ if (pendingNames.length > 0) {+ // Cached inventory nominates candidates; only live table identities may supply+ // the capability flags and names in their full detail evidence.+ const refreshed = await resolveExactNameEntities(request, entities, pendingNames, {+ refreshRequested: true,+ });+ entities = refreshed.entities;+ finalCustomizableEntities = entities.filter((entity) => managedValue(entity.IsCustomizable));+ const freshByName = new Map(+ refreshed.entities.map((entity) => [logicalNameOf(entity).toLowerCase(), entity]),+ );+ for (const name of pendingNames) selectedIdentities.set(name, freshByName.get(name) || null);+ liveRefreshedExactNames.push(...pendingNames);}}+ const adaptiveRead = adaptiveReadRequest(request, readConcurrency);+ let outcomes;+ try {+ outcomes = await mapWithConcurrency(+ selection.selectedEntities,+ parseReadConcurrency(readConcurrency),+ async (entity) => {+ try {+ const currentEntity = selectedIdentities.get(logicalNameOf(entity).toLowerCase());+ if (!currentEntity) {+ const error = new Error('Selected cached table was not returned by live exact-name discovery');+ error.status = 404;+ throw error;+ }+ return {+ table: await loadDetailedEntity(adaptiveRead.request, currentEntity, {+ detailLevel: selection.detailLevels?.get(entity.LogicalName) || 'full',+ combinedBaseRead,+ }),+ failure: null,+ };+ } catch (error) {+ if (isPlanningAccessFailure(error)) throw error;+ const evidence = selectedEvidenceByName.get(entity.LogicalName.toLowerCase());+ return {+ table: null,+ failure: normalizeDetailLoadFailure(entity, evidence?.reasons || [], error),+ };+ }+ },+ { currentConcurrency: adaptiveRead.currentConcurrency },+ );+ } finally {+ adaptiveRead.dispose();+ }+ for (const outcome of outcomes) {+ if (outcome.table) tables.push(outcome.table);+ if (outcome.failure) detailLoadFailures.push(outcome.failure);+ }const detailCompletedAt = nowMs();onProgress({milestoneId: 'details-loaded',@@ -1410,9 +2069,6 @@ async function createSnapshot({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,@@ -1435,8 +2091,8 @@ async function createSnapshot({.map(normalizeInventoryEntity).sort((left, right) => left.logicalName.localeCompare(right.logicalName)),inventoryFacts: {- customizableTables: customizableEntities.length,- exactNameTables: exactResolution.discoveredTables.length,+ customizableTables: finalCustomizableEntities.length,+ exactNameTables: boundedExactDiscoveryTables.length,requiredExactNameTables: requiredDiscoveredTables.length,proposedCollisionTables: proposedCollisionTables.length,totalTables: entities.length,@@ -1450,14 +2106,23 @@ async function createSnapshot({loadedCandidates: tables.length,failedCandidates: detailLoadFailures.length,...selection.detailSelectionSummary,+ ...(combinedBaseRead ? { baseReadMode: 'combined' } : {}),+ ...(parseReadConcurrency(readConcurrency) !== 1+ || adaptiveRead.currentConcurrency() !== 1 ? {+ readConcurrency: parseReadConcurrency(readConcurrency),+ finalReadConcurrency: adaptiveRead.currentConcurrency(),+ } : {}),},proposedNameChecks,missingProposedTables: proposedNameChecks.missing,+ exactNameDiscoveryTables: boundedExactDiscoveryTables,+ ...(inventorySource === 'cache'+ ? { liveRefreshedExactNames: uniqueLogicalNames(liveRefreshedExactNames) }+ : {}),exactNameResolution: {requestedTables: requiredNames,loadedTables: requiredNames- .filter((logicalName) => detailedNames.has(logicalName.toLowerCase()))- .map((logicalName) => detailedNames.get(logicalName.toLowerCase())),+ .filter((logicalName) => availableEntityNames.has(logicalName.toLowerCase())),unavailableTables: requiredUnavailableTables,},timings: {@@ -1466,6 +2131,10 @@ async function createSnapshot({detailLoadingMs: detailCompletedAt - selectionCompletedAt,totalDurationMs: totalCompletedAt - totalStartedAt,},+ ...(inventorySource ? {+ inventorySource,+ inventoryCacheAgeMs: inventorySource === 'cache' ? inventoryCacheAgeMs : null,+ } : {}),};}@@ -1474,6 +2143,8 @@ async function createReconciliationSnapshot({tenantId,tableNames = [],proposedTableNames = [],+ combinedBaseRead = false,+ readConcurrency = 1,request,nowMs = () => Date.now(),nowIso = () => new Date().toISOString(),@@ -1517,9 +2188,17 @@ async function createReconciliationSnapshot({elapsedMs: inventoryCompletedAt - totalStartedAt,});- const tables = [];- for (const entity of entitiesToLoad) {- tables.push(await loadDetailedEntity(request, entity));+ const adaptiveRead = adaptiveReadRequest(request, readConcurrency);+ let tables;+ try {+ tables = await mapWithConcurrency(+ entitiesToLoad,+ parseReadConcurrency(readConcurrency),+ (entity) => loadDetailedEntity(adaptiveRead.request, entity, { combinedBaseRead }),+ { currentConcurrency: adaptiveRead.currentConcurrency },+ );+ } finally {+ adaptiveRead.dispose();}const detailCompletedAt = nowMs();onProgress({@@ -1577,6 +2256,12 @@ async function createReconciliationSnapshot({exactCoveredConcepts: 0,unresolvedConcepts: 0,advisoryLimit: 0,+ ...(combinedBaseRead ? { baseReadMode: 'combined' } : {}),+ ...(parseReadConcurrency(readConcurrency) !== 1+ || adaptiveRead.currentConcurrency() !== 1 ? {+ readConcurrency: parseReadConcurrency(readConcurrency),+ finalReadConcurrency: adaptiveRead.currentConcurrency(),+ } : {}),},proposedNameChecks,missingProposedTables: proposedNameChecks.missing,@@ -1615,10 +2300,14 @@ function inventoryEntityToRaw(entity) {PrimaryIdAttribute: entity.primaryIdAttribute,PrimaryNameAttribute: entity.primaryNameAttribute,OwnershipType: entity.ownershipType,- HasActivities: entity.hasActivities,- HasNotes: entity.hasNotes,- IsAvailableOffline: entity.isAvailableOffline,- ChangeTrackingEnabled: entity.changeTrackingEnabled,+ ...(entity.hasActivities == null ? {} : { HasActivities: entity.hasActivities }),+ ...(entity.hasNotes == null ? {} : { HasNotes: entity.hasNotes }),+ ...(entity.isAvailableOffline == null+ ? {}+ : { IsAvailableOffline: entity.isAvailableOffline }),+ ...(entity.changeTrackingEnabled == null+ ? {}+ : { ChangeTrackingEnabled: entity.changeTrackingEnabled }),IsCustomEntity: entity.customEntity,IsManaged: entity.managed,IsCustomizable: { Value: entity.customizable },@@ -1633,10 +2322,16 @@ function inventoryEntityToRaw(entity) {};}+function cacheablePlanningInventory(snapshot) {+ return (snapshot.inventory || []).filter((entity) => entity.customizable === true);+}+async function expandSnapshot({snapshot,tableNames = [],proposedTableNames = [],+ combinedBaseRead = false,+ readConcurrency = 1,request,nowMs = () => Date.now(),nowIso = () => new Date().toISOString(),@@ -1653,21 +2348,53 @@ async function expandSnapshot({const proposedNames = uniqueLogicalNames(proposedTableNames);const exactCheckNames = uniqueLogicalNames([...requestedNames, ...proposedNames]);const baseRawInventory = snapshot.inventory.map(inventoryEntityToRaw);+ const previouslyRefreshedKeys = new Set(+ (snapshot.liveRefreshedExactNames || []).map((name) => name.toLowerCase()),+ );+ const namesToRefresh = snapshot.inventorySource === 'cache'+ ? exactCheckNames.filter((name) => !previouslyRefreshedKeys.has(name.toLowerCase()))+ : [];const exactResolution = await resolveExactNameEntities(request,baseRawInventory,exactCheckNames,+ { refreshRequestedNames: namesToRefresh },);const inventoryCompletedAt = nowMs();const rawInventory = exactResolution.entities;const inventoryByName = new Map(rawInventory.map((entity) => [logicalNameOf(entity).toLowerCase(), entity]),);- const existingDetailed = new Map(+ const requestedNameKeys = new Set(requestedNames.map((name) => name.toLowerCase()));+ const refreshedUnavailableKeys = new Set(+ snapshot.inventorySource === 'cache'+ ? namesToRefresh+ .map((name) => name.toLowerCase())+ .filter((name) => !inventoryByName.has(name))+ : [],+ );+ const refreshedRequestedNameKeys = new Set(+ namesToRefresh+ .map((name) => name.toLowerCase())+ .filter((name) => requestedNameKeys.has(name)),+ );+ const invalidatedDetailKeys = new Set([+ ...refreshedUnavailableKeys,+ ...refreshedRequestedNameKeys,+ ]);+ const originalTables = new Map(snapshot.tables.map((table) => [table.logicalName.toLowerCase(), table]),);+ const existingTables = new Map(+ snapshot.tables+ .filter((table) => !invalidatedDetailKeys.has(table.logicalName.toLowerCase()))+ .map((table) => [table.logicalName.toLowerCase(), table]),+ );const entitiesToLoad = requestedNames- .filter((logicalName) => !existingDetailed.has(logicalName.toLowerCase()))+ .filter((logicalName) => {+ const existing = existingTables.get(logicalName.toLowerCase());+ return !existing || existing.detailLevel === 'core';+ }).map((logicalName) => inventoryByName.get(logicalName.toLowerCase())).filter(Boolean).map((entity) => (entity.logicalName ? inventoryEntityToRaw(entity) : entity));@@ -1678,15 +2405,10 @@ async function expandSnapshot({...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',@@ -1704,35 +2426,104 @@ async function expandSnapshot({elapsedMs: selectionCompletedAt - totalStartedAt,});- const loadedTables = [];- for (const entity of entitiesToLoad) loadedTables.push(await loadDetailedEntity(request, entity));+ const expandedEvidence = new Map(+ (snapshot.selectedCandidateEvidence || [])+ .filter((item) => !refreshedUnavailableKeys.has(item.logicalName.toLowerCase()))+ .map((item) => [+ item.logicalName.toLowerCase(),+ {+ logicalName: item.logicalName,+ reasons: new Set(item.reasons),+ detailLevel: item.detailLevel || null,+ },+ ]),+ );+ const adaptiveRead = adaptiveReadRequest(request, readConcurrency);+ let loadOutcomes;+ try {+ loadOutcomes = await mapWithConcurrency(+ entitiesToLoad,+ parseReadConcurrency(readConcurrency),+ async (entity) => {+ try {+ return {+ table: await loadDetailedEntity(+ adaptiveRead.request,+ entity,+ { combinedBaseRead },+ ),+ failure: null,+ };+ } catch (error) {+ if (isPlanningAccessFailure(error)) throw error;+ const priorEvidence = expandedEvidence.get(entity.LogicalName.toLowerCase());+ return {+ table: null,+ failure: normalizeDetailLoadFailure(+ entity,+ [...(priorEvidence?.reasons || []), 'explicit-expansion'],+ error,+ ),+ };+ }+ },+ { currentConcurrency: adaptiveRead.currentConcurrency },+ );+ } finally {+ adaptiveRead.dispose();+ }+ const loadedTables = loadOutcomes+ .filter((outcome) => outcome.table)+ .map((outcome) => outcome.table);+ const newDetailLoadFailures = loadOutcomes+ .filter((outcome) => outcome.failure)+ .map((outcome) => outcome.failure);+ const newlyLoadedTables = loadedTables+ .filter((table) => !originalTables.has(table.logicalName.toLowerCase()))+ .map((table) => table.logicalName);+ const upgradedTables = loadedTables+ .filter((table) => originalTables.get(table.logicalName.toLowerCase())?.detailLevel === 'core')+ .map((table) => table.logicalName);+ const reloadedTables = loadedTables+ .filter((table) => {+ const original = originalTables.get(table.logicalName.toLowerCase());+ return original && (original.detailLevel || 'full') === 'full';+ })+ .map((table) => table.logicalName);const detailCompletedAt = nowMs();onProgress({milestoneId: 'expansion-loaded',attemptedDetailedCandidates: entitiesToLoad.length,loadedDetailedCandidates: loadedTables.length,- failedDetailedCandidates: 0,- newlyLoadedTables: loadedTables.length,+ failedDetailedCandidates: newDetailLoadFailures.length,+ newlyLoadedTables: newlyLoadedTables.length,+ upgradedTables: upgradedTables.length,+ reloadedTables: reloadedTables.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) },- ]));+ const mergedTableMap = new Map(+ snapshot.tables+ .filter((table) => !invalidatedDetailKeys.has(table.logicalName.toLowerCase()))+ .map((table) => [table.logicalName.toLowerCase(), table]),+ );+ for (const table of loadedTables) mergedTableMap.set(table.logicalName.toLowerCase(), table);+ const mergedTables = [...mergedTableMap.values()]+ .sort((left, right) => left.logicalName.localeCompare(right.logicalName));+ const detailedNames = new Set(mergedTables+ .filter((table) => (table.detailLevel || 'full') === 'full')+ .map((table) => table.logicalName.toLowerCase()));for (const logicalName of requestedNames) {- if (!detailedNames.has(logicalName.toLowerCase())) continue;+ if (!inventoryByName.has(logicalName.toLowerCase())) continue;const key = logicalName.toLowerCase();const evidence = expandedEvidence.get(key) || {logicalName,reasons: new Set(),+ detailLevel: 'full',};evidence.reasons.add('explicit-expansion');+ evidence.detailLevel = 'full';expandedEvidence.set(key, evidence);}const loadedRequestedTables = requestedNames@@ -1741,28 +2532,132 @@ async function expandSnapshot({|| snapshot.exactNameResolution?.requestedTables|| [];const allExactNames = uniqueLogicalNames([...previousExactNames, ...requestedNames]);- const allExactAvailable = new Map(- rawInventory.map((entity) => [logicalNameOf(entity).toLowerCase(), logicalNameOf(entity)]),+ const allExactAvailable = new Set(+ rawInventory.map((entity) => logicalNameOf(entity).toLowerCase()),);const allDetailedNames = new Map(- [...snapshot.tables, ...loadedTables]+ mergedTables+ .filter((table) => (table.detailLevel || 'full') === 'full').map((table) => [table.logicalName.toLowerCase(), table.logicalName]),);const remainingDetailLoadFailures = (snapshot.detailLoadFailures || []).filter(- (failure) => !allDetailedNames.has(failure.logicalName.toLowerCase()),- );+ (failure) => (+ !allDetailedNames.has(failure.logicalName.toLowerCase())+ && !refreshedUnavailableKeys.has(failure.logicalName.toLowerCase())+ && !requestedNameKeys.has(failure.logicalName.toLowerCase())+ ),+ ).concat(newDetailLoadFailures);const expandedSelectedEvidence = [...expandedEvidence.values()].sort((left, right) => left.logicalName.localeCompare(right.logicalName)).map((item) => ({logicalName: item.logicalName,reasons: [...item.reasons].sort(),+ detailLevel: item.detailLevel || null,}));+ const snapshotConcepts = snapshot.inputs?.concepts || [];+ const refreshedCandidateRanking = (+ snapshotConcepts.length > 0+ ? rankCandidatesByConcept(rawInventory, snapshotConcepts)+ : snapshot.candidateRanking || []+ ).map((ranking) => ({+ ...ranking,+ candidates: ranking.candidates+ .filter((candidate) => !refreshedUnavailableKeys.has(candidate.logicalName.toLowerCase()))+ .map((candidate) => ({+ ...candidate,+ detailed: false,+ detailStatus: expandedEvidence.has(candidate.logicalName.toLowerCase())+ ? 'pending'+ : 'inventory-only',+ detailFailure: null,+ selectionEvidence: expandedEvidence.has(candidate.logicalName.toLowerCase())+ ? [...expandedEvidence.get(candidate.logicalName.toLowerCase()).reasons].sort()+ : [],+ })),+ }));const detailOutcomes = applyDetailLoadOutcomes(- snapshot.candidateRanking,+ refreshedCandidateRanking,expandedSelectedEvidence,- [...snapshot.tables, ...loadedTables],+ mergedTables,remainingDetailLoadFailures,);+ const baseInventoryKeys = new Set(+ baseRawInventory.map((entity) => logicalNameOf(entity).toLowerCase()),+ );+ const previousDiscoveryTables = Array.isArray(snapshot.exactNameDiscoveryTables)+ ? snapshot.exactNameDiscoveryTables+ : [];+ const exactDiscoveryNames = new Map(+ previousDiscoveryTables+ .filter((name) => !refreshedUnavailableKeys.has(name.toLowerCase()))+ .map((name) => [name.toLowerCase(), name]),+ );+ for (const name of exactResolution.discoveredTables) {+ const key = name.toLowerCase();+ if (exactDiscoveryNames.has(key) || !baseInventoryKeys.has(key)) {+ exactDiscoveryNames.set(key, name);+ }+ }+ const discoveredExactTables = [...exactDiscoveryNames.values()]+ .sort((left, right) => left.localeCompare(right));+ const allExactNameKeys = new Set(allExactNames.map((name) => name.toLowerCase()));+ const allProposedNameKeys = new Set(allProposedNames.map((name) => name.toLowerCase()));+ const selectedEvidenceReasons = expandedSelectedEvidence.flatMap((item) => item.reasons);+ const selectedEvidenceKeys = new Set(+ expandedSelectedEvidence.map((item) => item.logicalName.toLowerCase()),+ );+ const exactCoveredConcepts = new Set(+ selectedEvidenceReasons+ .filter((reason) => reason.startsWith('concept:') && reason.endsWith(':exact-covered'))+ .map((reason) => reason.slice('concept:'.length, -':exact-covered'.length)),+ );+ const refreshedSelectionSummary = {+ requiredCandidates: expandedSelectedEvidence.filter((item) => (+ item.reasons.includes('explicit-table')+ || item.reasons.includes('explicit-expansion')+ )).length,+ advisoryCandidates: expandedSelectedEvidence.filter((item) => (+ !item.reasons.includes('explicit-table')+ && !item.reasons.includes('explicit-expansion')+ )).length,+ exactCoveredConcepts: exactCoveredConcepts.size,+ unresolvedConcepts: refreshedCandidateRanking.filter((ranking) => (+ ranking.discoverTable !== false+ && (ranking.conceptKind == null || ranking.conceptKind === 'entity')+ && ranking.candidates.length > 0+ && !exactCoveredConcepts.has(ranking.concept)+ )).length,+ advisoryLimit: snapshot.detailLoadSummary?.advisoryLimit+ || MAX_ADVISORY_DETAIL_TABLES,+ primaryCandidates: expandedSelectedEvidence.filter((item) => (+ item.reasons.some((reason) => reason.endsWith(':primary'))+ )).length,+ ambiguityCandidates: expandedSelectedEvidence.filter((item) => (+ item.reasons.some((reason) => reason.endsWith(':ambiguous-alternative'))+ && !item.reasons.some((reason) => reason.endsWith(':primary'))+ )).length,+ strongCollisionCandidates: expandedSelectedEvidence.filter((item) => (+ item.reasons.includes('proposed-collision:strong-concept-phrase')+ )).length,+ coreCandidates: expandedSelectedEvidence.filter(+ (item) => item.detailLevel === 'core',+ ).length,+ fullCandidates: expandedSelectedEvidence.filter(+ (item) => (item.detailLevel || 'full') === 'full',+ ).length,+ deferredCandidates: new Set(+ refreshedCandidateRanking+ .filter((ranking) => (+ ranking.discoverTable !== false+ && (ranking.conceptKind == null || ranking.conceptKind === 'entity')+ ))+ .flatMap((ranking) => ranking.candidates.slice(+ 0,+ MAX_TABLES_PER_CONCEPT,+ ).map((candidate) => candidate.logicalName.toLowerCase()))+ .filter((name) => !selectedEvidenceKeys.has(name)),+ ).size,+ };return {...snapshot,@@ -1779,17 +2674,17 @@ async function expandSnapshot({.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),+ customizableTables: rawInventory.filter(+ (entity) => (entity.IsCustomizable?.Value ?? entity.customizable) === true,+ ).length,+ exactNameTables: discoveredExactTables.length,+ requiredExactNameTables: discoveredExactTables+ .filter((name) => allExactNameKeys.has(name.toLowerCase())).length,+ proposedCollisionTables: discoveredExactTables+ .filter((name) => (+ allProposedNameKeys.has(name.toLowerCase())+ && !allExactNameKeys.has(name.toLowerCase())+ )).length,totalTables: rawInventory.length,},candidateRanking: detailOutcomes.candidateRanking.map((ranking) => ({@@ -1805,29 +2700,31 @@ async function expandSnapshot({}),})),selectedCandidateEvidence: detailOutcomes.selectedCandidateEvidence,- tables: [...snapshot.tables, ...loadedTables]- .sort((left, right) => left.logicalName.localeCompare(right.logicalName)),+ tables: mergedTables,detailLoadFailures: remainingDetailLoadFailures,detailLoadSummary: {- attemptedCandidates: snapshot.tables.length- + loadedTables.length- + remainingDetailLoadFailures.length,- loadedCandidates: snapshot.tables.length + loadedTables.length,+ attemptedCandidates: mergedTables.length + remainingDetailLoadFailures.length,+ loadedCandidates: mergedTables.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,+ ...refreshedSelectionSummary,+ ...(combinedBaseRead ? { baseReadMode: 'combined' } : {}),+ ...(parseReadConcurrency(readConcurrency) !== 1+ || adaptiveRead.currentConcurrency() !== 1 ? {+ readConcurrency: parseReadConcurrency(readConcurrency),+ finalReadConcurrency: adaptiveRead.currentConcurrency(),+ } : {}),},proposedNameChecks,missingProposedTables: proposedNameChecks.missing,+ exactNameDiscoveryTables: discoveredExactTables,+ liveRefreshedExactNames: uniqueLogicalNames([+ ...(snapshot.liveRefreshedExactNames || []),+ ...namesToRefresh,+ ]),exactNameResolution: {requestedTables: allExactNames,loadedTables: allExactNames- .filter((logicalName) => allDetailedNames.has(logicalName.toLowerCase()))- .map((logicalName) => allDetailedNames.get(logicalName.toLowerCase())),+ .filter((logicalName) => allExactAvailable.has(logicalName.toLowerCase())),unavailableTables: allExactNames.filter((logicalName) => !allExactAvailable.has(logicalName.toLowerCase()),),@@ -1843,44 +2740,76 @@ async function expandSnapshot({inventoryReused: true,requestedTables: requestedNames,loadedTables: loadedRequestedTables,- newlyLoadedTables: loadedTables.map((table) => table.logicalName),- unavailableTables: unavailableRequestedTables,+ newlyLoadedTables,+ upgradedTables,+ reloadedTables,+ unavailableTables: requestedNames.filter(+ (logicalName) => !detailedNames.has(logicalName.toLowerCase()),+ ),attemptedDetailedCandidates: entitiesToLoad.length,loadedDetailedCandidates: loadedTables.length,- failedDetailedCandidates: 0,+ failedDetailedCandidates: newDetailLoadFailures.length,},};}-function createCliRequest(args, createExecutor = createDataverseRequestExecutor) {+function createCliRequest(+ args,+ createExecutor = createDataverseRequestExecutor,+ executorOptions = {},+) {return createExecutor({environmentUrl: args['env-url'],tenantId: args['tenant-id'],solution: args.solution || null,+ ...executorOptions,});}-async function main() {- const args = parseArgs(process.argv);+async function main(argv = process.argv, { createExecutor = createDataverseRequestExecutor } = {}) {+ const args = parseArgs(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',+ + '[--concepts <domain-term,...> | --concepts-file <json>] [--solution <unique-name>] '+ + '[--base-snapshot <existing-json>] [--reconcile-exact] [--progressive-detail] '+ + '[--combined-base-read] '+ + '[--read-concurrency <1-8>] [--inventory-cache <json>] '+ + '[--inventory-cache-ttl-ms <number>]\n',);process.exit(1);}const progress = (event) => {process.stderr.write(`DATAVERSE_SNAPSHOT_PROGRESS ${JSON.stringify(event)}\n`);};- const request = createCliRequest(args);+ const request = createCliRequest(args, createExecutor);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');}+ const readConcurrency = parseReadConcurrency(args['read-concurrency']);+ const inventoryCachePath = args['inventory-cache']+ ? path.resolve(args['inventory-cache'])+ : null;+ const inventoryCacheTtlMs = args['inventory-cache-ttl-ms'] === undefined+ ? DEFAULT_TTL_MS+ : Number(args['inventory-cache-ttl-ms']);+ if (!Number.isFinite(inventoryCacheTtlMs) || inventoryCacheTtlMs <= 0) {+ throw new Error('--inventory-cache-ttl-ms must be a positive number');+ }+ const cacheContext = {+ environmentUrl: args['env-url'],+ tenantId: args['tenant-id'],+ solution: args.solution || 'Default',+ apiVersion: '9.2',+ inventorySchemaVersion: 3,+ };+ const cacheRead = inventoryCachePath && !baseSnapshot && !args['reconcile-exact']+ ? readInventoryCache(inventoryCachePath, cacheContext, { ttlMs: inventoryCacheTtlMs })+ : { hit: false, reason: 'not-applicable', inventory: null };if (baseSnapshot) {const validation = validateSnapshot(baseSnapshot, {environmentUrl: args['env-url'],@@ -1890,12 +2819,17 @@ async function main() {throw new Error(`Base snapshot mismatch: ${validation.errors.join('; ')}`);}}+ // Start cache age before discovery so pagination and slow detail loads cannot+ // give the oldest inventory observations a new TTL when the snapshot is written.+ const inventoryReadStartedAtMs = Date.now();const snapshot = args['reconcile-exact']? await createReconciliationSnapshot({environmentUrl: args['env-url'],tenantId: args['tenant-id'],tableNames: parseList(args.tables),proposedTableNames: parseList(args['proposed-tables']),+ combinedBaseRead: Boolean(args['combined-base-read']),+ readConcurrency,request,onProgress: progress,})@@ -1904,6 +2838,8 @@ async function main() {snapshot: baseSnapshot,tableNames: parseList(args.tables),proposedTableNames: parseList(args['proposed-tables']),+ combinedBaseRead: Boolean(args['combined-base-read']),+ readConcurrency,request,onProgress: progress,})@@ -1912,12 +2848,29 @@ async function main() {tenantId: args['tenant-id'],tableNames: parseList(args.tables),proposedTableNames: parseList(args['proposed-tables']),- concepts: parseList(args.concepts),+ concepts: parseConcepts(args),+ progressiveDetail: Boolean(args['progressive-detail']),+ combinedBaseRead: Boolean(args['combined-base-read']),+ readConcurrency,+ inventory: cacheRead.inventory,+ inventorySource: inventoryCachePath ? cacheRead.hit ? 'cache' : 'live' : null,+ inventoryCacheAgeMs: cacheRead.ageMs ?? null,request,onProgress: progress,});const output = path.resolve(args.output);atomicWriteJson(output, snapshot);+ if (inventoryCachePath && !baseSnapshot && !args['reconcile-exact'] && !cacheRead.hit) {+ writeInventoryCache(+ inventoryCachePath,+ cacheContext,+ cacheablePlanningInventory(snapshot),+ {+ nowMs: () => inventoryReadStartedAtMs,+ nowIso: () => new Date(inventoryReadStartedAtMs).toISOString(),+ },+ );+ }console.log(JSON.stringify({status: 'DONE',output,@@ -1933,12 +2886,28 @@ async function main() {exactCoveredConcepts: snapshot.detailLoadSummary?.exactCoveredConcepts || 0,advisoryLimit: snapshot.detailLoadSummary?.advisoryLimit|| MAX_ADVISORY_DETAIL_TABLES,+ primary: snapshot.detailLoadSummary?.primaryCandidates || 0,+ ambiguity: snapshot.detailLoadSummary?.ambiguityCandidates || 0,+ strongCollisions: snapshot.detailLoadSummary?.strongCollisionCandidates || 0,+ deferred: snapshot.detailLoadSummary?.deferredCandidates || 0,+ core: snapshot.detailLoadSummary?.coreCandidates || 0,+ full: snapshot.detailLoadSummary?.fullCandidates || 0,},proposedCollisions: snapshot.proposedNameChecks.collisions.length,proposedMissing: snapshot.proposedNameChecks.missing.length,exactNameResolution: snapshot.exactNameResolution,expansion: snapshot.expansion || null,timings: snapshot.timings,+ readConcurrency: snapshot.detailLoadSummary?.readConcurrency || 1,+ finalReadConcurrency: snapshot.detailLoadSummary?.finalReadConcurrency || 1,+ baseReadMode: snapshot.detailLoadSummary?.baseReadMode || 'separate',+ inventorySource: snapshot.inventorySource || 'live',+ inventoryCache: inventoryCachePath ? {+ path: inventoryCachePath,+ hit: cacheRead.hit,+ reason: cacheRead.reason,+ ageMs: cacheRead.ageMs ?? null,+ } : null,}, null, 2));}@@ -1951,9 +2920,11 @@ if (require.main === module) {module.exports = {analyzeProposedNames,+ adaptiveReadRequest,atomicWriteFile,atomicWriteJson,canonicalAttributeType,+ cacheablePlanningInventory,compact,choiceMetadataType,conceptDescriptor,@@ -1965,19 +2936,26 @@ module.exports = {isVersionedName,labelText,loadDetailedEntity,+ main,+ requestBaseMetadata,+ requestCombinedBaseMetadata,normalizeNextLink,normalizeIntegerMetadata,normalizedTokens,odataString,parseArgs,+ parseConcepts,parseList,+ parseReadConcurrency,publisherPrefix,rankCandidatesByConcept,relationshipCount,resolveExactNameEntities,requestCollection,+ mapWithConcurrency,selectDetailedCandidates,selectDetailedEntities,+ selectStrongProposedCollisions,singularizeToken,validateSnapshot,};diff --git a/plugins/mobile-apps/scripts/dataverse-inventory-cache.js b/plugins/mobile-apps/scripts/dataverse-inventory-cache.jsnew file mode 100644index 000000000..d9f2473da--- /dev/null+++ b/plugins/mobile-apps/scripts/dataverse-inventory-cache.js@@ -0,0 +1,180 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');++const CACHE_SCHEMA_VERSION = 1;+const DATAVERSE_API_VERSION = '9.2';+const DEFAULT_TTL_MS = 5 * 60 * 1000;++function atomicWriteJson(file, value, fileSystem = fs) {+ const resolved = path.resolve(file);+ fileSystem.mkdirSync(path.dirname(resolved), { recursive: true });+ const temporary = `${resolved}.tmp-${process.pid}-${Date.now()}`;+ try {+ fileSystem.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');+ fileSystem.renameSync(temporary, resolved);+ } finally {+ if (fileSystem.existsSync(temporary)) fileSystem.rmSync(temporary, { force: true });+ }+}++function normalizeUrl(value) {+ return String(value || '').trim().replace(/\/+$/, '').toLowerCase();+}++function identity(context) {+ return {+ environmentUrl: normalizeUrl(context.environmentUrl),+ tenantId: String(context.tenantId || '').trim().toLowerCase(),+ solution: String(context.solution || 'Default').trim(),+ apiVersion: String(context.apiVersion || DATAVERSE_API_VERSION),+ inventorySchemaVersion: Number(context.inventorySchemaVersion || 3),+ };+}++function sameIdentity(left, right) {+ const leftKeys = Object.keys(left).sort();+ const rightKeys = Object.keys(right).sort();+ return leftKeys.length === rightKeys.length+ && leftKeys.every((key, index) => key === rightKeys[index] && left[key] === right[key]);+}++function hasValidInventory(inventory) {+ if (!Array.isArray(inventory)) return false;+ const names = new Set();+ const identifier = /^[A-Za-z][A-Za-z0-9_]*$/;+ return inventory.every((item) => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) return false;+ if (['logicalName', 'schemaName', 'entitySetName', 'primaryIdAttribute'].some(+ (field) => typeof item[field] !== 'string' || !identifier.test(item[field]),+ )) return false;+ if (['displayName', 'displayCollectionName', 'description'].some(+ (field) => typeof item[field] !== 'string',+ )) return false;+ if (item.customizable !== true || typeof item.customEntity !== 'boolean'+ || typeof item.managed !== 'boolean') return false;+ if (item.ownershipType !== null && typeof item.ownershipType !== 'string') return false;+ if (item.primaryNameAttribute != null && (typeof item.primaryNameAttribute !== 'string'+ || !identifier.test(item.primaryNameAttribute))) return false;+ // Normalized inventory records unavailable capability facts as null, e.g.+ // { customizable: true, canCreateAttributes: null }, never an omitted flag.+ if (['hasActivities', 'hasNotes', 'isAvailableOffline', 'changeTrackingEnabled',+ 'canCreateAttributes', 'canBePrimaryEntityInRelationship',+ 'canBeRelatedEntityInRelationship', 'canBeInManyToMany'].some(+ (field) => item[field] !== null && typeof item[field] !== 'boolean',+ )) return false;+ const name = item.logicalName.toLowerCase();+ if (names.has(name)) return false;+ names.add(name);+ return true;+ });+}++function readInventoryCache(file, context, {+ ttlMs = DEFAULT_TTL_MS,+ nowMs = () => Date.now(),+ fileSystem = fs,+} = {}) {+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error('inventory cache TTL must be positive');+ const resolved = path.resolve(file);+ if (!fileSystem.existsSync(resolved)) return { hit: false, reason: 'missing', inventory: null };+ let cache;+ try {+ cache = JSON.parse(fileSystem.readFileSync(resolved, 'utf8'));+ } catch {+ return { hit: false, reason: 'invalid-json', inventory: null };+ }+ if (!cache || typeof cache !== 'object' || Array.isArray(cache)+ || cache.schemaVersion !== CACHE_SCHEMA_VERSION || !hasValidInventory(cache.inventory)) {+ return { hit: false, reason: 'invalid-shape', inventory: null };+ }+ if (!sameIdentity(cache.identity || {}, identity(context))) {+ return { hit: false, reason: 'identity-mismatch', inventory: null };+ }+ const ageMs = nowMs() - Number(cache.cachedAtMs);+ if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > ttlMs) {+ return { hit: false, reason: 'expired', inventory: null, ageMs };+ }+ return {+ hit: true,+ reason: 'fresh',+ inventory: cache.inventory,+ ageMs,+ cachedAt: cache.cachedAt,+ };+}++function writeInventoryCache(file, context, inventory, {+ nowMs = () => Date.now(),+ nowIso = () => new Date().toISOString(),+ fileSystem = fs,+} = {}) {+ if (!Array.isArray(inventory)) throw new Error('inventory cache requires an array');+ const cache = {+ schemaVersion: CACHE_SCHEMA_VERSION,+ identity: identity(context),+ cachedAt: nowIso(),+ cachedAtMs: nowMs(),+ inventory,+ };+ atomicWriteJson(file, cache, fileSystem);+ return cache;+}++function invalidateInventoryCache(file, fileSystem = fs) {+ const resolved = path.resolve(file);+ fileSystem.rmSync(resolved, { force: true });+ return !fileSystem.existsSync(resolved);+}++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ if (argv[index] === '--file') args.file = argv[++index];+ else if (argv[index] === '--invalidate') args.invalidate = true;+ }+ return args;+}++function main(argv = process.argv, {+ fileSystem = fs,+ stdout = process.stdout,+ stderr = process.stderr,+} = {}) {+ const args = parseArgs(argv);+ if (!args.file || !args.invalidate) {+ stderr.write(+ 'Usage: node dataverse-inventory-cache.js --file <json> --invalidate\n',+ );+ return 2;+ }+ try {+ if (!invalidateInventoryCache(args.file, fileSystem)) {+ stderr.write(+ `dataverse-inventory-cache: failed to invalidate ${path.resolve(args.file)}\n`,+ );+ return 2;+ }+ stdout.write(`${JSON.stringify({ status: 'invalidated', file: path.resolve(args.file) })}\n`);+ return 0;+ } catch (error) {+ stderr.write(`dataverse-inventory-cache: ${error.message}\n`);+ return 2;+ }+}++if (require.main === module) process.exitCode = main();++module.exports = {+ CACHE_SCHEMA_VERSION,+ DATAVERSE_API_VERSION,+ DEFAULT_TTL_MS,+ identity,+ invalidateInventoryCache,+ main,+ readInventoryCache,+ sameIdentity,+ writeInventoryCache,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/dataverse-request.js b/plugins/mobile-apps/scripts/dataverse-request.jsindex ebec88eac..4692b023c 100644--- a/plugins/mobile-apps/scripts/dataverse-request.js+++ b/plugins/mobile-apps/scripts/dataverse-request.js@@ -194,25 +194,51 @@ function createDataverseRequestExecutor({solution = null,getToken = getAuthToken,sendRequest = doRequest,+ sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),}) {const envUrl = String(environmentUrl || '').replace(/\/+$/, '');if (!envUrl) throw new Error('environmentUrl is required');let token = null;let tokenPromise = null;+ let refreshPromise = null;+ const rateLimitListeners = new Set();async function ensureToken() {if (token) return token;- if (!tokenPromise) tokenPromise = Promise.resolve(getToken(envUrl, tenantId));- token = await tokenPromise;- tokenPromise = null;+ if (!tokenPromise) {+ tokenPromise = Promise.resolve(getToken(envUrl, tenantId));+ }+ const pendingToken = tokenPromise;+ try {+ token = await pendingToken;+ } finally {+ if (tokenPromise === pendingToken) 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();+ async function refreshToken(staleToken) {+ if (token && staleToken && token !== staleToken) {+ return token;+ }+ if (!refreshPromise) {+ refreshPromise = Promise.resolve(getToken(envUrl, tenantId))+ .then((refreshed) => {+ if (refreshed) token = refreshed;+ return refreshed;+ })+ .finally(() => {+ refreshPromise = null;+ });+ }+ return refreshPromise;+ }++ const execute = async (method, apiPath, body = null, includeHeaders = false) => {+ const currentToken = await ensureToken();let bodyString = null;if (body !== null && body !== undefined) {bodyString = typeof body === 'string' ? body : JSON.stringify(body);@@ -222,14 +248,25 @@ function createDataverseRequestExecutor({String(method || '').toUpperCase(),apiPath,bodyString,- requestToken,+ currentToken,includeHeaders,solution,tenantId,- getToken,+ async (_environmentUrl, _tenantId, staleToken) => refreshToken(staleToken),sendRequest,+ {+ sleep,+ onRateLimited: (event) => {+ for (const listener of rateLimitListeners) {+ try {+ listener(event);+ } catch {+ // Backpressure observers must not change request behavior.+ }+ }+ },+ },);- token = executed.token;return {status: executed.status,data: executed.data,@@ -238,6 +275,12 @@ function createDataverseRequestExecutor({rateLimited: executed.rateLimited,};};+ execute.onRateLimited = (listener) => {+ if (typeof listener !== 'function') throw new Error('rate-limit listener must be a function');+ rateLimitListeners.add(listener);+ return () => rateLimitListeners.delete(listener);+ };+ return execute;}async function main() {@@ -991,6 +1034,10 @@ async function runOneMetadataOperation(tenantId,getToken = getAuthToken,sendRequest = doRequest,+ {+ sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),+ onRateLimited = () => {},+ } = {},) {let token = initialToken;let rateLimited = false;@@ -1010,12 +1057,14 @@ async function runOneMetadataOperation(uncertain: true,};}- if (attempt < maxRetries) continue;+ if (attempt < maxRetries) {+ continue;+ }return { status: 0, error: res.error, token, rateLimited };}if (res.statusCode === 401 && attempt < maxRetries) {- const refreshed = await getToken(envUrl, tenantId);+ const refreshed = await getToken(envUrl, tenantId, token);if (!refreshed) {return { status: 401, error: 'Token refresh failed', token, rateLimited };}@@ -1025,13 +1074,14 @@ async function runOneMetadataOperation(if (res.statusCode === 429 && attempt < maxRetries) {const delayMs = retryAfterDelayMs(res.headers?.['retry-after'], 30000);+ if (!rateLimited) onRateLimited({ delayMs, attempt: attempt + 1 });rateLimited = true;- await new Promise((resolve) => setTimeout(resolve, delayMs));+ await sleep(delayMs);continue;}if ([500, 502, 503].includes(res.statusCode) && attempt < maxRetries) {- await new Promise((resolve) => setTimeout(resolve, 5000));+ await sleep(5000);continue;}diff --git a/plugins/mobile-apps/scripts/lib/environment-resolution.js b/plugins/mobile-apps/scripts/lib/environment-resolution.jsindex fbfb093a2..93b8a2635 100644--- a/plugins/mobile-apps/scripts/lib/environment-resolution.js+++ b/plugins/mobile-apps/scripts/lib/environment-resolution.js@@ -13,6 +13,44 @@ const CACHE_FILE = '.resolved-environment.json';const AUTH_CONFIG_FILE = 'auth.config.json';const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+function redactDiagnostic(value) {+ return String(value || '')+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')+ .replace(/([?&](?:token|access_token|client_secret|code)=)[^&\s]+/gi, '$1[redacted]')+ .replace(/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/g, '[redacted-jwt]')+ .slice(0, 240);+}++function describeResponseShape(data) {+ if (data === null) return 'null body';+ if (data === undefined) return 'no body';+ if (Array.isArray(data)) return `array(${data.length})`;+ if (typeof data === 'string') return data.length ? `text(${data.length})` : 'empty text';+ if (typeof data === 'object') {+ const keys = Object.keys(data).sort();+ return keys.length > 0+ ? `object keys [${keys.slice(0, 8).join(', ')}]`+ : 'empty object';+ }+ return typeof data;+}++function formatRequestFailure(operation, response) {+ const status = response && response.statusCode;+ const parts = [+ status ? `HTTP ${status}` : 'request failed',+ describeResponseShape(response && response.data),+ ];+ const code = response && response.data && typeof response.data === 'object'+ ? response.data.code || (response.data.error && response.data.error.code)+ : null;+ if (code) parts.push(`code ${redactDiagnostic(code)}`);+ if (!status && response && response.error) {+ parts.push(redactDiagnostic(response.error));+ }+ return `${operation}: ${parts.join('; ')}`;+}+function normalizeUrl(value) {return value.replace(/\/+$/, '');}@@ -75,13 +113,14 @@ function toEnvironmentResult(value, source) {};}-function shouldWriteCache(result, projectRoot) {+function shouldWriteCache(result, projectRoot = process.cwd()) {return Boolean(result && result.environmentId && result.environmentUrl&& fs.existsSync(path.join(projectRoot, AUTH_CONFIG_FILE)));}-function writeCacheIfProject(result, projectRoot) {- if (!shouldWriteCache(result, projectRoot)) return;+function writeCacheIfProject(result, projectRoot, options = {}) {+ if (options.noCache) return false;+ if (!shouldWriteCache(result, projectRoot)) return false;const cachePath = path.join(projectRoot, CACHE_FILE);const cache = { ...result, cachedAt: new Date().toISOString() };fs.writeFileSync(cachePath, `${JSON.stringify(cache, null, 2)}\n`);@@ -92,6 +131,7 @@ function writeCacheIfProject(result, projectRoot) {authConfig.environment = cache;fs.writeFileSync(authPath, `${JSON.stringify(authConfig, null, 2)}\n`);}+ return true;}function getAzTenantId() {@@ -239,25 +279,29 @@ async function resolveEnvironmentId(environmentId, tenantId) {if (record) return environmentFromPowerPlatformPayload(record, environmentId);}- const apiMessage = res.data && typeof res.data === 'object'- ? [res.data.code, res.data.message, res.data.innererror && res.data.innererror.message].filter(Boolean).join(': ')- : res.error || `HTTP ${res.statusCode}`;- const recovery = /Forbidden|Unauthorized|Authorization|permission|privilege|Insufficient/i.test(apiMessage || '')- ? ' The Azure CLI account may not have permission to read this environment through the BAP admin API. Use an account with environment read access, or provide the Dataverse environment URL directly.'- : '';- throw new Error(`Could not resolve environment ID ${environmentId} through ${endpointUrl}: ${apiMessage || 'unknown error'}.${recovery}`);+ const failure = formatRequestFailure(+ `Could not resolve environment ID ${environmentId} through the Power Platform admin API`,+ res,+ );+ const recovery = [401, 403].includes(res.statusCode)+ ? ' The Azure CLI account may not have permission to read this environment. Sign in with an account that has environment read access, or provide the Dataverse environment URL directly.'+ : res.statusCode === 404+ ? ' Verify the environment ID and tenant, or provide the Dataverse environment URL directly.'+ : '';+ throw new Error(`${failure}.${recovery}`);}-async function resolveEnvironment(target, projectRoot = process.cwd(), allowLegacyCache = false) {+async function resolveEnvironment(target, projectRoot = process.cwd(), allowLegacyCache = false, options = {}) {if (!target) {const powerConfig = readJsonFile(path.join(projectRoot, 'power.config.json'));target = powerConfig?.environmentId || readCachedResolution(null, projectRoot)?.environmentId;if (typeof target !== 'string' || !GUID_RE.test(target)) return null;}const cached = readCachedResolution(target, projectRoot);- if (canUseCachedResolution(cached, target, allowLegacyCache)) {+ // Read-only planning needs identity, not a refresh solely for telemetry routing.+ if (canUseCachedResolution(cached, target, allowLegacyCache || options.noCache)) {const result = toEnvironmentResult(cached, 'cache');- writeCacheIfProject(result, projectRoot);+ writeCacheIfProject(result, projectRoot, options);return result;}@@ -305,8 +349,19 @@ async function resolveEnvironment(target, projectRoot = process.cwd(), allowLega}const result = toEnvironmentResult(resolved, resolved.source || (isUrl(target) ? 'environment-url' : 'environment-id'));- writeCacheIfProject(result, projectRoot);+ writeCacheIfProject(result, projectRoot, options);return result;}-module.exports = { cacheMatchesTarget, canUseCachedResolution, toEnvironmentResult, environmentFromPowerPlatformPayload, resolveEnvironment };\ No newline at end of file+module.exports = {+ cacheMatchesTarget,+ canUseCachedResolution,+ toEnvironmentResult,+ environmentFromPowerPlatformPayload,+ describeResponseShape,+ formatRequestFailure,+ redactDiagnostic,+ resolveEnvironment,+ shouldWriteCache,+ writeCacheIfProject,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/render-dataverse-architect-evidence.js b/plugins/mobile-apps/scripts/render-dataverse-architect-evidence.jsnew file mode 100644index 000000000..438133623--- /dev/null+++ b/plugins/mobile-apps/scripts/render-dataverse-architect-evidence.js@@ -0,0 +1,228 @@+#!/usr/bin/env node+'use strict';++const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');+const {+ atomicWriteJson,+ validateSnapshot,+} = require('./create-dataverse-snapshot');++function sha256(value) {+ return crypto.createHash('sha256').update(value).digest('hex');+}++function stableJson(value) {+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;+ if (value && typeof value === 'object') {+ return `{${Object.keys(value).sort().map(+ (key) => `${JSON.stringify(key)}:${stableJson(value[key])}`,+ ).join(',')}}`;+ }+ return JSON.stringify(value);+}++function clone(value) {+ if (Array.isArray(value)) return value.map(clone);+ if (!value || typeof value !== 'object') return value;+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, clone(child)]));+}++function architectCandidate(candidate) {+ return {+ logicalName: candidate.logicalName,+ displayName: candidate.displayName,+ rank: candidate.rank,+ score: candidate.score,+ matchClass: candidate.matchClass || 'legacy',+ publisherFamily: candidate.publisherFamily,+ versioned: candidate.versioned,+ detailStatus: candidate.detailStatus || (candidate.detailed ? 'loaded' : 'inventory-only'),+ detailLevel: candidate.detailLevel || null,+ selectionEvidence: candidate.selectionEvidence || [],+ reasons: candidate.reasons || [],+ };+}++function buildArchitectEvidence(snapshot, sourceSnapshotSha256) {+ const validation = validateSnapshot(snapshot);+ if (!validation.valid) {+ throw new Error(`Invalid Dataverse snapshot: ${validation.errors.join('; ')}`);+ }+ if (!/^[a-f0-9]{64}$/.test(String(sourceSnapshotSha256 || ''))) {+ throw new Error('sourceSnapshotSha256 must be a SHA-256 value');+ }+ const evidence = {+ schemaVersion: 1,+ sourceSnapshotSha256,+ environment: {+ url: snapshot.environmentUrl,+ tenantId: snapshot.tenantId,+ },+ generatedAt: snapshot.generatedAt,+ concepts: snapshot.candidateRanking.map((ranking) => ({+ concept: ranking.concept,+ conceptKind: ranking.conceptKind || 'legacy',+ discoverTable: ranking.discoverTable !== false,+ skippedReason: ranking.skippedReason || null,+ preferredPublisherFamily: ranking.preferredPublisherFamily || '',+ topCandidates: (ranking.candidates || []).slice(0, 3).map(architectCandidate),+ })),+ selectedTables: snapshot.tables.map((table) => {+ const selected = clone(table);+ selected.detailLevel = table.detailLevel || 'full';+ selected.missingDetailClasses = clone(table.missingDetailClasses || []);+ return selected;+ }),+ selectedCandidateEvidence: snapshot.selectedCandidateEvidence || [],+ proposedNameChecks: snapshot.proposedNameChecks,+ exactNameResolution: snapshot.exactNameResolution,+ detailLoadFailures: snapshot.detailLoadFailures || [],+ detailLoadSummary: snapshot.detailLoadSummary,+ timings: snapshot.timings,+ };+ return JSON.parse(JSON.stringify(evidence));+}++function validateArchitectEvidence(evidence, snapshot, sourceSnapshotSha256) {+ const errors = [];+ if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence)) {+ return { valid: false, errors: ['architect evidence must be an object'] };+ }+ if (evidence.schemaVersion !== 1) errors.push('architect evidence schemaVersion must be 1');+ if (evidence.sourceSnapshotSha256 !== sourceSnapshotSha256) {+ errors.push('architect evidence source snapshot hash is stale');+ }+ if (evidence.environment?.url !== snapshot.environmentUrl+ || evidence.environment?.tenantId !== snapshot.tenantId) {+ errors.push('architect evidence environment does not match the snapshot');+ }+ const expectedTables = new Map(snapshot.tables.map((table) => [table.logicalName, table]));+ const actualTables = Array.isArray(evidence.selectedTables) ? evidence.selectedTables : [];+ if (new Set(actualTables.map((table) => table.logicalName)).size !== actualTables.length) {+ errors.push('architect evidence selected tables must be unique');+ }+ if (actualTables.length !== expectedTables.size) {+ errors.push('architect evidence selected table count does not match the snapshot');+ }+ for (const table of actualTables) {+ const expected = expectedTables.get(table.logicalName);+ if (!expected) {+ errors.push(`architect evidence contains unknown table ${table.logicalName}`);+ continue;+ }+ const normalized = { ...table };+ if (!Object.prototype.hasOwnProperty.call(expected, 'detailLevel')) {+ delete normalized.detailLevel;+ }+ if (!Object.prototype.hasOwnProperty.call(expected, 'missingDetailClasses')) {+ delete normalized.missingDetailClasses;+ }+ if (stableJson(normalized) !== stableJson(expected)) {+ errors.push(`architect evidence table ${table.logicalName} differs from the snapshot`);+ }+ }+ const expectedConcepts = snapshot.candidateRanking || [];+ if (!Array.isArray(evidence.concepts) || evidence.concepts.length !== expectedConcepts.length) {+ errors.push('architect evidence concept count does not match the snapshot');+ } else {+ for (const [index, concept] of evidence.concepts.entries()) {+ if (concept.concept !== expectedConcepts[index].concept) {+ errors.push(`architect evidence concept ${index} does not match the snapshot`);+ }+ if (!Array.isArray(concept.topCandidates) || concept.topCandidates.length > 3) {+ errors.push(`architect evidence concept ${index} exceeds the top-three candidate limit`);+ }+ }+ }+ const expectedEvidence = buildArchitectEvidence(snapshot, sourceSnapshotSha256);+ if (stableJson(evidence) !== stableJson(expectedEvidence)) {+ errors.push('architect evidence differs from the deterministic snapshot projection');+ }+ return { valid: errors.length === 0, errors };+}++function loadAndValidateArchitectEvidence(snapshotFile, evidenceFile, fileSystem = fs) {+ const snapshotSource = fileSystem.readFileSync(path.resolve(snapshotFile), 'utf8');+ const snapshot = JSON.parse(snapshotSource);+ const snapshotValidation = validateSnapshot(snapshot);+ if (!snapshotValidation.valid) {+ throw new Error(`Invalid Dataverse snapshot: ${snapshotValidation.errors.join('; ')}`);+ }+ const evidence = JSON.parse(fileSystem.readFileSync(path.resolve(evidenceFile), 'utf8'));+ const sourceSnapshotSha256 = sha256(snapshotSource);+ const validation = validateArchitectEvidence(evidence, snapshot, sourceSnapshotSha256);+ if (!validation.valid) throw new Error(validation.errors.join('; '));+ return { evidence, snapshot, sourceSnapshotSha256 };+}++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ if (argv[index] === '--snapshot') args.snapshot = argv[++index];+ else if (argv[index] === '--output') args.output = argv[++index];+ else if (argv[index] === '--json') args.json = true;+ else if (argv[index] === '--validate-only') args.validateOnly = true;+ }+ return args;+}++function main(argv = process.argv) {+ const args = parseArgs(argv);+ if (!args.snapshot || !args.output) {+ process.stderr.write(+ 'Usage: node render-dataverse-architect-evidence.js '+ + '--snapshot <json> --output <json> [--validate-only] [--json]\n',+ );+ return 2;+ }+ try {+ const snapshotPath = path.resolve(args.snapshot);+ const output = path.resolve(args.output);+ if (args.validateOnly) {+ const validated = loadAndValidateArchitectEvidence(snapshotPath, output);+ const result = {+ status: 'DONE',+ output,+ sourceSnapshotSha256: validated.sourceSnapshotSha256,+ concepts: validated.evidence.concepts.length,+ selectedTables: validated.evidence.selectedTables.length,+ };+ process.stdout.write(`${args.json ? JSON.stringify(result, null, 2) : 'Dataverse architect evidence is current.'}\n`);+ return 0;+ }+ const source = fs.readFileSync(snapshotPath, 'utf8');+ const snapshot = JSON.parse(source);+ const sourceSnapshotSha256 = sha256(source);+ const evidence = buildArchitectEvidence(snapshot, sourceSnapshotSha256);+ const validation = validateArchitectEvidence(evidence, snapshot, sourceSnapshotSha256);+ if (!validation.valid) throw new Error(validation.errors.join('; '));+ atomicWriteJson(output, evidence);+ const result = {+ status: 'DONE',+ output,+ sourceSnapshotSha256,+ concepts: evidence.concepts.length,+ selectedTables: evidence.selectedTables.length,+ bytes: Buffer.byteLength(JSON.stringify(evidence)),+ };+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ return 0;+ } catch (error) {+ process.stderr.write(`render-dataverse-architect-evidence: ${error.message}\n`);+ return 2;+ }+}++if (require.main === module) process.exitCode = main();++module.exports = {+ architectCandidate,+ buildArchitectEvidence,+ loadAndValidateArchitectEvidence,+ main,+ sha256,+ stableJson,+ validateArchitectEvidence,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.js b/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.jsindex b4d61c81e..b2c1103b9 100644--- a/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.js+++ b/plugins/mobile-apps/scripts/render-dataverse-planning-evidence.js@@ -78,18 +78,19 @@ function renderPlanningEvidence(snapshot) {lines.push('',- '## Skipped advisory detail failures',+ '## Unavailable detail metadata','',- '| Logical name | Selection reasons | Status | Error |',- '|---|---|---:|---|',+ '| Logical name | Required | Selection reasons | Status | Error |',+ '|---|---:|---|---:|---|',);const detailLoadFailures = snapshot.detailLoadFailures || [];if (detailLoadFailures.length === 0) {- lines.push('| — | — | — | None |');+ lines.push('| — | — | — | — | None |');} else {for (const failure of detailLoadFailures) {lines.push(`| \`${escapeCell(failure.logicalName)}\` | `+ + `${failure.required ? 'yes' : 'no'} | `+ `${escapeCell(failure.selectionReasons.join(', '))} | `+ `${failure.status ?? 'n/a'} | ${escapeCell(failure.error)} |`,);diff --git a/plugins/mobile-apps/scripts/resolve-environment.js b/plugins/mobile-apps/scripts/resolve-environment.jsindex 5cab38f58..f35f94da3 100644--- a/plugins/mobile-apps/scripts/resolve-environment.js+++ b/plugins/mobile-apps/scripts/resolve-environment.js@@ -1,31 +1,74 @@#!/usr/bin/env node// Resolves a Power Platform environment URL or ID through Azure CLI and Dataverse APIs.-// Usage: node scripts/resolve-environment.js <environment-url-or-id>+// Usage: node scripts/resolve-environment.js <environment-url-or-id> [--no-cache] [--require-tenant]// Output: JSON with environmentUrl, environmentId, tenantId, and displayName when available.const environmentResolution = require('./lib/environment-resolution');const { readTelemetryCluster } = require('./lib/app-identity');const { flushPriorEvents } = require('./lib/mobile-telemetry-dispatcher');-async function main() {- const target = process.argv[2];- if (!target) {- process.stderr.write('Usage: node scripts/resolve-environment.js <environment-url-or-id>\nPass the environment ID from power.config.json, or pass the Dataverse environment URL directly.\n');- process.exit(1);+const USAGE = 'Usage: node scripts/resolve-environment.js <environment-url-or-id> [--no-cache] [--require-tenant]\n'+ + ' node scripts/resolve-environment.js --help\n'+ + 'Pass the environment ID from power.config.json, or pass the Dataverse environment URL directly.\n'+ + '\nOptions:\n'+ + ' --no-cache Do not persist environment/auth caches or telemetry routing, or replay telemetry.\n'+ + ' Existing identity metadata may still be read.\n'+ + ' --require-tenant Fail unless both a Dataverse environment URL and tenant ID are resolved.\n'+ + ' --help, -h Show this help without resolving an environment.\n';++function parseArgs(argv) {+ const options = { noCache: false, target: null };+ for (const argument of argv) {+ if (argument === '--no-cache') options.noCache = true;+ else if (argument === '--require-tenant') options.requireTenant = true;+ else if (argument === '--help' || argument === '-h') options.help = true;+ else if (argument.startsWith('-')) throw new Error(`Unknown option: ${argument}`);+ else if (!options.target) options.target = argument;+ else throw new Error(`Unknown argument: ${argument}`);}+ return options;+}++function writeCacheIfProject(result, options = {}) {+ return environmentResolution.writeCacheIfProject(result, process.cwd(), options);+}+async function main(argv = process.argv.slice(2)) {+ const options = parseArgs(argv);+ if (options.help) {+ process.stdout.write(USAGE);+ return;+ }+ if (!options.target) {+ process.stderr.write(USAGE);+ process.exitCode = 1;+ return;+ }const projectRoot = process.cwd();- const result = await environmentResolution.resolveEnvironment(target, projectRoot, Boolean(readTelemetryCluster(projectRoot)));- await flushPriorEvents(projectRoot, result);+ const result = await environmentResolution.resolveEnvironment(+ options.target, projectRoot, Boolean(readTelemetryCluster(projectRoot)), options,+ );+ if (options.requireTenant && ['environmentUrl', 'tenantId'].some(+ (field) => typeof result?.[field] !== 'string' || !result[field].trim(),+ )) {+ throw new Error('Could not resolve a Dataverse environment URL and tenant ID.');+ }+ // Planning must not persist cluster routing or replay telemetry before approval.+ if (!options.noCache) await flushPriorEvents(projectRoot, result);console.log(JSON.stringify(result, null, 2));}if (require.main === module) {main().catch((error) => {- process.stderr.write(`${error.message}\n`);- process.exit(1);+ process.stderr.write(`${environmentResolution.redactDiagnostic(error.message)}\n`);+ process.exitCode = 1;});}-module.exports = environmentResolution;\ No newline at end of file+module.exports = {+ ...environmentResolution,+ main,+ parseArgs,+ writeCacheIfProject,+};diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.jsindex 376222d68..0284c079b 100644--- a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js@@ -1,9 +1,13 @@'use strict';const assert = require('assert');+const { spawnSync } = require('child_process');const fs = require('fs');+const os = require('os');const path = require('path');const test = require('node:test');+const { createSnapshot } = require('../create-dataverse-snapshot');+const { loadAndValidateArchitectEvidence } = require('../render-dataverse-architect-evidence');const skillPath = path.resolve(__dirname,@@ -11,6 +15,177 @@ const skillPath = path.resolve();const skill = fs.readFileSync(skillPath, 'utf8');+function planningAttemptBlock(source) {+ const match = source.replace(/\r\n/g, '\n')+ .match(/```bash\n(SNAPSHOT_PATH=[\s\S]*?\nrun_dataverse_planning_attempt)\n```/);+ assert.ok(match, 'foreground snapshot commands must expose one recoverable attempt');+ return match[1];+}++test('foreground command extraction accepts LF and Windows CRLF checkouts', () => {+ const normalized = skill.replace(/\r\n/g, '\n');+ assert.equal(planningAttemptBlock(normalized.replace(/\n/g, '\r\n')),+ planningAttemptBlock(normalized));+});++test('foreground Dataverse planning resolves and validates environment in one read-only command', () => {+ const planningStart = skill.indexOf('### Foreground Dataverse planning');+ const planningEnd = skill.indexOf(+ 'Build `<working_dir>/.tmp/dataverse-concepts.json`',+ planningStart,+ );+ assert.notStrictEqual(planningStart, -1);+ assert.notStrictEqual(planningEnd, -1);+ const planning = skill.slice(planningStart, planningEnd);+ const commands = [...planning.matchAll(/```bash\r?\n([\s\S]*?)\r?\n```/g)];+ assert.strictEqual(commands.length, 1);+ assert.strictEqual(+ commands[0][1].trim(),+ 'node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$ACTIVE_ENV_ID" --no-cache --require-tenant',+ );+ assert.doesNotMatch(planning, /PLANNING_ENV_JSON|node -e|JSON\.parse/);+ assert.match(planning, /`environmentUrl` as `\$ACTIVE_ENV_URL`/);+ assert.match(planning, /`tenantId` as\s+`\$ACTIVE_TENANT_ID`/);+ assert.match(planning, /nonzero exit[\s\S]*do not create a snapshot or reuse stale environment values/);+});++test('approved architecture precedes typed discovery without retrying the normal planner phases', () => {+ const architectureStart = skill.indexOf('### Architecture gate');+ const publisher = skill.indexOf('Now execute the deferred Step 1.7');+ const snapshotStart = skill.indexOf('### Foreground Dataverse planning');+ const conceptsStart = skill.indexOf('Build `<working_dir>/.tmp/dataverse-concepts.json`');+ const commandsStart = skill.indexOf('SNAPSHOT_PATH="');+ assert.ok(architectureStart >= 0 && architectureStart < publisher);+ assert.ok(publisher < snapshotStart && snapshotStart < conceptsStart);+ assert.ok(conceptsStart < commandsStart);+ const architecture = skill.slice(architectureStart, publisher);+ assert.match(architecture, /Architecture phase: gate-only/);+ assert.match(architecture, /Dataverse planning snapshot: NOT SUPPLIED/);+ assert.match(architecture, /approved-architecture\.md/);+ assert.doesNotMatch(architecture, /create-dataverse-snapshot\.js|detect-publisher-prefix\.js/);+ const concepts = skill.slice(conceptsStart, commandsStart);+ assert.match(concepts, /Gate 1-approved architecture/);+ assert.match(concepts, /exclude connector-owned\s+records from Dataverse candidate selection/);+ assert.doesNotMatch(skill, /planning-timings\.js|PLANNING_TIMINGS_PATH/);+ assert.doesNotMatch(skill, /telemetry-output|PLANNING_TELEMETRY_PATH/);+});++test('inline Dataverse planning keeps compact evidence and validates before Gate 2', () => {+ const fallbackStart = skill.indexOf('#### 3.0a — Inline-gate fallback');+ const fallbackEnd = skill.indexOf('#### 3.0 — Sub-agent return-status switch');+ assert.ok(fallbackStart >= 0 && fallbackStart < fallbackEnd);+ const fallback = skill.slice(fallbackStart, fallbackEnd);+ assert.match(fallback, /Approved native capabilities:[\s\S]*Approved connectors:/);+ assert.match(fallback, /`SNAPSHOT_PATH` and `ARCHITECT_EVIDENCE_PATH` verbatim/);+ assert.match(fallback, /full snapshot is\s+validator input only; read only the compact evidence/);+ assert.doesNotMatch(fallback, /\bEVIDENCE_PATH\b/);+ assert.doesNotMatch(fallback, /timing protocol|modelArchitect|screenPlanner|--retry/);+ assert.match(fallback, /Before presenting Gate 2[\s\S]*validate-dataverse-planning-decisions\.js/);+ assert.match(fallback, /permit approval only on exit `0`/);+ assert.match(fallback, /every direct revision and the fully-inline fallback/);+ assert.match(fallback, /approve native capabilities, connectors, and data platform first/);+ assert.match(fallback, /then draft the data model from `ARCHITECT_EVIDENCE_PATH`/);+});++test('foreground planning returns failed attempts to recovery and resumes with fresh validated evidence', async (testContext) => {+ const commands = planningAttemptBlock(skill);+ const pluginRoot = path.resolve(__dirname, '../..');+ const bashPaths = process.platform === 'win32'+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)+ : [];+ const bash = bashPaths.find((entry) => /[\\/]Git[\\/]/i.test(entry)) || 'bash';+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ request: async () => ({ status: 200, data: { value: [] } }),+ });+ const stub = `+node() {+ case "$1" in+ */create-dataverse-snapshot.js)+ if [ "$FAILURE_STAGE" = snapshot ]; then+ printf 'injected snapshot failure\\n' >&2+ return 1+ fi+ "$REAL_NODE" -e 'require("node:fs").writeFileSync(process.argv[1], process.env.FIXTURE_SNAPSHOT)' "$SNAPSHOT_PATH"+ ;;+ */render-dataverse-architect-evidence.js)+ if [ "$FAILURE_STAGE" = evidence ]; then+ printf 'injected evidence failure\\n' >&2+ return 1+ fi+ "$REAL_NODE" "$@"+ ;;+ *) "$REAL_NODE" "$@" ;;+ esac+}+`;+ for (const failureStage of ['snapshot', 'evidence']) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'planning recovery '));+ testContext.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const temporary = path.join(directory, '.tmp');+ fs.mkdirSync(temporary);+ const snapshotFile = path.join(temporary, 'dataverse-foreground-planning-snapshot.json');+ const evidenceFile = path.join(temporary, 'dataverse-architect-evidence.json');+ fs.writeFileSync(snapshotFile, '{"stale":true}');+ fs.writeFileSync(evidenceFile, '{"stale":true}');+ const block = commands.replaceAll('<working_dir>', directory.replaceAll('\\', '/'));+ const env = {+ ...process.env, PLUGIN_ROOT: pluginRoot.replaceAll('\\', '/'), REAL_NODE: process.execPath.replaceAll('\\', '/'),+ FIXTURE_SNAPSHOT: JSON.stringify(snapshot), FAILURE_STAGE: failureStage,+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',+ };+ const failed = spawnSync(bash, ['-s'], {+ input: `${stub}\n${block}\nresult=$?\nprintf 'CONTROLLER_READY:%s\\n' "$result"\nexit "$result"`,+ env, encoding: 'utf8', timeout: 10000,+ });+ assert.equal(failed.status, 2, failed.stderr);+ assert.match(failed.stderr, /NEEDS_RECOVERY: dataverse-(snapshot|evidence)/);+ assert.match(failed.stdout, /CONTROLLER_READY:2/);+ assert.doesNotMatch(failed.stdout, /Dataverse inventory:/);+ assert.equal(fs.readFileSync(evidenceFile, 'utf8'), '{"stale":true}');+ if (failureStage === 'snapshot') {+ assert.equal(fs.readFileSync(snapshotFile, 'utf8'), '{"stale":true}');+ }++ const recovered = spawnSync(bash, ['-s'], {+ input: `${stub}\n${block}`,+ env: { ...env, FAILURE_STAGE: '' }, encoding: 'utf8', timeout: 10000,+ });+ assert.equal(recovered.status, 0, recovered.stderr);+ assert.match(recovered.stdout, /Dataverse inventory:/);+ loadAndValidateArchitectEvidence(snapshotFile, evidenceFile);+ }+});++test('planning recovery keeps the agent active without weakening approval or metadata checks', () => {+ assert.match(skill, /Foreground recovery, not agent termination/);+ assert.match(skill, /at most two repair-and-retry attempts per failing stage/);+ assert.match(skill, /rerun `run_dataverse_planning_attempt`/);+ assert.match(skill, /Never substitute stale\s+evidence, invent metadata/);+ assert.match(skill, /Ask the user only when recovery needs interactive sign-in/);+ assert.match(skill, /Individual table-detail failures do not stop planning/);+});++test('offline setup follows materialized Dataverse data and never infers connector-only from absence', () => {+ const dataModel = skill.indexOf('### Step 8 — Apply data model');+ const sampleData = skill.indexOf('### Step 8.5 — Seed sample data');+ const offline = skill.indexOf('### Offline profile');+ const native = skill.indexOf('### Step 9 — Apply native capabilities');++ assert.ok(dataModel < sampleData);+ assert.ok(sampleData < offline);+ assert.ok(offline < native);+ assert.doesNotMatch(skill, /Step 6\.85/);+ const design = skill.slice(skill.indexOf('### Step 6.75'), skill.indexOf('### Step 7'));+ assert.match(design, /`DONE`[^\n]+continue to Step 7/);+ assert.match(design, /Continuing to Step 7/);+ const offlineSetup = skill.slice(offline, native);+ assert.match(offlineSetup, /Do not infer connector-only from a missing manifest/);+ assert.match(offlineSetup, /read-only manifest\s+recovery in Step 8\.5 before asking/);+ assert.match(offlineSetup, /If verification still fails, report\s+`BLOCKED: offline setup requires the materialized Dataverse manifest from Step 8`/);+ assert.match(skill, /seeding step fails[\s\S]*continue to the offline-profile phase/);+});+test('template preparation is delegated to the deterministic script', () => {const start = skill.indexOf('### Step 5 — Prepare existing template');const end = skill.indexOf('### Step 6 — Initialize');diff --git a/plugins/mobile-apps/scripts/tests/dataverse-architect-evidence.test.js b/plugins/mobile-apps/scripts/tests/dataverse-architect-evidence.test.jsnew file mode 100644index 000000000..5c17edb2a--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-architect-evidence.test.js@@ -0,0 +1,154 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');++const {+ buildArchitectEvidence,+ loadAndValidateArchitectEvidence,+ sha256,+ validateArchitectEvidence,+} = require('../render-dataverse-architect-evidence');++function snapshot() {+ const table = {+ logicalName: 'new_goodsreception',+ schemaName: 'new_GoodsReception',+ entitySetName: 'new_goodsreceptions',+ primaryIdAttribute: 'new_goodsreceptionid',+ detailLevel: 'full',+ missingDetailClasses: [],+ columns: [{ logicalName: 'new_name', type: 'String' }],+ manyToOneRelationships: [],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ facts: { columnCount: 1, relationshipCount: 0, keyCount: 0 },+ };+ return {+ version: 3,+ purpose: 'foreground-planning',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ generatedAt: '2026-08-28T00:00:00.000Z',+ inputs: { concepts: [], explicitTableNames: [], proposedTableNames: [] },+ inventory: [+ { logicalName: 'new_goodsreception', customizable: true },+ { logicalName: 'new_unselected', customizable: true },+ ],+ inventoryFacts: {+ customizableTables: 2,+ exactNameTables: 0,+ requiredExactNameTables: 0,+ proposedCollisionTables: 0,+ totalTables: 2,+ },+ candidateRanking: [{+ concept: 'goods receptions',+ conceptKind: 'entity',+ discoverTable: true,+ skippedReason: null,+ preferredPublisherFamily: 'new',+ candidates: [+ { rank: 1, logicalName: 'new_goodsreception', score: 999, reasons: ['exact:goodreception'], matchClass: 'exact', detailed: true },+ { rank: 2, logicalName: 'new_unselected', score: 500, reasons: ['token:reception'], matchClass: 'token', detailed: false },+ { rank: 3, logicalName: 'new_third', score: 400, reasons: ['partial-token:reception'], matchClass: 'partial-token', detailed: false },+ { rank: 4, logicalName: 'new_fourth', score: 399, reasons: ['partial-token:reception'], matchClass: 'partial-token', detailed: false },+ ],+ }],+ selectedCandidateEvidence: [{ logicalName: table.logicalName, reasons: ['concept:goods receptions:primary'], required: false, detailStatus: 'loaded', detailFailure: null }],+ tables: [table],+ detailLoadFailures: [],+ detailLoadSummary: { attemptedCandidates: 1, loadedCandidates: 1, failedCandidates: 0 },+ proposedNameChecks: { checked: [], collisions: [], missing: [] },+ exactNameResolution: { requestedTables: [], loadedTables: [], unavailableTables: [] },+ timings: { inventoryRetrievalMs: 1, candidateSelectionMs: 1, detailLoadingMs: 1, totalDurationMs: 3 },+ };+}++test('architect evidence excludes unselected inventory and caps candidate summaries', () => {+ const source = snapshot();+ const hash = 'a'.repeat(64);+ const evidence = buildArchitectEvidence(source, hash);+ assert.deepEqual(evidence.selectedTables.map((table) => table.logicalName), [+ 'new_goodsreception',+ ]);+ assert.equal(evidence.concepts[0].topCandidates.length, 3);+ assert.doesNotMatch(JSON.stringify(evidence), /new_unselected.*customizable/);+ assert.deepEqual(validateArchitectEvidence(evidence, source, hash), {+ valid: true,+ errors: [],+ });+});++test('architect evidence detects stale hashes and changed selected facts', () => {+ const source = snapshot();+ const evidence = buildArchitectEvidence(source, 'a'.repeat(64));+ evidence.selectedTables[0].columns[0].type = 'Integer';+ const validation = validateArchitectEvidence(evidence, source, 'b'.repeat(64));+ assert.equal(validation.valid, false);+ assert.ok(validation.errors.includes('architect evidence source snapshot hash is stale'));+ assert.ok(validation.errors.some((error) => /differs from the snapshot/.test(error)));+ assert.ok(validation.errors.includes(+ 'architect evidence differs from the deterministic snapshot projection',+ ));+});++test('architect evidence detects tampered candidate and name-check projections', () => {+ const source = snapshot();+ const hash = 'a'.repeat(64);+ const evidence = buildArchitectEvidence(source, hash);+ evidence.concepts[0].topCandidates[0].score = -1;+ evidence.proposedNameChecks.missing.push('new_injected');+ const validation = validateArchitectEvidence(evidence, source, hash);+ assert.equal(validation.valid, false);+ assert.ok(validation.errors.includes(+ 'architect evidence differs from the deterministic snapshot projection',+ ));+});++test('architect evidence is materially smaller when inventory is large', () => {+ const source = snapshot();+ source.inventory.push(...Array.from({ length: 500 }, (_, index) => ({+ logicalName: `new_inventory${index}`,+ description: 'Inventory-only table that is deliberately excluded from architect evidence.',+ customizable: true,+ })));+ source.inventoryFacts.customizableTables = source.inventory.length;+ source.inventoryFacts.totalTables = source.inventory.length;+ const evidence = buildArchitectEvidence(source, 'a'.repeat(64));+ assert.ok(+ Buffer.byteLength(JSON.stringify(evidence))+ < Buffer.byteLength(JSON.stringify(source)) * 0.5,+ );+});++test('file validation detects a sidecar stale against the full snapshot', (context) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'architect-evidence-'));+ context.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const snapshotFile = path.join(directory, 'snapshot.json');+ const evidenceFile = path.join(directory, 'evidence.json');+ const sourceSnapshot = snapshot();+ const source = `${JSON.stringify(sourceSnapshot, null, 2)}\n`;+ fs.writeFileSync(snapshotFile, source);+ fs.writeFileSync(+ evidenceFile,+ JSON.stringify(buildArchitectEvidence(sourceSnapshot, sha256(source))),+ );++ assert.equal(+ loadAndValidateArchitectEvidence(snapshotFile, evidenceFile).evidence.schemaVersion,+ 1,+ );+ fs.writeFileSync(+ snapshotFile,+ `${JSON.stringify({ ...sourceSnapshot, generatedAt: '2026-08-28T00:01:00.000Z' }, null, 2)}\n`,+ );+ assert.throws(+ () => loadAndValidateArchitectEvidence(snapshotFile, evidenceFile),+ /source snapshot hash is stale/,+ );+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-candidate-relevance.test.js b/plugins/mobile-apps/scripts/tests/dataverse-candidate-relevance.test.jsnew file mode 100644index 000000000..48a7cef67--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-candidate-relevance.test.js@@ -0,0 +1,179 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');++const {+ parseConcepts,+ rankCandidatesByConcept,+ selectDetailedCandidates,+ selectStrongProposedCollisions,+} = require('../create-dataverse-snapshot');++function label(value) {+ return { UserLocalizedLabel: { Label: value } };+}++function entity(logicalName, displayName, description = `${displayName} records`) {+ return {+ LogicalName: logicalName,+ SchemaName: logicalName,+ EntitySetName: `${logicalName}s`,+ DisplayName: label(displayName),+ DisplayCollectionName: label(`${displayName}s`),+ Description: label(description),+ 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 },+ };+}++function concept(phrase, kind = 'entity', discoverTable = kind === 'entity') {+ return { phrase, kind, discoverTable, evidence: `Brief mentions ${phrase}.` };+}++test('typed roles, attributes, and constraints do not discover Dataverse tables', () => {+ const rankings = rankCandidatesByConcept([+ entity('rollupfield', 'Rollup Field'),+ entity('fax', 'Fax'),+ entity('new_goodsreception', 'Goods Reception'),+ ], [+ concept('field logisticians', 'role', false),+ concept('batch numbers', 'attribute', false),+ concept('limited connectivity', 'constraint', false),+ concept('goods receptions'),+ ]);++ assert.deepEqual(rankings.slice(0, 3).map((ranking) => ({+ concept: ranking.concept,+ candidates: ranking.candidates,+ skippedReason: ranking.skippedReason,+ })), [+ { concept: 'field logisticians', candidates: [], skippedReason: 'concept-kind:role' },+ { concept: 'batch numbers', candidates: [], skippedReason: 'concept-kind:attribute' },+ { concept: 'limited connectivity', candidates: [], skippedReason: 'concept-kind:constraint' },+ ]);+ assert.equal(rankings[3].candidates[0].logicalName, 'new_goodsreception');+ assert.equal(rankings[3].candidates[0].matchClass, 'exact');+});++test('typed persistent concepts select the six exact receiving tables without alternatives', () => {+ const entities = [+ entity('new_goodsitem', 'Goods Item'),+ entity('new_expectedshipment', 'Expected Shipment'),+ entity('new_expectedshipmentline', 'Expected Shipment Line'),+ entity('new_goodsreception', 'Goods Reception'),+ entity('new_goodsreceptionline', 'Goods Reception Line'),+ entity('new_damageevidence', 'Damage Evidence'),+ entity('new_damagephoto', 'Damage Photo'),+ entity('new_damagereport', 'Damage Report'),+ ];+ const concepts = [+ concept('goods items'),+ concept('expected shipments'),+ concept('expected shipment lines'),+ concept('goods receptions'),+ concept('goods reception lines'),+ concept('damage evidence'),+ ];+ const selection = selectDetailedCandidates(entities, [], concepts);++ assert.deepEqual(selection.selectedEntities.map((item) => item.LogicalName), [+ 'new_damageevidence',+ 'new_expectedshipment',+ 'new_expectedshipmentline',+ 'new_goodsitem',+ 'new_goodsreception',+ 'new_goodsreceptionline',+ ]);+ assert.equal(selection.detailSelectionSummary.primaryCandidates, 6);+ assert.equal(selection.detailSelectionSummary.ambiguityCandidates, 0);+ assert.equal(selection.detailSelectionSummary.deferredCandidates, 2);+});++test('typed ambiguity adds only the second candidate and defers the third', () => {+ const selection = selectDetailedCandidates([+ entity('new_inspection', 'Inspection'),+ entity('new_inspectionitem', 'Inspection Item'),+ entity('new_inspectionphoto', 'Inspection Photo'),+ ], [], [concept('inspection results')]);++ assert.equal(selection.selectedEntities.length, 2);+ assert.equal(selection.detailSelectionSummary.primaryCandidates, 1);+ assert.equal(selection.detailSelectionSummary.ambiguityCandidates, 1);+ assert.equal(selection.detailSelectionSummary.deferredCandidates, 1);+});++test('multiword display phrase promotes a lower-ranked proposed collision', () => {+ const entities = [+ entity('new_checkin', 'Evidence'),+ entity('new_damagephoto', 'Damage Photo'),+ entity('new_damageevidence', 'Damage Evidence'),+ ];+ const concepts = [concept('damage evidence attachments')];+ const selection = selectDetailedCandidates(entities, [], concepts, {+ proposedTableNames: ['new_damageevidence'],+ });++ assert.deepEqual(+ selection.selectedEntities.map((item) => item.LogicalName),+ ['new_checkin', 'new_damageevidence', 'new_damagephoto'],+ );+ assert.equal(selection.detailSelectionSummary.strongCollisionCandidates, 1);+ assert.ok(selection.selectedEvidence.find(+ (item) => item.logicalName === 'new_damageevidence',+ ).reasons.includes('proposed-collision:strong-concept-phrase'));+});++test('single generic display word does not promote a proposed collision', () => {+ const entities = [+ entity('fax', 'Signed Document Register'),+ entity('new_document', 'Document'),+ ];+ const rankings = rankCandidatesByConcept(entities, [concept('signed delivery documents')]);+ const selected = selectStrongProposedCollisions(+ entities,+ ['new_document'],+ rankings,+ new Map([['fax', new Set(['concept:signed delivery documents:primary'])]]),+ );+ assert.deepEqual(selected, []);+});++test('structured concept files are validated and legacy input remains supported', (context) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'dataverse-concepts-'));+ context.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const file = path.join(directory, 'concepts.json');+ fs.writeFileSync(file, JSON.stringify([+ concept('goods receptions'),+ concept('batch numbers', 'attribute', false),+ ]));+ assert.deepEqual(parseConcepts({ 'concepts-file': file }), [+ concept('goods receptions'),+ concept('batch numbers', 'attribute', false),+ ]);+ assert.deepEqual(parseConcepts({ concepts: 'goods receptions,batch numbers' }), [+ 'goods receptions',+ 'batch numbers',+ ]);+ assert.throws(+ () => parseConcepts({ concepts: 'goods', 'concepts-file': file }),+ /mutually exclusive/,+ );+ fs.writeFileSync(file, JSON.stringify([{ phrase: 'goods receptions', kind: 'unknown' }]));+ assert.throws(() => parseConcepts({ 'concepts-file': file }), /kind is invalid/);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-inventory-cache.test.js b/plugins/mobile-apps/scripts/tests/dataverse-inventory-cache.test.jsnew file mode 100644index 000000000..c7eba6063--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-inventory-cache.test.js@@ -0,0 +1,663 @@+'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 {+ DEFAULT_TTL_MS,+ invalidateInventoryCache,+ main: cacheMain,+ readInventoryCache,+ writeInventoryCache,+} = require('../dataverse-inventory-cache');+const {+ cacheablePlanningInventory,+ createSnapshot,+ expandSnapshot,+ main: snapshotMain,+} = require('../create-dataverse-snapshot');++const context = {+ environmentUrl: 'https://example.crm.dynamics.com/',+ tenantId: 'TENANT-1',+ solution: 'Default',+ apiVersion: '9.2',+ inventorySchemaVersion: 3,+};++function tempFile(testContext) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'dataverse-inventory-'));+ testContext.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ return path.join(directory, 'inventory.json');+}++function inventoryItem() {+ return {+ logicalName: 'new_item', schemaName: 'new_Item',+ entitySetName: 'new_items', primaryIdAttribute: 'new_itemid',+ displayName: 'Item', displayCollectionName: 'Items', description: '',+ primaryNameAttribute: 'new_name', ownershipType: 'UserOwned',+ customEntity: true, managed: false, customizable: true,+ canCreateAttributes: true, canBePrimaryEntityInRelationship: true,+ canBeRelatedEntityInRelationship: true, canBeInManyToMany: true,+ hasActivities: false, hasNotes: false,+ isAvailableOffline: true, changeTrackingEnabled: true,+ };+}++function planningFixture() {+ const displayName = (value) => ({ UserLocalizedLabel: { Label: value } });+ const logicalName = 'new_item';+ return {+ concepts: [{+ phrase: 'items',+ kind: 'entity',+ discoverTable: true,+ evidence: 'Fixture brief mentions items.',+ }],+ entities: [{+ LogicalName: logicalName,+ SchemaName: 'new_Item',+ EntitySetName: 'new_items',+ DisplayName: displayName('Item'),+ DisplayCollectionName: displayName('Items'),+ Description: displayName('Item records'),+ PrimaryIdAttribute: 'new_itemid',+ PrimaryNameAttribute: 'new_name',+ OwnershipType: 'UserOwned',+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ CanBePrimaryEntityInRelationship: { Value: true },+ CanBeRelatedEntityInRelationship: { Value: true },+ CanBeInManyToMany: { Value: true },+ HasActivities: false,+ HasNotes: false,+ IsAvailableOffline: true,+ ChangeTrackingEnabled: true,+ }],+ tables: [{+ logicalName,+ columns: [{+ MetadataId: 'new_name-metadata',+ LogicalName: 'new_name',+ SchemaName: 'new_Name',+ AttributeType: 'String',+ AttributeTypeName: { Value: 'StringType' },+ IsPrimaryName: true,+ IsCustomAttribute: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ IsValidForCreate: true,+ IsValidForRead: true,+ IsValidForUpdate: true,+ RequiredLevel: { Value: 'ApplicationRequired' },+ MaxLength: 200,+ FormatName: { Value: 'Text' },+ SourceType: 0,+ SourceTypeMask: 0,+ }],+ manyToOneRelationships: [],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ lookupTargets: {},+ computed: {},+ }],+ };+}++function fixtureRequest(fixture, calls = []) {+ return async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.startsWith('EntityDefinitions?')) {+ return {+ status: 200,+ data: {+ value: apiPath.includes('IsCustomizable/Value eq true')+ ? fixture.entities+ : fixture.entities.filter(+ (item) => apiPath.includes(`LogicalName eq '${item.LogicalName}'`),+ ),+ },+ };+ }+ const table = fixture.tables[0];+ if (apiPath.includes('$expand=Attributes(')) {+ return {+ status: 200,+ data: {+ LogicalName: table.logicalName,+ Attributes: table.columns,+ ManyToOneRelationships: [],+ OneToManyRelationships: [],+ ManyToManyRelationships: [],+ Keys: [],+ },+ };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: table.columns } };+ }+ return { status: 200, data: { value: [] } };+ };+}++test('fresh matching inventory cache is reused', (testContext) => {+ const file = tempFile(testContext);+ writeInventoryCache(file, context, [inventoryItem()], {+ nowMs: () => 100,+ nowIso: () => '2026-08-28T00:00:00.000Z',+ });+ assert.deepEqual(readInventoryCache(file, context, {+ nowMs: () => 150,+ ttlMs: 100,+ }), {+ hit: true,+ reason: 'fresh',+ inventory: [inventoryItem()],+ ageMs: 50,+ cachedAt: '2026-08-28T00:00:00.000Z',+ });+});++test('expired, mismatched, and corrupt caches fail open to a live planning read', (testContext) => {+ const file = tempFile(testContext);+ writeInventoryCache(file, context, [], { nowMs: () => 100 });+ assert.equal(readInventoryCache(file, context, { nowMs: () => 201, ttlMs: 100 }).reason, 'expired');+ assert.equal(readInventoryCache(file, { ...context, tenantId: 'tenant-2' }).reason, 'identity-mismatch');+ assert.equal(readInventoryCache(file, { ...context, solution: 'Other' }).reason, 'identity-mismatch');+ assert.equal(readInventoryCache(file, { ...context, apiVersion: '9.3' }).reason, 'identity-mismatch');+ const malformed = JSON.parse(fs.readFileSync(file, 'utf8'));+ malformed.identity = {};+ fs.writeFileSync(file, JSON.stringify(malformed));+ assert.equal(readInventoryCache(file, context).reason, 'identity-mismatch');+ fs.writeFileSync(file, '{invalid');+ assert.equal(readInventoryCache(file, context).reason, 'invalid-json');+});++test('slow snapshot details cannot restart the inventory cache TTL', async (testContext) => {+ const file = tempFile(testContext);+ const output = path.join(path.dirname(file), 'snapshot.json');+ const fixture = planningFixture();+ const calls = [];+ const request = fixtureRequest(fixture, calls);+ const retrievedAtMs = Date.parse('2026-09-23T00:00:00.000Z');+ let currentTimeMs = retrievedAtMs;+ let delayed = false;+ testContext.mock.method(Date, 'now', () => currentTimeMs);+ testContext.mock.method(console, 'log', () => {});+ testContext.mock.method(process.stderr, 'write', () => true);+ const args = [+ 'node', 'create-dataverse-snapshot.js',+ '--env-url', context.environmentUrl,+ '--tenant-id', context.tenantId,+ '--output', output,+ '--tables', 'new_item',+ '--combined-base-read',+ '--inventory-cache', file,+ ];+ const createExecutor = () => async (method, apiPath) => {+ if (apiPath.includes('$expand=Attributes(') && !delayed) {+ currentTimeMs += DEFAULT_TTL_MS + 1;+ delayed = true;+ }+ return request(method, apiPath);+ };++ await snapshotMain(args, { createExecutor });+ assert.equal(delayed, true);+ const cache = readInventoryCache(file, context);+ assert.equal(cache.hit, false);+ assert.equal(cache.reason, 'expired');+ assert.equal(cache.ageMs, DEFAULT_TTL_MS + 1);+ const stored = JSON.parse(fs.readFileSync(file, 'utf8'));+ assert.equal(stored.cachedAtMs, retrievedAtMs);+ assert.equal(stored.cachedAt, new Date(retrievedAtMs).toISOString());++ fixture.entities.push({+ ...fixture.entities[0],+ LogicalName: 'new_recent',+ SchemaName: 'new_Recent',+ EntitySetName: 'new_recents',+ PrimaryIdAttribute: 'new_recentid',+ });+ await snapshotMain(args, { createExecutor });+ assert.equal(calls.filter((apiPath) => apiPath.includes('IsCustomizable/Value eq true')).length, 2);+ const snapshot = JSON.parse(fs.readFileSync(output, 'utf8'));+ assert.ok(snapshot.inventory.some((table) => table.logicalName === 'new_recent'));+});++test('snapshot cache hits preserve discovery age until the configured TTL expires', async (testContext) => {+ const file = tempFile(testContext);+ const output = path.join(path.dirname(file), 'snapshot.json');+ const calls = [];+ const request = fixtureRequest(planningFixture(), calls);+ const retrievedAtMs = Date.parse('2026-09-23T00:00:00.000Z');+ let currentTimeMs = retrievedAtMs;+ testContext.mock.method(Date, 'now', () => currentTimeMs);+ testContext.mock.method(console, 'log', () => {});+ testContext.mock.method(process.stderr, 'write', () => true);+ const ttlMs = 5000;+ const args = [+ 'node', 'create-dataverse-snapshot.js',+ '--env-url', context.environmentUrl,+ '--tenant-id', context.tenantId,+ '--output', output,+ '--tables', 'new_item',+ '--combined-base-read',+ '--inventory-cache', file,+ '--inventory-cache-ttl-ms', String(ttlMs),+ ];+ const createExecutor = () => async (method, apiPath) => {+ if (apiPath.includes('$expand=Attributes(')) currentTimeMs += 1000;+ return request(method, apiPath);+ };++ await snapshotMain(args, { createExecutor });+ const cache = readInventoryCache(file, context, { ttlMs });+ assert.equal(cache.hit, true);+ assert.equal(cache.ageMs, 1000);+ const beforeHit = fs.readFileSync(file, 'utf8');++ await snapshotMain(args, { createExecutor });+ assert.equal(JSON.parse(fs.readFileSync(output, 'utf8')).inventorySource, 'cache');+ assert.equal(fs.readFileSync(file, 'utf8'), beforeHit);+ assert.equal(readInventoryCache(file, context, { ttlMs }).ageMs, 2000);+ assert.equal(calls.filter((apiPath) => apiPath.includes('IsCustomizable/Value eq true')).length, 1);++ currentTimeMs = retrievedAtMs + ttlMs + 1;+ await snapshotMain(args, { createExecutor });+ assert.equal(JSON.parse(fs.readFileSync(output, 'utf8')).inventorySource, 'live');+ assert.equal(calls.filter((apiPath) => apiPath.includes('IsCustomizable/Value eq true')).length, 2);+});++test('cache invalidation is idempotent', (testContext) => {+ const file = tempFile(testContext);+ writeInventoryCache(file, context, []);+ assert.equal(invalidateInventoryCache(file), true);+ assert.equal(invalidateInventoryCache(file), true);+});++test('cache invalidation CLI fails when the cache file survives', () => {+ let stderr = '';+ const code = cacheMain(+ ['node', 'dataverse-inventory-cache.js', '--file', '/tmp/inventory.json', '--invalidate'],+ {+ fileSystem: {+ rmSync() {},+ existsSync: () => true,+ },+ stdout: { write() {} },+ stderr: { write: (value) => { stderr += value; } },+ },+ );+ assert.equal(code, 2);+ assert.match(stderr, /failed to invalidate/);+});++test('a corrupt cache is replaced atomically without temporary siblings', (testContext) => {+ const file = tempFile(testContext);+ fs.writeFileSync(file, '{invalid');+ assert.equal(readInventoryCache(file, context).reason, 'invalid-json');+ writeInventoryCache(file, context, [inventoryItem()]);+ assert.equal(readInventoryCache(file, context).hit, true);+ assert.deepEqual(fs.readdirSync(path.dirname(file)), ['inventory.json']);+});++test('cached inventory skips broad discovery and refreshes every exact name live', async () => {+ const calls = [];+ const inventory = [{+ logicalName: 'new_item',+ schemaName: 'new_item',+ displayName: 'Item',+ displayCollectionName: 'Items',+ description: 'Item records',+ entitySetName: 'new_items',+ primaryIdAttribute: 'new_itemid',+ primaryNameAttribute: 'new_name',+ ownershipType: 'UserOwned',+ customEntity: true,+ managed: false,+ customizable: true,+ canCreateAttributes: true,+ }];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ inventory,+ inventorySource: 'cache',+ inventoryCacheAgeMs: 20,+ proposedTableNames: ['new_item', 'new_missing'],+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ return { status: 200, data: { value: [] } };+ },+ });+ assert.equal(snapshot.inventorySource, 'cache');+ assert.equal(snapshot.inventoryCacheAgeMs, 20);+ assert.equal(calls.some((apiPath) => apiPath.includes('IsCustomizable/Value eq true')), false);+ assert.equal(calls.filter((apiPath) => apiPath.startsWith('EntityDefinitions?')).length, 1);+ assert.match(calls[0], /LogicalName eq 'new_item'/);+ assert.match(calls[0], /LogicalName eq 'new_missing'/);+ assert.deepEqual(snapshot.proposedNameChecks.missing, ['new_item', 'new_missing']);+ assert.equal(snapshot.inventory.some((item) => item.logicalName === 'new_item'), false);+ assert.equal(snapshot.inventoryFacts.customizableTables, 0);+ assert.equal(snapshot.inventoryFacts.exactNameTables, 0);+ assert.equal(snapshot.inventoryFacts.proposedCollisionTables, 0);+});++test('cached exact-name refresh chunks more than fifty requested names', async () => {+ const rawInventory = Array.from({ length: 55 }, (_, index) => ({+ LogicalName: `new_item${index}`,+ SchemaName: `new_Item${index}`,+ DisplayName: { UserLocalizedLabel: { Label: `Item ${index}` } },+ DisplayCollectionName: { UserLocalizedLabel: { Label: `Items ${index}` } },+ Description: { UserLocalizedLabel: { Label: `Item ${index} records` } },+ EntitySetName: `new_item${index}s`,+ PrimaryIdAttribute: `new_item${index}id`,+ PrimaryNameAttribute: 'new_name',+ OwnershipType: 'UserOwned',+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ }));+ const calls = [];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ inventory: rawInventory,+ inventorySource: 'cache',+ proposedTableNames: rawInventory.map((item) => item.LogicalName),+ request: async (_method, apiPath) => {+ calls.push(apiPath);+ return { status: 200, data: { value: rawInventory } };+ },+ });+ assert.equal(calls.length, 2);+ assert.equal(snapshot.proposedNameChecks.collisions.length, 55);+ assert.equal(snapshot.inventoryFacts.exactNameTables, 0);+});++test('live and cached inventory produce identical ranking and selected table evidence', async (testContext) => {+ const rawEntity = {+ LogicalName: 'new_item',+ SchemaName: 'new_Item',+ DisplayName: { UserLocalizedLabel: { Label: 'Item' } },+ DisplayCollectionName: { UserLocalizedLabel: { Label: 'Items' } },+ Description: { UserLocalizedLabel: { Label: 'Item records' } },+ EntitySetName: 'new_items',+ PrimaryIdAttribute: 'new_itemid',+ PrimaryNameAttribute: 'new_name',+ OwnershipType: 'UserOwned',+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ };+ const makeRequest = (liveInventory) => async (_method, apiPath) => {+ if ((liveInventory && apiPath.includes('IsCustomizable/Value eq true'))+ || apiPath.includes("LogicalName eq 'new_item'")) {+ return { status: 200, data: { value: [rawEntity] } };+ }+ return { status: 200, data: { value: [] } };+ };+ const options = {+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: [{ phrase: 'items', kind: 'entity', discoverTable: true, evidence: 'items' }],+ nowIso: () => '2026-08-28T00:00:00.000Z',+ };+ const live = await createSnapshot({ ...options, request: makeRequest(true) });+ const file = tempFile(testContext);+ writeInventoryCache(file, context, cacheablePlanningInventory(live));+ const cache = readInventoryCache(file, context);+ assert.equal(cache.hit, true);+ const cached = await createSnapshot({+ ...options,+ inventory: cache.inventory,+ inventorySource: 'cache',+ inventoryCacheAgeMs: 10,+ request: makeRequest(false),+ });+ assert.deepEqual(cached.candidateRanking, live.candidateRanking);+ assert.deepEqual(cached.selectedCandidateEvidence, live.selectedCandidateEvidence);+ assert.deepEqual(cached.tables, live.tables);+});++test('malformed cached inventories recover through a live read instead of an empty or crashed discovery', async (testContext) => {+ const file = tempFile(testContext);+ const valid = writeInventoryCache(file, context, [inventoryItem()]);+ const requiredFields = ['displayName', 'displayCollectionName', 'description',+ 'ownershipType', 'customEntity', 'managed', 'customizable', 'canCreateAttributes',+ 'canBePrimaryEntityInRelationship', 'canBeRelatedEntityInRelationship', 'canBeInManyToMany',+ 'hasActivities', 'hasNotes', 'isAvailableOffline', 'changeTrackingEnabled'];+ const missingFields = requiredFields.map((field) => {+ const item = inventoryItem();+ delete item[field];+ return [item];+ });+ const invalidFields = [+ { customizable: false }, { customizable: 'true' }, { displayName: [] },+ { displayCollectionName: null }, { description: {} }, { customEntity: 'false' },+ { managed: null }, { canCreateAttributes: 'false' }, { isAvailableOffline: 1 },+ { primaryNameAttribute: 'bad name' }, { ownershipType: {} },+ ].map((updates) => [{ ...inventoryItem(), ...updates }]);+ const invalidInventories = [null, {}, [null], [[]], ['invalid'], [{}],+ [{ logicalName: 'new_item' }], [{ ...inventoryItem(), logicalName: 'bad name' }],+ [inventoryItem(), inventoryItem()],+ [inventoryItem(), { ...inventoryItem(), logicalName: 'NEW_ITEM' }],+ ...missingFields, ...invalidFields];+ for (const body of [null, [], 'invalid', ...invalidInventories.map((inventory) => ({ ...valid, inventory }))]) {+ fs.writeFileSync(file, JSON.stringify(body));+ const cache = readInventoryCache(file, context);+ assert.equal(cache.hit, false);+ assert.equal(cache.reason, 'invalid-shape');+ assert.equal(cache.inventory, null);+ let liveReads = 0;+ const snapshot = await createSnapshot({+ ...context, inventory: cache.inventory,+ request: async (_method, apiPath) => {+ assert.match(apiPath, /IsCustomizable\/Value eq true/);+ liveReads += 1;+ return { status: 200, data: { value: [] } };+ },+ });+ assert.equal(liveReads, 1);+ assert.deepEqual(snapshot.inventory, []);+ }+});++test('cache preserves customizable managed tables and explicit unknown capabilities', (testContext) => {+ const file = tempFile(testContext);+ const item = { ...inventoryItem(), managed: true, customEntity: false,+ primaryNameAttribute: null, ownershipType: null, canCreateAttributes: null,+ canBePrimaryEntityInRelationship: null, canBeRelatedEntityInRelationship: null,+ canBeInManyToMany: null, hasActivities: null, hasNotes: null,+ isAvailableOffline: null, changeTrackingEnabled: null };+ writeInventoryCache(file, context, [item]);+ const cache = readInventoryCache(file, context);+ assert.equal(cache.hit, true);+ assert.deepEqual(cache.inventory, [item]);+});++test('cached advisory tables refresh live identity flags without broad discovery or duplicate exact reads', async () => {+ const fixture = planningFixture();+ const options = { ...context, concepts: [fixture.concepts[0]], combinedBaseRead: true };+ const baseline = await createSnapshot({ ...options, request: fixtureRequest(fixture) });+ const target = fixture.entities[0];+ target.CanCreateAttributes = { Value: false };+ target.OwnershipType = 'OrganizationOwned';+ for (const exact of [{}, { tableNames: [target.LogicalName] }, { proposedTableNames: [target.LogicalName] }]) {+ const calls = [];+ const snapshot = await createSnapshot({+ ...options, ...exact, inventory: baseline.inventory, inventorySource: 'cache',+ request: fixtureRequest(fixture, calls),+ });+ const selected = snapshot.tables.find((item) => item.logicalName === target.LogicalName);+ assert.equal(selected.detailLevel, 'full');+ assert.equal(selected.canCreateAttributes, false);+ assert.equal(selected.ownershipType, 'OrganizationOwned');+ const currentInventory = snapshot.inventory.find((item) => item.logicalName === target.LogicalName);+ assert.equal(currentInventory.canCreateAttributes, false);+ assert.equal(currentInventory.ownershipType, 'OrganizationOwned');+ assert.equal(calls.filter((apiPath) => apiPath.startsWith('EntityDefinitions?')).length, 1);+ assert.equal(calls.some((apiPath) => apiPath.includes('IsCustomizable/Value eq true')), false);+ assert.ok(snapshot.liveRefreshedExactNames.includes(target.LogicalName));+ }+ target.IsCustomizable = { Value: false };+ const changed = await createSnapshot({+ ...options, inventory: baseline.inventory, inventorySource: 'cache',+ request: fixtureRequest(fixture),+ });+ assert.equal(changed.tables[0].customizable, false);+ assert.equal(changed.inventoryFacts.customizableTables, baseline.inventory.length - 1);+ const expanded = await expandSnapshot({+ snapshot: changed, proposedTableNames: [target.LogicalName],+ request: async () => assert.fail('already refreshed identity must not be loaded again'),+ });+ assert.equal(expanded.proposedNameChecks.collisions[0].existing.customizable, false);+});++test('deleted cached candidates are unavailable and malformed identity responses remain errors', async () => {+ const fixture = planningFixture();+ const options = { ...context, concepts: [fixture.concepts[0]] };+ const baseline = await createSnapshot({ ...options, request: fixtureRequest(fixture) });+ const cached = { ...options, inventory: baseline.inventory, inventorySource: 'cache' };+ const snapshot = await createSnapshot({+ ...cached, request: async (_method, apiPath) => {+ assert.ok(apiPath.startsWith('EntityDefinitions?'));+ return { status: 200, data: { value: [] } };+ },+ });+ assert.deepEqual(snapshot.tables, []);+ assert.equal(snapshot.detailLoadFailures[0].status, 404);+ assert.equal(snapshot.candidateRanking[0].candidates[0].detailStatus, 'unavailable');+ assert.equal(snapshot.inventory.some((item) => item.logicalName === fixture.entities[0].LogicalName), false);+ await assert.rejects(createSnapshot({+ ...cached, request: async () => ({ status: 200, data: {} }),+ }), /OData collection/);+});++test('execution reconciliation explicitly bypasses the planning inventory cache', () => {+ const source = fs.readFileSync(path.resolve(__dirname, '..', 'create-dataverse-snapshot.js'), 'utf8');+ assert.match(source, /inventoryCachePath && !baseSnapshot && !args\['reconcile-exact'\]/);+ assert.match(source, /if \(inventoryCachePath && !baseSnapshot && !args\['reconcile-exact'\] && !cacheRead\.hit\)/);+});++test('cache candidates exclude non-customizable exact-name additions', () => {+ assert.deepEqual(cacheablePlanningInventory({+ inventory: [+ { logicalName: 'new_item', customizable: true },+ { logicalName: 'managed_dependency', customizable: false },+ ],+ }), [{ logicalName: 'new_item', customizable: true }]);+});++test('both successful metadata publish paths invalidate planning inventory', () => {+ const skill = fs.readFileSync(path.resolve(+ __dirname,+ '..',+ '..',+ 'skills',+ 'add-dataverse',+ 'SKILL.md',+ ), 'utf8');+ const invalidations = skill.match(/node "\$\{PLUGIN_ROOT\}\/scripts\/dataverse-inventory-cache\.js"/g) || [];+ assert.equal(invalidations.length, 2);+ assert.doesNotMatch(skill, /CLAUDE_SKILL_DIR.*dataverse-inventory-cache/);+ assert.match(skill, /After the `publish` phase succeeds[\s\S]*dataverse-inventory-cache\.js/);+ assert.match(skill, /After a 2xx publish[\s\S]*dataverse-inventory-cache\.js/);+});++test('post-publish invalidation failures return to recovery before dependent steps', (testContext) => {+ const pluginRoot = path.resolve(__dirname, '..', '..');+ const skill = fs.readFileSync(path.join(pluginRoot, 'skills/add-dataverse/SKILL.md'), 'utf8');+ const blocks = [...skill.matchAll(/```bash\r?\n([\s\S]*?)\r?\n```/g)]+ .map((match) => match[1])+ .filter((block) => block.includes('/scripts/dataverse-inventory-cache.js'));+ assert.equal(blocks.length, 2);+ assert.match(skill, /at most two targeted retries\s+of the invalidation command/);+ assert.match(skill, /do not replay metadata writes or publish/);+ assert.match(skill, /Continue to Step 6c only after invalidation exits `0`/);+ const bashPaths = process.platform === 'win32'+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)+ : [];+ const bash = bashPaths.find((entry) => /[\\/]Git[\\/]/i.test(entry)) || 'bash';+ const directory = path.dirname(tempFile(testContext));+ fs.mkdirSync(path.join(directory, '.tmp'));+ const cachePath = path.join(directory, '.tmp/dataverse-inventory-cache.json');+ const checkpointPath = path.join(directory, '.tmp/dataverse-publish-pending.json');+ const stub = `+node() {+ case "$1" in+ */dataverse-inventory-cache.js)+ if [ "$FAIL_INVALIDATION" = 1 ]; then+ printf 'injected cache deletion failure\\n' >&2+ return 2+ fi+ ;;+ esac+ "$REAL_NODE" "$@"+}+`;+ for (const block of blocks) {+ fs.writeFileSync(cachePath, '{}');+ fs.writeFileSync(checkpointPath, '{}');+ const input = `${stub}\n${block.replaceAll('<working_dir>', directory.replaceAll('\\', '/'))}\nprintf 'DEPENDENT_STEP_REACHED\\n'\n`;+ const env = { ...process.env, PLUGIN_ROOT: pluginRoot.replaceAll('\\', '/'),+ REAL_NODE: process.execPath.replaceAll('\\', '/'),+ PUBLISH_CHECKPOINT: checkpointPath.replaceAll('\\', '/'),+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' };+ const failed = spawnSync(bash, ['-s'], {+ input, env: { ...env, FAIL_INVALIDATION: '1' }, encoding: 'utf8', timeout: 10000,+ });+ assert.equal(failed.status, 2, failed.stderr);+ assert.match(failed.stderr, /NEEDS_RECOVERY: dataverse-inventory-cache/);+ assert.doesNotMatch(failed.stdout, /DEPENDENT_STEP_REACHED/);+ assert.equal(fs.existsSync(cachePath), true);+ const recovered = spawnSync(bash, ['-s'], {+ input, env: { ...env, FAIL_INVALIDATION: '' }, encoding: 'utf8', timeout: 10000,+ });+ assert.equal(recovered.status, 0, recovered.stderr);+ assert.match(recovered.stdout, /DEPENDENT_STEP_REACHED/);+ assert.equal(fs.existsSync(cachePath), false);+ }+});++test('publish checkpoint cleanup tolerates an absent path but surfaces deletion errors', (testContext) => {+ const skill = fs.readFileSync(path.resolve(+ __dirname, '..', '..', 'skills', 'add-dataverse', 'SKILL.md',+ ), 'utf8');+ const cleanup = skill.match(/node -e "([^"]+)" \\\r?\n\s+"\$\{PUBLISH_CHECKPOINT:-\}"/);+ assert.ok(cleanup, 'checkpoint cleanup must default an unset shell variable to an empty path');++ const file = path.join(path.dirname(tempFile(testContext)), 'publish checkpoint.json');+ const runCleanup = args => spawnSync(process.execPath, ['-e', cleanup[1], ...args], {+ encoding: 'utf8',+ timeout: 5000,+ });+ fs.writeFileSync(file, '{}');+ for (const args of [[], ['']]) {+ const result = runCleanup(args);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.readFileSync(file, 'utf8'), '{}');+ }++ for (let attempt = 0; attempt < 2; attempt += 1) {+ const result = runCleanup([file]);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.existsSync(file), false);+ }++ const failed = runCleanup([path.dirname(file)]);+ assert.notEqual(failed.status, 0);+ assert.match(failed.stderr, /EISDIR|ERR_FS_EISDIR|EPERM/);+ assert.equal(fs.existsSync(path.dirname(file)), true);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.jsindex 774bb9949..d04f68b04 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-operation-manifest.test.js@@ -3,6 +3,7 @@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');@@ -96,6 +97,8 @@ function table(logicalName, columns, overrides = {}) {canBePrimaryEntityInRelationship: true,canBeRelatedEntityInRelationship: true,canBeInManyToMany: true,+ detailLevel: 'full',+ missingDetailClasses: [],columns,manyToOneRelationships: [],oneToManyRelationships: [],@@ -142,6 +145,15 @@ function snapshot({exactUnavailable = [],generatedAt = SNAPSHOT_AT,} = {}) {+ tables = tables.map((item) => ({+ ...item,+ facts: {+ columnCount: item.columns.length,+ relationshipCount: item.manyToOneRelationships.length+ + item.oneToManyRelationships.length + item.manyToManyRelationships.length,+ keyCount: item.alternateKeys.length,+ },+ }));const exactLoaded = tables.map((item) => item.logicalName);const requested = [...new Set([...exactLoaded,@@ -1149,7 +1161,7 @@ test('existing Dataverse File and Image virtual attributes are zero-write compat}});-test('existing image full-size configuration is repaired once with a full-definition PUT', () => {+function imageRepairFixture() {const contract = {schemaVersion: 1,publisherPrefix: 'cr1',@@ -1187,6 +1199,11 @@ test('existing image full-size configuration is repaired once with a full-definiimageUpdateDefinition: imageDefinition,}),]);+ return { contract, imageDefinition, existing };+}++test('existing image full-size configuration is repaired once with a full-definition PUT', () => {+ const { contract, imageDefinition, existing } = imageRepairFixture();const repair = buildManifest(buildInputs(contract, snapshot({ tables: [existing] })));const update = repair.execution.phases[1].operations[0];@@ -1828,6 +1845,203 @@ test('collision checkpoint roll-forward preserves prior writes and rebinds revis);});+function imageCollisionRecoveryFixture({ adaptedImage = false, existingSize = 10240, existingPrimaryImage = false } = {}) {+ const { contract, existing } = imageRepairFixture();+ const item = contract.tables[0];+ const image = item.columns.find((value) => value.type === 'image');+ const liveImage = existing.columns.find((value) => value.logicalName === 'cr1_photo');+ liveImage.maxSizeInKB = existingSize;+ liveImage.imageUpdateDefinition.MaxSizeInKB = existingSize;+ liveImage.imageUpdateDefinition.DisplayName = {+ LocalizedLabels: [{ Label: 'Existing localized image label', LanguageCode: 1033 }],+ };+ liveImage.isPrimaryImage = existingPrimaryImage;+ liveImage.imageUpdateDefinition.IsPrimaryImage = existingPrimaryImage;+ if (adaptedImage) {+ image.plannedDecision = 'adapt';+ image.adaptedLogicalName = 'cr1_photov2';+ image.adaptedSchemaName = 'cr1_PhotoV2';+ liveImage.logicalName = image.adaptedLogicalName;+ liveImage.schemaName = image.adaptedSchemaName;+ liveImage.imageUpdateDefinition.LogicalName = image.adaptedLogicalName;+ liveImage.imageUpdateDefinition.SchemaName = image.adaptedSchemaName;+ }+ item.dependencyTier = 1;+ item.columns.push(contractColumn('cr1_categoryid', 'lookup', 'create', {+ lookupTarget: 'cr1_category',+ }));+ item.relationships.push({+ 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',+ },+ });+ contract.tables.push(contractTable('cr1_category', 'reuse', 0, []));+ const reconciliation = snapshot({ tables: [+ existing,+ table('cr1_category', [column('cr1_name', 'String', { primaryName: true })]),+ ] });+ const priorInputs = buildInputs(contract, reconciliation, '# Prior image plan\n');+ const priorManifest = buildManifest(priorInputs);+ const operations = priorManifest.execution.phases.flatMap((phase) => phase.operations);+ assert.equal(priorManifest.executable, true);+ assert.deepEqual(operations.map((value) => value.method), ['PUT', 'POST', 'POST']);+ const [completedOperation, collisionOperation] = operations;+ const journal = {+ schemaVersion: 1,+ binding: {+ environmentUrl: CONTEXT.environmentUrl,+ solution: CONTEXT.solutionUniqueName,+ },+ completed: {+ [operationFingerprint(completedOperation, CONTEXT.solutionUniqueName)]: {+ operationId: completedOperation.id,+ status: 204,+ },+ },+ 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 },+ },+ };+ liveImage.canStoreFullImage = true;+ liveImage.imageUpdateDefinition = structuredClone(completedOperation.body);+ const revisedContract = structuredClone(contract);+ const revisedItem = revisedContract.tables.find((value) => value.logicalName === 'cr1_item');+ const relationship = revisedItem.relationships[0];+ relationship.plannedDecision = 'adapt';+ relationship.adaptedSchemaName = 'cr1_Category_ItemV2';+ relationship.lookup.adaptedLogicalName = 'cr1_categoryidv2';+ relationship.lookup.adaptedSchemaName = 'cr1_CategoryIdV2';+ const lookup = revisedItem.columns.find((value) => value.type === 'lookup');+ lookup.plannedDecision = 'adapt';+ lookup.adaptedLogicalName = relationship.lookup.adaptedLogicalName;+ lookup.adaptedSchemaName = relationship.lookup.adaptedSchemaName;+ function revisionInputs(revise = () => {}) {+ const revised = structuredClone(revisedContract);+ revise(revised.tables.find((value) => value.logicalName === 'cr1_item'));+ return buildInputs(revised, reconciliation, '# Revised image plan\n');+ }+ function rollForward(inputs) {+ return rollForwardPublishCheckpoint({+ checkpoint: priorManifest.publishCheckpoint,+ previousManifest: priorManifest,+ journal,+ contract: inputs.contract,+ approvalReceipt: inputs.approvalReceipt,+ contractBytes: inputs.contractBytes,+ planBytes: inputs.planBytes,+ context: CONTEXT,+ rolledAt: NOW,+ });+ }+ return { priorManifest, completedOperation, revisionInputs, rollForward };+}++test('image checkpoint roll-forward preserves completed PUTs and resumes relationship publication', () => {+ for (const adaptedImage of [false, true]) {+ const fixture = imageCollisionRecoveryFixture({ adaptedImage, existingSize: 20480 });+ const priorBytes = stableJson(fixture.priorManifest);+ const inputs = fixture.revisionInputs();+ const rolled = fixture.rollForward(inputs);+ assert.deepEqual(rolled.tables, ['cr1_item']);+ assert.equal(rolled.binding.planSha256, sha256(inputs.planBytes));+ assert.deepEqual(rolled.rollForwards[0].previousCheckpoint, fixture.priorManifest.publishCheckpoint);+ assert.equal(stableJson(fixture.priorManifest), priorBytes);+ assert.equal(fixture.completedOperation.body.MaxSizeInKB, 20480);+ assert.equal(fixture.completedOperation.body.MaxHeight, 144);+ assert.equal(fixture.completedOperation.body.IsPrimaryImage, false);+ assert.equal(fixture.completedOperation.body.DisplayName.LocalizedLabels[0].Label, 'Existing localized image label');++ const manifest = buildManifest({ ...inputs, publishCheckpoint: rolled });+ assert.equal(manifest.executable, true);+ assert.deepEqual(+ manifest.execution.phases.flatMap((phase) => phase.operations).map((value) => value.id),+ ['create-relationship:cr1_category_itemv2', 'publish-customizations'],+ );+ assert.match(+ manifest.execution.phases[4].operations[0].body.ParameterXml,+ /<entity>cr1_item<\/entity>/,+ );+ const validation = validateManifest(manifest, {+ ...inputs, publishCheckpoint: rolled, requireExecutable: true,+ });+ assert.equal(validation.valid, true, validation.errors.join('; '));+ }+});++test('image checkpoint roll-forward rejects incompatible or removed completed image components', () => {+ const fixture = imageCollisionRecoveryFixture();+ const cases = [+ ['removed', (item) => { item.columns = item.columns.filter((value) => value.type !== 'image'); }],+ ['table deferred', (item) => { item.plannedDecision = 'defer'; }],+ ['table unverified', (item) => { item.plannedDecision = 'unverified'; }],+ ['table renamed', (item) => {+ item.plannedDecision = 'adapt';+ item.adaptedLogicalName = 'cr1_itemv2';+ item.adaptedSchemaName = 'cr1_ItemV2';+ }],+ ...[+ ['type', { type: 'file' }],+ ['deferred', { plannedDecision: 'defer' }],+ ['unverified', { plannedDecision: 'unverified' }],+ ['reuse', { plannedDecision: 'reuse' }],+ ['retention', { canStoreFullImage: false }],+ ['larger size', { maxSizeInKB: 20480 }],+ ['required level', { requiredLevel: 'ApplicationRequired' }],+ ['primary name', { primaryName: true }],+ ['renamed', {+ plannedDecision: 'adapt',+ adaptedLogicalName: 'cr1_photov2',+ adaptedSchemaName: 'cr1_PhotoV2',+ }],+ ].map(([name, updates]) => [+ name,+ (item) => Object.assign(item.columns.find((value) => value.type === 'image'), updates),+ ]),+ ];+ for (const [name, revise] of cases) {+ assert.throws(+ () => fixture.rollForward(fixture.revisionInputs(revise)),+ /completed metadata component configure-image:cr1_item:cr1_photo was removed or changed/,+ name,+ );+ }+});++test('image checkpoint recovery verifies explicitly approved primary-image semantics', () => {+ for (const existingPrimaryImage of [false, true]) {+ const fixture = imageCollisionRecoveryFixture({ existingPrimaryImage });+ const matching = fixture.revisionInputs((item) => {+ item.columns.find((column) => column.type === 'image').isPrimaryImage = existingPrimaryImage;+ });+ const rolled = fixture.rollForward(matching);+ const manifest = buildManifest({ ...matching, publishCheckpoint: rolled });+ assert.equal(manifest.executable, true);+ assert.equal(manifest.execution.phases.flatMap((phase) => phase.operations)+ .some((operation) => operation.id.startsWith('configure-image:')), false);++ const changed = fixture.revisionInputs((item) => {+ item.columns.find((column) => column.type === 'image').isPrimaryImage = !existingPrimaryImage;+ });+ assert.throws(() => fixture.rollForward(changed),+ /completed metadata component configure-image:cr1_item:cr1_photo was removed or changed/);+ assert.equal(buildManifest(changed).executable, false);+ }+});+test('checkpoint roll-forward rejects removed completed columns, relationships, and keys', () => {function expectCompletedComponentRejected({priorContract,diff --git a/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.jsdeleted file mode 100644index fe90557a5..000000000--- a/plugins/mobile-apps/scripts/tests/dataverse-planning-benchmark.test.js+++ /dev/null@@ -1,52 +0,0 @@-'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-decisions.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-decisions.test.jsnew file mode 100644index 000000000..dae3b4a4c--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-planning-decisions.test.js@@ -0,0 +1,389 @@+'use strict';++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 test = require('node:test');++const {+ getBlockingErrors,+ getRevisionErrors,+ validatePlanningDecisions,+} = require('../validate-dataverse-planning-decisions');++function table(logicalName, detailLevel = 'full') {+ return {+ logicalName,+ schemaName: logicalName,+ entitySetName: `${logicalName}s`,+ primaryIdAttribute: `${logicalName}id`,+ detailLevel,+ missingDetailClasses: detailLevel === 'full' ? [] : ['typed-constraints'],+ columns: [],+ manyToOneRelationships: [],+ oneToManyRelationships: [],+ manyToManyRelationships: [],+ alternateKeys: [],+ facts: { columnCount: 0, relationshipCount: 0, keyCount: 0 },+ };+}++function snapshot(tables, proposedChecks = [], detailLoadFailures = []) {+ const inventoryNames = new Set([+ ...tables.map((item) => item.logicalName),+ ...detailLoadFailures.map((failure) => failure.logicalName),+ ]);+ return {+ version: 3,+ purpose: 'foreground-planning',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ generatedAt: '2026-08-28T00:00:00.000Z',+ inputs: { concepts: [], explicitTableNames: [], proposedTableNames: [] },+ inventory: [...inventoryNames].map((logicalName) => ({ logicalName, customizable: true })),+ inventoryFacts: { customizableTables: inventoryNames.size, exactNameTables: 0, requiredExactNameTables: 0, proposedCollisionTables: 0, totalTables: inventoryNames.size },+ candidateRanking: [],+ selectedCandidateEvidence: [],+ tables,+ detailLoadFailures,+ detailLoadSummary: { attemptedCandidates: tables.length + detailLoadFailures.length, loadedCandidates: tables.length, failedCandidates: detailLoadFailures.length },+ proposedNameChecks: {+ checked: proposedChecks,+ collisions: proposedChecks.filter((item) => item.status === 'collision'),+ missing: proposedChecks.filter((item) => item.status === 'missing')+ .map((item) => item.logicalName),+ },+ exactNameResolution: { requestedTables: [], loadedTables: [], unavailableTables: [] },+ timings: { inventoryRetrievalMs: 1, candidateSelectionMs: 1, detailLoadingMs: 1, totalDurationMs: 3 },+ };+}++function contract(decisions) {+ return {+ schemaVersion: 1,+ planningMode: 'required',+ executionEligible: true,+ publisherPrefix: 'new',+ tables: Object.entries(decisions).map(([logicalName, plannedDecision]) => {+ const createsTable = ['create', 'adapt'].includes(plannedDecision);+ return {+ logicalName,+ schemaName: logicalName,+ displayName: logicalName,+ displayCollectionName: `${logicalName}s`,+ primaryIdAttribute: `${logicalName}id`,+ plannedDecision,+ ...(plannedDecision === 'adapt' ? {+ adaptedLogicalName: `${logicalName}v2`,+ adaptedSchemaName: `${logicalName}v2`,+ } : {}),+ dependencyTier: 0,+ serviceRequired: true,+ ownershipType: 'UserOwned',+ columns: createsTable ? [{+ logicalName: `${logicalName}_name`,+ schemaName: `${logicalName}_name`,+ displayName: 'Name',+ type: 'string',+ plannedDecision: 'create',+ requiredLevel: 'ApplicationRequired',+ primaryName: true,+ }] : [],+ relationships: [],+ alternateKeys: [],+ };+ }),+ };+}++test('reuse, extend, and adapt decisions request full metadata for core tables', () => {+ const result = validatePlanningDecisions(+ contract({ new_reuse: 'reuse', new_extend: 'extend', new_adapt: 'adapt' }),+ snapshot([+ table('new_reuse', 'core'),+ table('new_extend', 'full'),+ ]),+ );+ assert.equal(result.valid, false);+ assert.deepEqual(result.contextNames, ['new_adapt', 'new_reuse']);+ assert.deepEqual(result.proposedContextNames, ['new_adaptv2']);+});++test('create decisions require a checked missing proposed name', () => {+ const result = validatePlanningDecisions(+ contract({ new_create: 'create', new_defer: 'defer' }),+ snapshot([]),+ );+ assert.equal(result.valid, false);+ assert.deepEqual(result.contextNames, []);+ assert.deepEqual(result.proposedContextNames, ['new_create']);+});++test('checked missing Create and Adapt names satisfy the collision gate', () => {+ const result = validatePlanningDecisions(+ contract({ new_create: 'create', new_adapt: 'adapt' }),+ snapshot([table('new_adapt')], [+ { logicalName: 'new_create', status: 'missing', existing: null },+ { logicalName: 'new_adaptv2', status: 'missing', existing: null },+ ]),+ );+ assert.deepEqual(result, {+ valid: true,+ errors: [],+ contextNames: [],+ proposedContextNames: [],+ });+});++test('a proposed-name collision makes the approved decision invalid', () => {+ const result = validatePlanningDecisions(+ contract({ new_create: 'create' }),+ snapshot([], [+ { logicalName: 'new_create', status: 'collision', existing: {} },+ ]),+ );+ assert.equal(result.valid, false);+ assert.match(result.errors.join('; '), /new_create is not available \(collision\)/);+});++test('decision revision errors take precedence over missing-context signals', () => {+ const result = validatePlanningDecisions(+ contract({ new_reuse: 'reuse', new_create: 'create' }),+ snapshot([table('new_reuse', 'core')], [+ { logicalName: 'new_create', status: 'collision', existing: {} },+ ]),+ );+ assert.deepEqual(result.contextNames, ['new_reuse']);+ assert.deepEqual(getBlockingErrors(result), []);+ assert.deepEqual(+ getRevisionErrors(result),+ ['proposed table name new_create is not available (collision)'],+ );+});++test('validator CLI requests automatic revision before emitting context signals', (t) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'planning-decisions-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const contractPath = path.join(directory, 'contract.json');+ const snapshotPath = path.join(directory, 'snapshot.json');+ fs.writeFileSync(+ contractPath,+ JSON.stringify(contract({ new_reuse: 'reuse', new_create: 'create' })),+ );+ fs.writeFileSync(+ snapshotPath,+ JSON.stringify(snapshot([table('new_reuse', 'core')], [+ { logicalName: 'new_create', status: 'collision', existing: {} },+ ])),+ );++ const result = spawnSync(process.execPath, [+ path.resolve(__dirname, '..', 'validate-dataverse-planning-decisions.js'),+ '--contract', contractPath,+ '--snapshot', snapshotPath,+ ], { encoding: 'utf8' });++ assert.equal(result.status, 4);+ assert.match(result.stderr, /^NEEDS_REVISION: dataverse-plan-validation/m);+ assert.match(result.stderr, /new_create is not available \(collision\)/);+ assert.doesNotMatch(result.stderr, /NEEDS_CONTEXT:/);+});++test('create many-to-many relationships require a checked missing intersect name', () => {+ const source = contract({ new_left: 'create', new_right: 'create' });+ source.tables[0].relationships.push({+ kind: 'many-to-many',+ schemaName: 'new_Left_Right',+ plannedDecision: 'create',+ entity1: 'new_left',+ entity2: 'new_right',+ intersectTable: 'new_left_right',+ });+ const result = validatePlanningDecisions(+ source,+ snapshot([], [+ { logicalName: 'new_left', status: 'missing', existing: null },+ { logicalName: 'new_right', status: 'missing', existing: null },+ ]),+ );+ assert.equal(result.valid, false);+ assert.deepEqual(result.proposedContextNames, ['new_left_right']);+});++test('full evidence satisfies existing-table decisions', () => {+ const result = validatePlanningDecisions(+ contract({ new_reuse: 'reuse', new_extend: 'extend' }),+ snapshot([table('new_reuse'), table('new_extend')]),+ );+ assert.deepEqual(result, {+ valid: true,+ errors: [],+ contextNames: [],+ proposedContextNames: [],+ });+});++test('snapshot-only unverified tables require revision even without a detail failure', () => {+ const result = validatePlanningDecisions(+ contract({ new_target: 'unverified' }),+ snapshot([]),+ );+ assert.equal(result.valid, false);+ assert.deepEqual(getBlockingErrors(result), []);+ assert.deepEqual(result.contextNames, []);+ assert.deepEqual(result.proposedContextNames, []);+ assert.match(getRevisionErrors(result).join('; '), /new_target.*unverified.*defer/i);+});++test('snapshot-only unverified columns relationships and keys require revision', () => {+ for (const kind of ['columns', 'relationships', 'alternateKeys']) {+ const source = contract({ new_left: 'extend', new_right: 'reuse' });+ source.tables[0].columns.push({+ logicalName: 'new_code', schemaName: 'new_Code', displayName: 'Code',+ type: 'string', plannedDecision: 'reuse',+ });+ if (kind === 'relationships') {+ source.tables[0].relationships.push({+ kind: 'many-to-many', schemaName: 'new_Left_Right', plannedDecision: 'reuse',+ entity1: 'new_left', entity2: 'new_right', intersectTable: 'new_left_right',+ });+ } else if (kind === 'alternateKeys') {+ source.tables[0].alternateKeys.push({+ schemaName: 'new_Left_Code', plannedDecision: 'reuse', columns: ['new_code'],+ });+ }+ const component = source.tables[0][kind][0];+ component.plannedDecision = 'unverified';+ const evidence = snapshot([table('new_left'), table('new_right')]);+ const result = validatePlanningDecisions(source, evidence);+ assert.equal(result.valid, false, kind);+ assert.deepEqual(getBlockingErrors(result), [], kind);+ assert.deepEqual(result.contextNames, [], kind);+ assert.deepEqual(result.proposedContextNames, [], kind);+ assert.match(getRevisionErrors(result).join('; '), /unverified.*defer/i, kind);+ component.plannedDecision = 'defer';+ assert.equal(validatePlanningDecisions(source, evidence).valid, true, kind);+ }+});++test('unverified CLI decisions request revision instead of approval or extra discovery', (testContext) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'planning-unverified-'));+ testContext.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const contractPath = path.join(directory, 'contract.json');+ const snapshotPath = path.join(directory, 'snapshot.json');+ fs.writeFileSync(contractPath, JSON.stringify(contract({ new_target: 'unverified' })));+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot([])));+ const result = spawnSync(process.execPath, [+ path.resolve(__dirname, '..', 'validate-dataverse-planning-decisions.js'),+ '--contract', contractPath, '--snapshot', snapshotPath,+ ], { encoding: 'utf8' });+ assert.equal(result.status, 4, result.stderr);+ assert.match(result.stderr, /^NEEDS_REVISION: dataverse-plan-validation/m);+ assert.match(result.stderr, /new_target.*unverified.*defer/);+ assert.doesNotMatch(result.stderr, /NEEDS_CONTEXT:|BLOCKED:/);+});++test('attempted unavailable detail metadata must be deferred', () => {+ const failure = {+ logicalName: 'new_target',+ selectionReasons: ['concept:targets'],+ status: 500,+ error: 'metadata unavailable',+ required: false,+ };+ const invalid = validatePlanningDecisions(+ contract({ new_target: 'unverified' }),+ snapshot([], [], [failure]),+ );+ assert.equal(invalid.valid, false);+ assert.deepEqual(invalid.contextNames, ['new_target']);+ assert.match(invalid.errors.join('; '), /must be deferred/);+ assert.deepEqual(+ getRevisionErrors(invalid),+ [+ 'tables with attempted unavailable detail metadata must be deferred',+ 'table new_target is unverified; revise the decision from snapshot evidence or defer it',+ ],+ );++ const deferred = validatePlanningDecisions(+ contract({ new_target: 'defer' }),+ snapshot([], [], [failure]),+ );+ assert.deepEqual(deferred, {+ valid: true,+ errors: [],+ contextNames: [],+ proposedContextNames: [],+ });+});++function computedFixture(decision = 'reuse') {+ const source = contract({ new_item: decision });+ const column = {+ logicalName: 'new_total', schemaName: 'new_Total', type: 'computed',+ attributeType: 'Decimal', sourceType: 1, sourceTypeMask: 0,+ formulaDefinition: 'new_quantity * new_price', plannedDecision: 'reuse',+ };+ source.tables[0].columns.push(column);+ const evidence = table('new_item');+ evidence.columns.push({+ logicalName: column.logicalName, type: 'Decimal', sourceType: 1,+ computed: {+ metadataStatus: 'available', sourceType: 1, sourceTypeMask: 0,+ formulaDefinition: column.formulaDefinition,+ },+ });+ evidence.facts.columnCount = 1;+ const checks = decision === 'adapt'+ ? [{ logicalName: 'new_itemv2', status: 'missing', existing: null }]+ : [];+ return { source, evidence, checks };+}++test('required computed metadata must be available before an existing-table decision', () => {+ for (const decision of ['reuse', 'extend', 'adapt']) {+ const { source, evidence, checks } = computedFixture(decision);+ evidence.columns[0].computed.metadataStatus = 'unavailable';+ const result = validatePlanningDecisions(source, snapshot([evidence], checks));+ assert.equal(result.valid, false, decision);+ assert.deepEqual(result.contextNames, []);+ assert.match(getRevisionErrors(result).join('; '), /new_item.new_total.*defer the column/);+ }+});++test('computed evidence must match the contract and cannot claim availability with missing facts', () => {+ const { source, evidence } = computedFixture();+ assert.equal(validatePlanningDecisions(source, snapshot([evidence])).valid, true);+ for (const updates of [+ { sourceTypeMask: null }, { sourceTypeMask: 32 }, { sourceType: null },+ { formulaDefinition: '' }, { formulaDefinition: 'new_quantity + new_price' },+ ]) {+ const changed = structuredClone(evidence);+ Object.assign(changed.columns[0].computed, updates);+ const result = validatePlanningDecisions(source, snapshot([changed]));+ assert.equal(result.valid, false, JSON.stringify(updates));+ assert.ok(getRevisionErrors(result).length > 0);+ }+});++test('unused and explicitly deferred computed columns do not prevent reuse', () => {+ const { source, evidence } = computedFixture();+ evidence.columns[0].computed.metadataStatus = 'unavailable';+ source.tables[0].columns[0].plannedDecision = 'defer';+ assert.equal(validatePlanningDecisions(source, snapshot([evidence])).valid, true);+ source.tables[0].columns = [];+ assert.equal(validatePlanningDecisions(source, snapshot([evidence])).valid, true);+});++test('required computed columns on core tables request expansion before deferral', () => {+ const { source, evidence } = computedFixture();+ evidence.detailLevel = 'core';+ evidence.missingDetailClasses = ['computed-metadata'];+ evidence.columns[0].computed = null;+ const result = validatePlanningDecisions(source, snapshot([evidence]));+ assert.deepEqual(result.contextNames, ['new_item']);+ assert.deepEqual(getRevisionErrors(result), []);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.jsindex d3b38ea41..6ec90bb1a 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-planning-snapshot.test.js@@ -133,6 +133,74 @@ function validSnapshotBase(overrides = {}) {return snapshot;}+test('malformed successful metadata never becomes an empty inventory or a free name', async () => {+ const malformedBodies = [null, {}, [], { value: null }, { value: {} },+ { value: 'invalid' }, { value: [null] }, { value: ['invalid'] }];+ for (const data of malformedBodies) {+ let requests = 0;+ await assert.rejects(createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ proposedTableNames: ['new_equipment'],+ request: async () => { requests += 1; return { status: 200, data }; },+ }), /OData collection/);+ assert.equal(requests, 1);+ await assert.rejects(createReconciliationSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ tableNames: ['new_equipment'], proposedTableNames: ['new_equipment'],+ request: async () => ({ status: 200, data }),+ }), /Exact-name table metadata.*OData collection/);+ }+});++test('table metadata without valid identities cannot authorize name availability', async () => {+ for (const row of [{}, { LogicalName: null }, { LogicalName: '' },+ { LogicalName: 7 }, { LogicalName: 'bad table' }]) {+ await assert.rejects(createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ proposedTableNames: ['new_equipment'],+ request: async () => ({ status: 200, data: { value: [row] } }),+ }), /invalid table LogicalName/);+ await assert.rejects(createReconciliationSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ tableNames: ['new_equipment'], proposedTableNames: ['new_equipment'],+ request: async () => ({ status: 200, data: { value: [row] } }),+ }), /invalid table LogicalName/);+ }+});++test('malformed continuation pages stop inventory discovery before name checks', async () => {+ let requests = 0;+ await assert.rejects(createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ proposedTableNames: ['new_equipment'],+ request: async () => {+ requests += 1;+ return requests === 1 ? { status: 200, data: {+ value: [entity('new_gym', 'Gym')],+ '@odata.nextLink': 'https://example.crm.dynamics.com/api/data/v9.2/EntityDefinitions?$skiptoken=next',+ } } : { status: 200, data: {} };+ },+ }), /OData collection/);+ assert.equal(requests, 2);+ for (const nextLink of [{}, [], 7, ' ']) {+ await assert.rejects(createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ request: async () => ({ status: 200, data: { value: [], '@odata.nextLink': nextLink } }),+ }), /invalid OData continuation/);+ }+});++test('valid empty metadata collections still support create-only planning', async () => {+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com', tenantId: 'tenant-1',+ proposedTableNames: ['new_equipment'],+ request: async () => ({ status: 200, data: { value: [] } }),+ });+ assert.deepEqual(snapshot.inventory, []);+ assert.deepEqual(snapshot.proposedNameChecks.missing, ['new_equipment']);+ assert.equal(validateSnapshot(snapshot).valid, true);+});+test('concept ranking normalizes plurals and maps workflow families', () => {assert.equal(singularizeToken('activities'), 'activity');assert.equal(singularizeToken('batches'), 'batch');@@ -465,28 +533,71 @@ test('advisory candidate detail failure is recorded and does not abort the snaps});});-test('explicit candidate detail failure remains required and throws', async () => {+test('explicit candidate detail failure is recorded for a Defer decision', async () => {+ const snapshot = await 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: [] } };+ },+ });++ assert.deepEqual(snapshot.tables, []);+ assert.deepEqual(snapshot.exactNameResolution, {+ requestedTables: ['activitypointer'],+ loadedTables: ['activitypointer'],+ unavailableTables: [],+ });+ assert.deepEqual(snapshot.detailLoadFailures, [{+ logicalName: 'activitypointer',+ selectionReasons: ['concept:activities:exact-covered', 'explicit-table'],+ status: 400,+ error: 'abstract metadata type is unsupported',+ required: true,+ }]);+ assert.equal(validateSnapshot(snapshot).valid, true);+});++test('authentication failure during detail loading still requires user action', 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: [] } };+ inventory: [entity('new_product', 'Product')],+ concepts: ['products'],+ request: async () => {+ throw new Error('Failed to get Azure CLI token. Run az login first.');},}),- /activitypointer attributes failed \(400\): abstract metadata type is unsupported/,+ /Failed to get Azure CLI token/,);});-test('lookup sub-metadata failure skips advisory tables and blocks required tables', async () => {+test('transport failure during detail loading still requires retry or user action', async () => {+ const timeout = Object.assign(new Error('connect ETIMEDOUT'), { status: 0 });+ await assert.rejects(+ createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ inventory: [entity('new_product', 'Product')],+ concepts: ['products'],+ request: async () => {+ throw timeout;+ },+ }),+ /ETIMEDOUT/,+ );+});++test('lookup sub-metadata failure records both advisory and required tables', async () => {const request = async (_method, apiPath) => {if (apiPath.startsWith('EntityDefinitions?')) {return { status: 200, data: { value: [entity('new_product', 'Product')] } };@@ -517,15 +628,16 @@ test('lookup sub-metadata failure skips advisory tables and blocks required tablassert.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/,- );+ const required = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['new_product'],+ request,+ });+ assert.deepEqual(required.tables, []);+ assert.equal(required.detailLoadFailures[0].required, true);+ assert.deepEqual(required.exactNameResolution.loadedTables, ['new_product']);+ assert.equal(validateSnapshot(required).valid, true);});test('snapshot captures detailed metadata, evidence, and timing shape without network access', async () => {@@ -748,6 +860,39 @@ test('snapshot validation rejects missing decision evidence', () => {}});+test('snapshot validation requires explicit table detail and complete metadata collections', async () => {+ const loaded = await loadDetailedEntity(+ async () => ({ status: 200, data: { value: [] } }),+ entity('new_product', 'Product'),+ );+ const snapshot = validSnapshotBase({ tables: [loaded] });+ assert.equal(validateSnapshot(snapshot).valid, true);++ for (const field of [+ 'logicalName', 'schemaName', 'entitySetName', 'primaryIdAttribute',+ 'detailLevel', 'missingDetailClasses', 'columns', 'manyToOneRelationships',+ 'oneToManyRelationships', 'manyToManyRelationships', 'alternateKeys', 'facts',+ ]) {+ const malformed = structuredClone(snapshot);+ delete malformed.tables[0][field];+ assert.equal(validateSnapshot(malformed).valid, false, field);+ }+ for (const value of [null, [], 'invalid', { logicalName: 'new_product' }]) {+ assert.equal(validateSnapshot({ ...snapshot, tables: [value] }).valid, false);+ }+ for (const field of [+ 'columns', 'manyToOneRelationships', 'oneToManyRelationships',+ 'manyToManyRelationships', 'alternateKeys',+ ]) {+ const malformed = structuredClone(snapshot);+ malformed.tables[0][field] = [null];+ assert.equal(validateSnapshot(malformed).valid, false, field);+ }+ const inconsistent = structuredClone(snapshot);+ inconsistent.tables[0].facts.columnCount = 1;+ assert.equal(validateSnapshot(inconsistent).valid, false);+});+test('exact-name expansion reuses inventory and performs no broad discovery request', async () => {const calls = [];const base = validSnapshotBase({@@ -836,7 +981,10 @@ test('exact-name expansion discovers and details a managed dependency absent froassert.deepEqual(expanded.expansion.requestedTables, ['contact']);assert.deepEqual(expanded.expansion.loadedTables, ['contact']);assert.deepEqual(expanded.expansion.newlyLoadedTables, ['contact']);+ assert.deepEqual(expanded.expansion.reloadedTables, []);assert.deepEqual(expanded.expansion.unavailableTables, []);+ assert.equal(expanded.inventoryFacts.exactNameTables, 1);+ assert.equal(expanded.inventoryFacts.requiredExactNameTables, 1);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);@@ -871,24 +1019,187 @@ test('proposed-name expansion checks collisions without loading details', async});});-test('exact-name expansion fails closed when required detail metadata is unreadable', async () => {+test('cached proposed-name expansion removes a stale deleted collision', async () => {+ const staleTable = await loadDetailedEntity(+ async () => ({ status: 200, data: { value: [] } }),+ entity('new_deleted', 'Deleted'),+ );+ const base = validSnapshotBase({+ inventorySource: 'cache',+ inputs: {+ concepts: [],+ explicitTableNames: [],+ proposedTableNames: [],+ },+ inventory: [normalizeInventoryForTest(entity('new_deleted', 'Deleted'))],+ tables: [staleTable],+ detailLoadFailures: [{+ logicalName: 'new_deleted',+ selectionReasons: ['concept:deleted'],+ status: 400,+ error: 'stale cached failure',+ required: false,+ }],+ });+ const expanded = await expandSnapshot({+ snapshot: base,+ proposedTableNames: ['new_deleted'],+ request: async (_method, apiPath) => {+ assert.match(apiPath, /LogicalName eq 'new_deleted'/);+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(expanded.proposedNameChecks.missing, ['new_deleted']);+ assert.equal(expanded.inventory.some((item) => item.logicalName === 'new_deleted'), false);+ assert.equal(expanded.tables.some((item) => item.logicalName === 'new_deleted'), false);+ assert.deepEqual(expanded.detailLoadFailures, []);+ assert.equal(expanded.detailLoadSummary.failedCandidates, 0);+ assert.equal(expanded.detailLoadSummary.advisoryCandidates, 0);+ assert.equal(expanded.inventoryFacts.customizableTables, 0);+ assert.equal(expanded.inventoryFacts.proposedCollisionTables, 0);+});++test('cached detailed-name expansion reloads an existing full table live', async () => {+ let detailReads = 0;+ const staleTable = await loadDetailedEntity(+ async () => ({ status: 200, data: { value: [] } }),+ entity('new_item', 'Old item'),+ );+ const base = validSnapshotBase({+ inventorySource: 'cache',+ inputs: {+ concepts: ['items'],+ explicitTableNames: [],+ proposedTableNames: [],+ },+ inventory: [normalizeInventoryForTest(entity('new_item', 'Old item'))],+ candidateRanking: rankCandidatesByConcept(+ [entity('new_item', 'Old item')],+ ['items'],+ ),+ tables: [staleTable],+ });+ const refreshed = entity('new_item', 'Current item');+ const expanded = await expandSnapshot({+ snapshot: base,+ tableNames: ['new_item'],+ request: async (_method, apiPath) => {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [refreshed] } };+ }+ detailReads += 1;+ return { status: 200, data: { value: [] } };+ },+ });++ assert.ok(detailReads > 0);+ assert.equal(+ expanded.inventory.find((item) => item.logicalName === 'new_item').displayName,+ 'Current item',+ );+ assert.equal(+ expanded.candidateRanking[0].candidates[0].displayName,+ 'Current item',+ );+ assert.deepEqual(expanded.exactNameResolution.loadedTables, ['new_item']);+ assert.deepEqual(expanded.expansion.newlyLoadedTables, []);+ assert.deepEqual(expanded.expansion.upgradedTables, []);+ assert.deepEqual(expanded.expansion.reloadedTables, ['new_item']);+ assert.equal(expanded.inventoryFacts.exactNameTables, 0);+ assert.equal(expanded.inventoryFacts.requiredExactNameTables, 0);++ let repeatedReads = 0;+ const repeated = await expandSnapshot({+ snapshot: expanded,+ tableNames: ['new_item'],+ request: async () => {+ repeatedReads += 1;+ return { status: 200, data: { value: [] } };+ },+ });+ assert.equal(repeatedReads, 0);+ assert.deepEqual(repeated.expansion.reloadedTables, []);+});++test('old snapshots do not fabricate bounded exact discovery names', async () => {+ const base = validSnapshotBase({+ inventory: [normalizeInventoryForTest(entity('account', 'Account'))],+ inventoryFacts: {+ customizableTables: 1,+ exactNameTables: 1,+ requiredExactNameTables: 1,+ proposedCollisionTables: 0,+ totalTables: 1,+ },+ exactNameResolution: {+ requestedTables: ['account'],+ loadedTables: ['account'],+ unavailableTables: [],+ },+ });+ const expanded = await expandSnapshot({+ snapshot: base,+ request: async () => {+ throw new Error('no metadata request expected');+ },+ });+ assert.deepEqual(expanded.exactNameDiscoveryTables, []);+ assert.equal(expanded.inventoryFacts.exactNameTables, 0);+ assert.equal(expanded.inventoryFacts.requiredExactNameTables, 0);+});++test('exact-name expansion records unreadable detail metadata for Defer', async () => {const base = validSnapshotBase({inputs: { concepts: ['activities'], explicitTableNames: [], proposedTableNames: [] },inventory: [normalizeInventoryForTest(entity('activitypointer', 'Activity'))],});+ const expanded = await 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: [] } };+ },+ });++ assert.deepEqual(expanded.expansion.loadedTables, []);+ assert.deepEqual(expanded.expansion.unavailableTables, ['activitypointer']);+ assert.equal(expanded.expansion.failedDetailedCandidates, 1);+ assert.deepEqual(expanded.detailLoadFailures, [{+ logicalName: 'activitypointer',+ selectionReasons: ['explicit-expansion'],+ status: 403,+ error: 'metadata forbidden',+ required: true,+ }]);+ assert.deepEqual(expanded.exactNameResolution, {+ requestedTables: ['activitypointer'],+ loadedTables: ['activitypointer'],+ unavailableTables: [],+ });+ assert.equal(validateSnapshot(expanded).valid, true);+});++test('exact-name expansion propagates terminal authentication failures', async () => {+ const base = validSnapshotBase({+ inputs: { concepts: ['products'], explicitTableNames: [], proposedTableNames: [] },+ inventory: [normalizeInventoryForTest(entity('new_product', 'Product'))],+ });+ const unauthorized = Object.assign(new Error('token refresh failed'), { status: 401 });+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: [] } };+ tableNames: ['new_product'],+ request: async () => {+ throw unauthorized;},}),- /activitypointer attributes failed \(403\): metadata forbidden/,+ /token refresh failed/,);});@@ -939,7 +1250,8 @@ test('image metadata preserves full-image settings and its complete update definCanStoreFullImage: false,IsPrimaryImage: false,};- const table = await loadDetailedEntity(async (_method, apiPath) => {+ const imageRequests = [];+ const request = async (_method, apiPath) => {if (apiPath.includes('/Attributes?$select=')) {return { status: 200, data: { value: [{...imageDefinition,@@ -952,10 +1264,12 @@ test('image metadata preserves full-image settings and its complete update defin}] } };}if (apiPath.includes('ImageAttributeMetadata')) {+ imageRequests.push(apiPath);return { status: 200, data: { value: [imageDefinition] } };}return { status: 200, data: { value: [] } };- }, entity('new_issue', 'Issue'));+ };+ const table = await loadDetailedEntity(request, entity('new_issue', 'Issue'));const image = table.columns[0];assert.equal(image.metadataId, 'image-id');@@ -964,6 +1278,15 @@ test('image metadata preserves full-image settings and its complete update definassert.equal(image.maxHeight, 144);assert.equal(image.maxWidth, 144);assert.deepEqual(image.imageUpdateDefinition, imageDefinition);+ assert.deepEqual(imageRequests, [+ "EntityDefinitions(LogicalName='new_issue')/Attributes/Microsoft.Dynamics.CRM.ImageAttributeMetadata",+ ]);++ const coreTable = await loadDetailedEntity(request, entity('new_issue', 'Issue'), { detailLevel: 'core' });+ assert.equal(coreTable.detailLevel, 'core');+ assert.ok(coreTable.missingDetailClasses.includes('typed-constraints'));+ assert.equal(coreTable.columns[0].imageUpdateDefinition, undefined);+ assert.equal(imageRequests.length, 1);});test('CLI request creation initializes one long-lived executor for the snapshot phase', async () => {@@ -1009,6 +1332,11 @@ test('evidence renderer emits compact deterministic planning facts', () => {}],tables: [{logicalName: 'wr_animal',+ schemaName: 'wr_animal',+ entitySetName: 'wr_animals',+ primaryIdAttribute: 'wr_animalid',+ detailLevel: 'full',+ missingDetailClasses: [],customEntity: true,managed: false,customizable: true,@@ -1017,6 +1345,7 @@ test('evidence renderer emits compact deterministic planning facts', () => {oneToManyRelationships: [],manyToManyRelationships: [],alternateKeys: [],+ facts: { columnCount: 1, relationshipCount: 1, keyCount: 0 },}],proposedNameChecks: {checked: [@@ -1042,7 +1371,7 @@ test('evidence renderer emits compact deterministic planning facts', () => {assert.match(markdown, /\*\*Total\*\*.*\*\*78 ms\*\*/);});-test('evidence renderer reports skipped advisory detail failures', () => {+test('evidence renderer reports unavailable detail metadata', () => {const snapshot = validSnapshotBase({candidateRanking: [{concept: 'activities',@@ -1081,8 +1410,8 @@ test('evidence renderer reports skipped advisory detail failures', () => {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/);+ assert.match(markdown, /Unavailable detail metadata/);+ assert.match(markdown, /activitypointer.*no.*concept:activities.*400.*abstract metadata type is unsupported/);});test('atomic output replaces the target and leaves no sibling temporary file', (t) => {@@ -1094,7 +1423,7 @@ test('atomic output replaces the target and leaves no sibling temporary file', (assert.deepEqual(fs.readdirSync(directory), ['evidence.md']);});-test('planning contracts require the snapshot-only path and bounded expansion', () => {+test('planning contracts require snapshot-only and monotonic incremental expansion', () => {const pluginRoot = path.resolve(__dirname, '..', '..');const architect = fs.readFileSync(path.join(pluginRoot, 'agents', 'data-model-architect.md'),@@ -1117,16 +1446,52 @@ test('planning contracts require the snapshot-only path and bounded expansion',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(architect, /--validate-only/);+ assert.match(architect, /Do not use `Read`, `Grep`, or shell\s+output to load the full snapshot/s);+ assert.match(architect, /detailLevel: core/);+ assert.doesNotMatch(architect, /approving Gate 1|user sees it at Gate 1/);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(planner, /validate-dataverse-planning-decisions\.js/);+ assert.match(planner, /only exit `0` permits\s+embedding and Gate 2/);+ assert.match(planner, /Gate 1\s+architecture acceptance does not satisfy this data-model precondition/);+ assert.match(planner, /preserve the validator's exact stderr first line/);+ assert.match(planner, /NEEDS_REVISION: dataverse-plan-validation/);+ assert.match(planner, /Do not\s+rewrite one signal as the other/);+ assert.doesNotMatch(planner, /planning-timings\.js/);+ assert.match(createSkill, /render-dataverse-architect-evidence\.js/);+ assert.match(createSkill, /--concepts-file "\$CONCEPTS_PATH"/);+ assert.match(createSkill, /--progressive-detail/);+ assert.match(createSkill, /--combined-base-read/);+ assert.match(createSkill, /--read-concurrency 1/);+ assert.match(createSkill, /--inventory-cache "\$INVENTORY_CACHE_PATH"/);+ assert.match(createSkill, /strongCollisionCandidates/);+ assert.match(createSkill, /coreCandidates/);+ assert.match(createSkill, /validate-dataverse-planning-decisions\.js/);+ assert.match(createSkill, /same validation MUST run before Gate 2 is shown/);assert.match(createSkill, /--base-snapshot "\$SNAPSHOT_PATH"/);- assert.match(createSkill, /--proposed-tables "<exact comma-separated logical names>"/);+ assert.match(createSkill, /DETAIL_ATTEMPTED_NAMES/);+ assert.match(createSkill, /selectedTables` with `detailLevel: full`/);+ assert.match(createSkill, /detailLevel: core` is not fully attempted/);+ assert.match(createSkill, /PROPOSED_CHECKED_NAMES/);+ assert.match(createSkill, /NEEDS_CONTEXT: dataverse-plan-revision:<short-safe-classification>/);+ assert.match(createSkill, /do not[\s]+route it through the generic `NEEDS_CONTEXT` retry cap/i);+ assert.match(createSkill, /NEW_DETAIL_NAMES = requested names - DETAIL_ATTEMPTED_NAMES/);+ assert.match(createSkill, /NEW_PROPOSED_NAMES = requested names - PROPOSED_CHECKED_NAMES/);+ assert.match(createSkill, /--proposed-tables "<NEW_PROPOSED_NAMES as exact comma-separated logical names>"/);+ assert.match(createSkill, /preserve and branch on the exact stderr first line/);+ assert.match(createSkill, /On exit `4`[\s\S]*NEEDS_REVISION: dataverse-plan-validation/);+ assert.match(createSkill, /do not issue another network request/i);+ assert.match(createSkill, /No-progress fallback/);+ assert.match(createSkill, /Ask the user only when the remaining choice changes business semantics/);+ assert.doesNotMatch(createSkill, /A second detailed-metadata signal is `BLOCKED`/);+ assert.doesNotMatch(createSkill, /A second proposed-name signal is `BLOCKED`/);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, /unresolved\s+metadata never authorizes a write/s);+ assert.match(createSkill, /Ask the user only when recovery needs interactive sign-in/);+ assert.match(createSkill, /classify the affected exact or advisory table as `Defer`/);assert.match(createSkill, /10–15 minute target/);assert.doesNotMatch(snapshotScript, /execFileSync/);});diff --git a/plugins/mobile-apps/scripts/tests/dataverse-progressive-detail.test.js b/plugins/mobile-apps/scripts/tests/dataverse-progressive-detail.test.jsnew file mode 100644index 000000000..287931342--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-progressive-detail.test.js@@ -0,0 +1,300 @@+'use strict';++const assert = require('node:assert/strict');+const test = require('node:test');++const {+ createSnapshot,+ expandSnapshot,+ loadDetailedEntity,+ requestCombinedBaseMetadata,+ validateSnapshot,+} = require('../create-dataverse-snapshot');++function label(value) {+ return { UserLocalizedLabel: { Label: value } };+}++function entity(logicalName = 'new_inspection', displayName = 'Inspection') {+ return {+ LogicalName: logicalName,+ SchemaName: logicalName,+ EntitySetName: `${logicalName}s`,+ DisplayName: label(displayName),+ DisplayCollectionName: label(`${displayName}s`),+ Description: label(`${displayName} records`),+ PrimaryIdAttribute: `${logicalName}id`,+ PrimaryNameAttribute: 'new_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 },+ };+}++function attributes() {+ return [+ {+ MetadataId: 'name-id',+ LogicalName: 'new_name',+ SchemaName: 'new_Name',+ AttributeType: 'String',+ AttributeTypeName: { Value: 'StringType' },+ RequiredLevel: { Value: 'ApplicationRequired' },+ IsPrimaryName: true,+ SourceType: 0,+ },+ {+ MetadataId: 'status-id',+ LogicalName: 'new_status',+ SchemaName: 'new_Status',+ AttributeType: 'Picklist',+ AttributeTypeName: { Value: 'PicklistType' },+ SourceType: 0,+ },+ {+ MetadataId: 'site-id',+ LogicalName: 'new_siteid',+ SchemaName: 'new_SiteId',+ AttributeType: 'Lookup',+ AttributeTypeName: { Value: 'LookupType' },+ SourceType: 0,+ },+ ];+}++function fixtureRequest(calls) {+ return async (_method, apiPath) => {+ calls.push(apiPath);+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: attributes() } };+ }+ if (apiPath.includes('StringAttributeMetadata')) {+ return { status: 200, data: { value: [{ LogicalName: 'new_name', MaxLength: 200 }] } };+ }+ if (apiPath.includes('PicklistAttributeMetadata')) {+ return { status: 200, data: { value: [{+ LogicalName: 'new_status',+ OptionSet: { Options: [{ Value: 1, Label: label('Open') }] },+ }] } };+ }+ if (apiPath.includes('LookupAttributeMetadata')) {+ return { status: 200, data: { value: [{ LogicalName: 'new_siteid', Targets: ['new_site'] }] } };+ }+ return { status: 200, data: { value: [] } };+ };+}++function typedConcept() {+ return {+ phrase: 'inspection results',+ kind: 'entity',+ discoverTable: true,+ evidence: 'The brief stores inspection results.',+ };+}++test('core detail skips typed and lookup enrichment requests', async () => {+ const coreCalls = [];+ const fullCalls = [];+ const core = await loadDetailedEntity(fixtureRequest(coreCalls), entity(), {+ detailLevel: 'core',+ });+ const full = await loadDetailedEntity(fixtureRequest(fullCalls), entity());++ assert.equal(coreCalls.length, 5);+ assert.ok(fullCalls.length > coreCalls.length);+ assert.equal(core.detailLevel, 'core');+ assert.deepEqual(core.missingDetailClasses.sort(), [+ 'choice-options',+ 'lookup-targets',+ 'typed-constraints',+ ]);+ assert.deepEqual(core.columns.find((column) => column.logicalName === 'new_status').choices, []);+ assert.deepEqual(core.columns.find((column) => column.logicalName === 'new_siteid').lookupTargets, []);+ assert.equal(full.detailLevel, 'full');+ assert.deepEqual(full.missingDetailClasses, []);+ assert.deepEqual(full.columns.find((column) => column.logicalName === 'new_status').choices, [+ { value: 1, label: 'Open' },+ ]);+});++test('combined base read matches sequential normalized evidence and follows pagination', async () => {+ const sequentialCalls = [];+ const sequential = await loadDetailedEntity(fixtureRequest(sequentialCalls), entity(), {+ detailLevel: 'core',+ });+ const combinedCalls = [];+ const combined = await loadDetailedEntity(async (method, apiPath) => {+ assert.equal(method, 'GET');+ combinedCalls.push(apiPath);+ if (apiPath.includes('$expand=Attributes')) {+ return {+ status: 200,+ data: {+ LogicalName: 'new_inspection',+ Attributes: attributes().slice(0, 1),+ '[email protected]': 'https://example.crm.dynamics.com/api/data/v9.2/attribute-page-2',+ ManyToOneRelationships: [],+ OneToManyRelationships: [],+ ManyToManyRelationships: [],+ Keys: [],+ },+ };+ }+ if (apiPath === 'attribute-page-2') {+ return { status: 200, data: { value: attributes().slice(1) } };+ }+ throw new Error(`Unexpected combined request: ${apiPath}`);+ }, entity(), {+ detailLevel: 'core',+ combinedBaseRead: true,+ });++ assert.deepEqual(combined, sequential);+ assert.equal(sequentialCalls.length, 5);+ assert.equal(combinedCalls.length, 2);+});++test('combined base read fails closed on a malformed or unreadable continuation', async () => {+ await assert.rejects(+ loadDetailedEntity(async (_method, apiPath) => {+ if (apiPath.includes('$expand=Attributes')) {+ return {+ status: 200,+ data: {+ Attributes: [],+ '[email protected]': 'next-page',+ ManyToOneRelationships: [],+ OneToManyRelationships: [],+ ManyToManyRelationships: [],+ Keys: [],+ },+ };+ }+ return { status: 500, error: 'continuation unavailable' };+ }, entity(), { detailLevel: 'core', combinedBaseRead: true }),+ /continuation failed \(500\): continuation unavailable/,+ );+});++test('combined base read follows relationship continuation links', async () => {+ const result = await requestCombinedBaseMetadata(+ async (_method, apiPath) => {+ if (apiPath.includes('$expand=Attributes')) {+ return {+ status: 200,+ data: {+ Attributes: [],+ ManyToOneRelationships: [{ SchemaName: 'new_First' }],+ '[email protected]': 'https://example.crm.dynamics.com/api/data/v9.2/relationship-page-2',+ OneToManyRelationships: [],+ ManyToManyRelationships: [],+ Keys: [],+ },+ };+ }+ assert.equal(apiPath, 'relationship-page-2');+ return { status: 200, data: { value: [{ SchemaName: 'new_Second' }] } };+ },+ "EntityDefinitions(LogicalName='new_inspection')",+ 'new_inspection',+ );+ assert.deepEqual(+ result.manyToOneRelationships.map((item) => item.SchemaName),+ ['new_First', 'new_Second'],+ );+});++test('progressive typed weak candidates are core while explicit tables remain full', async () => {+ async function request(_method, apiPath) {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity()] } };+ }+ return fixtureRequest([])(_method, apiPath);+ }+ const advisory = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: [typedConcept()],+ progressiveDetail: true,+ request,+ });+ const exact = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['new_inspection'],+ concepts: [typedConcept()],+ progressiveDetail: true,+ request,+ });++ assert.equal(advisory.tables[0].detailLevel, 'core');+ assert.equal(advisory.detailLoadSummary.coreCandidates, 1);+ assert.equal(exact.tables[0].detailLevel, 'full');+ assert.equal(exact.detailLoadSummary.fullCandidates, 1);+});++test('bounded exact expansion upgrades a core table in place', async () => {+ async function request(_method, apiPath) {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: [entity()] } };+ }+ return fixtureRequest([])(_method, apiPath);+ }+ const core = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: [typedConcept()],+ progressiveDetail: true,+ request,+ });+ const expanded = await expandSnapshot({+ snapshot: core,+ tableNames: ['new_inspection'],+ request,+ });++ assert.equal(expanded.tables.length, 1);+ assert.equal(expanded.tables[0].detailLevel, 'full');+ assert.deepEqual(expanded.expansion.newlyLoadedTables, []);+ assert.deepEqual(expanded.expansion.upgradedTables, ['new_inspection']);+ assert.deepEqual(expanded.exactNameResolution.loadedTables, ['new_inspection']);+ assert.equal(validateSnapshot(expanded).valid, true);+});++test('execution reconciliation rejects core detail', async () => {+ const calls = [];+ const coreTable = await loadDetailedEntity(fixtureRequest(calls), entity(), {+ detailLevel: 'core',+ });+ const malformed = {+ version: 3,+ purpose: 'execution-reconciliation',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ generatedAt: '2026-08-28T00:00:00.000Z',+ inputs: { concepts: [], explicitTableNames: ['new_inspection'], proposedTableNames: [] },+ inventory: [{ logicalName: 'new_inspection', customizable: true }],+ inventoryFacts: { customizableTables: 1, exactNameTables: 1, requiredExactNameTables: 1, proposedCollisionTables: 0, totalTables: 1 },+ candidateRanking: [],+ selectedCandidateEvidence: [],+ tables: [coreTable],+ detailLoadFailures: [],+ detailLoadSummary: { attemptedCandidates: 1, loadedCandidates: 1, failedCandidates: 0 },+ proposedNameChecks: { checked: [], collisions: [], missing: [] },+ exactNameResolution: { requestedTables: ['new_inspection'], loadedTables: ['new_inspection'], unavailableTables: [] },+ timings: { inventoryRetrievalMs: 1, candidateSelectionMs: 0, detailLoadingMs: 1, totalDurationMs: 2 },+ };+ const validation = validateSnapshot(malformed);+ assert.equal(validation.valid, false);+ assert.ok(validation.errors.includes('tables[0] execution reconciliation requires full detail'));+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-read-concurrency.test.js b/plugins/mobile-apps/scripts/tests/dataverse-read-concurrency.test.jsnew file mode 100644index 000000000..c5b706fbd--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/dataverse-read-concurrency.test.js@@ -0,0 +1,218 @@+'use strict';++const assert = require('node:assert/strict');+const test = require('node:test');++const {+ adaptiveReadRequest,+ createSnapshot,+ mapWithConcurrency,+ parseReadConcurrency,+} = require('../create-dataverse-snapshot');+const { createDataverseRequestExecutor } = require('../dataverse-request');++function label(value) {+ return { UserLocalizedLabel: { Label: value } };+}++function entity(logicalName) {+ const displayName = logicalName.replace(/^new_/, '');+ return {+ LogicalName: logicalName,+ SchemaName: logicalName,+ EntitySetName: `${logicalName}s`,+ DisplayName: label(displayName),+ DisplayCollectionName: label(`${displayName}s`),+ Description: label(`${displayName} records`),+ PrimaryIdAttribute: `${logicalName}id`,+ PrimaryNameAttribute: 'new_name',+ OwnershipType: 'UserOwned',+ IsCustomEntity: true,+ IsManaged: false,+ IsCustomizable: { Value: true },+ CanCreateAttributes: { Value: true },+ };+}++test('mapWithConcurrency preserves input order and respects its cap', async () => {+ let active = 0;+ let maximumActive = 0;+ const result = await mapWithConcurrency([3, 2, 1, 0], 2, async (value) => {+ active += 1;+ maximumActive = Math.max(maximumActive, active);+ await new Promise((resolve) => setImmediate(resolve));+ active -= 1;+ return value * 2;+ });+ assert.equal(maximumActive, 2);+ assert.deepEqual(result, [6, 4, 2, 0]);+});++test('mapWithConcurrency honors a reduced dynamic cap before dispatching more work', async () => {+ let cap = 2;+ let releaseSecond;+ const secondBlocked = new Promise((resolve) => {+ releaseSecond = resolve;+ });+ const started = [];+ const execution = mapWithConcurrency([0, 1, 2], 2, async (value) => {+ started.push(value);+ if (value === 0) {+ cap = 1;+ return value;+ }+ if (value === 1) await secondBlocked;+ return value;+ }, { currentConcurrency: () => cap });+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(started, [0, 1]);+ releaseSecond();+ assert.deepEqual(await execution, [0, 1, 2]);+});++test('adaptive reads halve the cap after rate limiting', async () => {+ let calls = 0;+ const adaptive = adaptiveReadRequest(async () => {+ calls += 1;+ return { status: 200, rateLimited: calls <= 2 };+ }, 4);+ await adaptive.request('GET', 'one');+ assert.equal(adaptive.currentConcurrency(), 2);+ await adaptive.request('GET', 'two');+ assert.equal(adaptive.currentConcurrency(), 1);+ await adaptive.request('GET', 'three');+ assert.equal(adaptive.currentConcurrency(), 1);+});++test('adaptive reads reduce the cap before a throttled retry sleeps', async () => {+ let requestCount = 0;+ let releaseSleep;+ const sleeping = new Promise((resolve) => {+ releaseSleep = resolve;+ });+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => 'token',+ sendRequest: async () => {+ requestCount += 1;+ return requestCount === 1+ ? { statusCode: 429, body: '', headers: { 'retry-after': '1' } }+ : { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ sleep: () => sleeping,+ });+ const adaptive = adaptiveReadRequest(request, 4);+ const pending = adaptive.request('GET', 'EntityDefinitions');+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(adaptive.currentConcurrency(), 2);+ releaseSleep();+ await pending;+ assert.equal(adaptive.currentConcurrency(), 2);+});++test('read concurrency rejects invalid values and defaults to one', () => {+ assert.equal(parseReadConcurrency(undefined), 1);+ assert.equal(parseReadConcurrency('4'), 4);+ for (const value of [0, -1, 1.5, 9, 'invalid']) {+ assert.throws(() => parseReadConcurrency(value), /integer from 1 to 8/);+ }+});++test('concurrency one and four produce identical normalized snapshot evidence', async () => {+ const entities = ['new_alpha', 'new_beta', 'new_gamma', 'new_delta'].map(entity);+ const request = async (_method, apiPath) => {+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: entities } };+ }+ if (apiPath.includes('/Attributes?$select=')) {+ return { status: 200, data: { value: [{+ MetadataId: 'name-id',+ LogicalName: 'new_name',+ SchemaName: 'new_Name',+ AttributeType: 'String',+ AttributeTypeName: { Value: 'StringType' },+ IsPrimaryName: true,+ SourceType: 0,+ }] } };+ }+ if (apiPath.includes('StringAttributeMetadata')) {+ return { status: 200, data: { value: [{ LogicalName: 'new_name', MaxLength: 100 }] } };+ }+ return { status: 200, data: { value: [] } };+ };+ const options = {+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: ['alpha', 'beta', 'gamma', 'delta'],+ nowIso: () => '2026-08-28T00:00:00.000Z',+ request,+ };+ const sequential = await createSnapshot({ ...options, readConcurrency: 1 });+ const concurrent = await createSnapshot({ ...options, readConcurrency: 4 });+ assert.deepEqual(concurrent.tables, sequential.tables);+ assert.deepEqual(concurrent.candidateRanking, sequential.candidateRanking);+ assert.deepEqual(concurrent.selectedCandidateEvidence, sequential.selectedCandidateEvidence);+ assert.equal(concurrent.detailLoadSummary.readConcurrency, 4);+ assert.equal(concurrent.detailLoadSummary.finalReadConcurrency, 4);+});++test('concurrent advisory failures are recorded and all pooled requests are GET-only', async () => {+ const entities = ['new_alpha', 'new_beta'].map(entity);+ const methods = [];+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ concepts: [+ { phrase: 'alpha', kind: 'entity', discoverTable: true, evidence: 'alpha' },+ { phrase: 'beta', kind: 'entity', discoverTable: true, evidence: 'beta' },+ ],+ readConcurrency: 2,+ request: async (method, apiPath) => {+ methods.push(method);+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: entities } };+ }+ if (apiPath.includes("LogicalName='new_beta'") && apiPath.includes('/Attributes?')) {+ return { status: 500, error: 'planned advisory failure' };+ }+ return { status: 200, data: { value: [] } };+ },+ });+ assert.deepEqual(snapshot.tables.map((table) => table.logicalName), ['new_alpha']);+ assert.deepEqual(+ snapshot.detailLoadFailures.map((failure) => failure.logicalName),+ ['new_beta'],+ );+ assert.deepEqual(new Set(methods), new Set(['GET']));+});++test('concurrent required detail failures remain explicit and non-executable', async () => {+ const entities = ['new_alpha', 'new_beta'].map(entity);+ const snapshot = await createSnapshot({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ tableNames: ['new_beta'],+ readConcurrency: 2,+ request: async (method, apiPath) => {+ assert.equal(method, 'GET');+ if (apiPath.startsWith('EntityDefinitions?')) {+ return { status: 200, data: { value: entities } };+ }+ if (apiPath.includes("LogicalName='new_beta'") && apiPath.includes('/Attributes?')) {+ return { status: 500, error: 'planned required failure' };+ }+ return { status: 200, data: { value: [] } };+ },+ });++ assert.deepEqual(snapshot.tables, []);+ assert.deepEqual(snapshot.detailLoadFailures, [{+ logicalName: 'new_beta',+ selectionReasons: ['explicit-table'],+ status: 500,+ error: 'planned required failure',+ required: true,+ }]);+ assert.deepEqual(snapshot.exactNameResolution.loadedTables, ['new_beta']);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.jsindex 1195a6a37..d61121285 100644--- a/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js+++ b/plugins/mobile-apps/scripts/tests/dataverse-request-metadata-batch.test.js@@ -265,6 +265,178 @@ test('in-process request executor reuses one token across sequential metadata reassert.deepEqual(new Set(requests.map((item) => item.token)), new Set(['shared-token']));});+test('concurrent 401 responses share one token refresh', async () => {+ let tokenCalls = 0;+ const attempts = new Map();+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => {+ tokenCalls += 1;+ return tokenCalls === 1 ? 'initial' : 'refreshed';+ },+ sendRequest: async (_envUrl, _method, apiPath, _body, token) => {+ const count = (attempts.get(apiPath) || 0) + 1;+ attempts.set(apiPath, count);+ await Promise.resolve();+ return token === 'initial'+ ? { statusCode: 401, body: '', headers: {} }+ : { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ });++ const results = await Promise.all([+ request('GET', "EntityDefinitions(LogicalName='new_a')/Attributes"),+ request('GET', "EntityDefinitions(LogicalName='new_b')/Attributes"),+ ]);++ assert.equal(tokenCalls, 2);+ assert.deepEqual(results.map((result) => result.status), [200, 200]);+ assert.deepEqual([...attempts.values()], [2, 2]);+});++test('token acquisition can retry after an initial rejection', async () => {+ let tokenCalls = 0;+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => {+ tokenCalls += 1;+ if (tokenCalls === 1) throw new Error('temporary token failure');+ return 'recovered-token';+ },+ sendRequest: async () => ({ statusCode: 200, body: '{"value":[]}', headers: {} }),+ });++ await assert.rejects(request('GET', 'first'), /temporary token failure/);+ const recovered = await request('GET', 'second');++ assert.equal(recovered.status, 200);+ assert.equal(tokenCalls, 2);+});++test('a slow request cannot restore a token replaced by a concurrent refresh', async () => {+ let tokenCalls = 0;+ let releaseSlow;+ let markSlowStarted;+ const slowStarted = new Promise((resolve) => {+ markSlowStarted = resolve;+ });+ const slowRelease = new Promise((resolve) => {+ releaseSlow = resolve;+ });+ const seen = [];+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => {+ tokenCalls += 1;+ return tokenCalls === 1 ? 'old' : 'new';+ },+ sendRequest: async (_envUrl, _method, apiPath, _body, token) => {+ seen.push([apiPath, token]);+ if (apiPath === 'slow') {+ markSlowStarted();+ await slowRelease;+ return { statusCode: 200, body: '{"value":[]}', headers: {} };+ }+ if (apiPath === 'refresh' && token === 'old') {+ return { statusCode: 401, body: '', headers: {} };+ }+ return { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ });++ const slow = request('GET', 'slow');+ await slowStarted;+ assert.equal((await request('GET', 'refresh')).status, 200);+ releaseSlow();+ assert.equal((await slow).status, 200);+ assert.equal((await request('GET', 'third')).status, 200);++ assert.equal(tokenCalls, 2);+ assert.deepEqual(seen.at(-1), ['third', 'new']);+});++test('an older refresh retry cannot replace a newer refreshed token', async () => {+ let tokenCalls = 0;+ let releaseFirstRetry;+ let markFirstRetryStarted;+ const firstRetryStarted = new Promise((resolve) => {+ markFirstRetryStarted = resolve;+ });+ const firstRetryRelease = new Promise((resolve) => {+ releaseFirstRetry = resolve;+ });+ const seen = [];+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => ['t0', 't1', 't2'][tokenCalls++],+ sendRequest: async (_envUrl, _method, apiPath, _body, token) => {+ seen.push([apiPath, token]);+ if (apiPath === 'first' && token === 't0') {+ return { statusCode: 401, body: '', headers: {} };+ }+ if (apiPath === 'first' && token === 't1') {+ markFirstRetryStarted();+ await firstRetryRelease;+ return { statusCode: 200, body: '{"value":[]}', headers: {} };+ }+ if (apiPath === 'second' && token === 't1') {+ return { statusCode: 401, body: '', headers: {} };+ }+ return { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ });++ const first = request('GET', 'first');+ await firstRetryStarted;+ assert.equal((await request('GET', 'second')).status, 200);+ releaseFirstRetry();+ assert.equal((await first).status, 200);+ assert.equal((await request('GET', 'third')).status, 200);++ assert.equal(tokenCalls, 3);+ assert.deepEqual(seen.at(-1), ['third', 't2']);+});++test('staggered stale 401 responses reuse the token already refreshed by a peer', async () => {+ let tokenCalls = 0;+ let markRefreshed;+ const refreshed = new Promise((resolve) => {+ markRefreshed = resolve;+ });+ const attempts = new Map();+ const request = createDataverseRequestExecutor({+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: 'tenant-1',+ getToken: async () => {+ tokenCalls += 1;+ if (tokenCalls === 2) markRefreshed();+ return tokenCalls === 1 ? 'old' : 'new';+ },+ sendRequest: async (_envUrl, _method, apiPath, _body, token) => {+ const attempt = (attempts.get(apiPath) || 0) + 1;+ attempts.set(apiPath, attempt);+ if (token === 'old') {+ if (apiPath !== 'request-0') await refreshed;+ return { statusCode: 401, body: '', headers: {} };+ }+ return { statusCode: 200, body: '{"value":[]}', headers: {} };+ },+ });++ const results = await Promise.all(Array.from(+ { length: 5 },+ (_, index) => request('GET', `request-${index}`),+ ));++ assert.equal(tokenCalls, 2);+ assert.deepEqual(results.map((result) => result.status), [200, 200, 200, 200, 200]);+ assert.deepEqual([...attempts.values()], [2, 2, 2, 2, 2]);+});+test('metadata transport loss is uncertain and mutation is not retried', async () => {let requests = 0;const result = await runOneMetadataOperation(diff --git a/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.jsindex f4bc135a2..60682a9b3 100644--- a/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js+++ b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js@@ -22,9 +22,12 @@ function tempDirectory(name) {return fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));}-function copyTemplate() {+function copyTemplate(sourceRoot = templateRoot) {const projectRoot = tempDirectory('mobile-template');- fs.cpSync(templateRoot, projectRoot, { recursive: true });+ fs.cpSync(sourceRoot, projectRoot, {+ recursive: true,+ filter: (source) => path.basename(source) !== 'node_modules',+ });fs.mkdirSync(path.join(projectRoot, 'node_modules', 'expo'), { recursive: true });return projectRoot;}@@ -74,6 +77,18 @@ function assertSnapshotsEqual(left, right) {}}+test('template test fixtures exclude installed dependencies and local dependency caches', (context) => {+ const sourceRoot = tempDirectory('mobile-template-source');+ context.after(() => fs.rmSync(sourceRoot, { recursive: true, force: true }));+ fs.writeFileSync(path.join(sourceRoot, 'package.json'), '{"name":"fixture"}\n');+ fs.mkdirSync(path.join(sourceRoot, 'node_modules', '.cache'), { recursive: true });+ fs.writeFileSync(path.join(sourceRoot, 'node_modules', '.cache', 'local-run.txt'), 'not template source');+ const projectRoot = copyTemplate(sourceRoot);+ context.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ assert.equal(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'), '{"name":"fixture"}\n');+ assert.deepStrictEqual(fs.readdirSync(path.join(projectRoot, 'node_modules')), ['expo']);+});+test('preparation is idempotent and preserves generated and existing helper files', () => {const projectRoot = copyTemplate();const tsconfigPath = path.join(projectRoot, 'tsconfig.json');diff --git a/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js b/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.jsnew file mode 100644index 000000000..07d679001--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js@@ -0,0 +1,245 @@+'use strict';++const assert = require('assert');+const fs = require('fs');+const os = require('os');+const path = require('path');+const { spawnSync } = require('child_process');+const test = require('node:test');++const {+ describeResponseShape,+ formatRequestFailure,+ main,+ parseArgs,+ redactDiagnostic,+ resolveEnvironment,+ writeCacheIfProject,+} = require('../resolve-environment');++const resolverPath = path.resolve(__dirname, '../resolve-environment.js');++test('no-cache mode permits reads but performs no filesystem writes', (t) => {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-no-cache-'));+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ const authPath = path.join(projectRoot, 'auth.config.json');+ fs.writeFileSync(authPath, `${JSON.stringify({ msal: { clientId: '', tenantId: '' } }, null, 2)}\n`);+ const before = fs.readFileSync(authPath);+ const previousCwd = process.cwd();++ try {+ process.chdir(projectRoot);+ const wrote = writeCacheIfProject({+ environmentId: '11111111-1111-1111-1111-111111111111',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: '22222222-2222-2222-2222-222222222222',+ }, { noCache: true });+ assert.strictEqual(wrote, false);+ assert.deepStrictEqual(fs.readFileSync(authPath), before);+ assert.ok(!fs.existsSync(path.join(projectRoot, '.resolved-environment.json')));+ } finally {+ process.chdir(previousCwd);+ }+});++test('resolver argument parsing accepts no-cache in either position', () => {+ const id = '11111111-1111-1111-1111-111111111111';+ assert.deepStrictEqual(parseArgs([id, '--no-cache']), { noCache: true, target: id });+ assert.deepStrictEqual(parseArgs(['--no-cache', id]), { noCache: true, target: id });+});++test('resolver accepts required-tenant and help options and rejects unknown flags', () => {+ const id = '11111111-1111-1111-1111-111111111111';+ for (const args of [+ [id, '--no-cache', '--require-tenant'],+ ['--require-tenant', '--no-cache', id],+ ]) {+ assert.deepStrictEqual(parseArgs(args), { noCache: true, target: id, requireTenant: true });+ }+ for (const help of ['--help', '-h']) {+ assert.deepStrictEqual(parseArgs([help]), { noCache: false, target: null, help: true });+ }+ for (const args of [['--typo'], ['--typo', id], [id, '--typo'], ['--help', '--typo']]) {+ assert.throws(() => parseArgs(args), /Unknown option: --typo/);+ }+ assert.throws(() => parseArgs([id, id]), /Unknown argument/);+});++test('resolver help and invalid options exit without resolving or writing project files', (testContext) => {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-cli-options-'));+ testContext.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ const target = '11111111-1111-1111-1111-111111111111';+ const run = (args) => spawnSync(process.execPath, [resolverPath, ...args], {+ cwd: projectRoot,+ encoding: 'utf8',+ timeout: 5000,+ env: { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ });+ for (const args of [['--help'], ['-h'], [target, '--no-cache', '--require-tenant', '--help']]) {+ const result = run(args);+ assert.strictEqual(result.status, 0, result.stderr);+ assert.match(result.stdout, /Usage:.*<environment-url-or-id>/);+ assert.match(result.stdout, /--require-tenant/);+ assert.match(result.stdout, /Existing identity metadata may still be read/);+ assert.strictEqual(result.stderr, '');+ }+ for (const args of [['--typo'], [target, '--typo']]) {+ const result = run(args);+ assert.strictEqual(result.status, 1, result.stderr);+ assert.match(result.stderr, /^Unknown option: --typo/);+ assert.strictEqual(result.stdout, '');+ }+ assert.deepStrictEqual(fs.readdirSync(projectRoot), []);+});++test('required-tenant mode rejects incomplete resolution before emitting JSON', async (testContext) => {+ const environmentResolution = require('../lib/environment-resolution');+ let resolved;+ const resolution = testContext.mock.method(environmentResolution, 'resolveEnvironment', async () => resolved);+ const output = testContext.mock.method(console, 'log', () => {});+ const environment = {+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: '22222222-2222-2222-2222-222222222222',+ };+ const args = ['11111111-1111-1111-1111-111111111111', '--no-cache', '--require-tenant'];+ for (const incomplete of [+ null,+ {},+ { environmentUrl: environment.environmentUrl },+ { tenantId: environment.tenantId },+ { ...environment, tenantId: null },+ { ...environment, tenantId: ' ' },+ { ...environment, tenantId: 42 },+ { ...environment, environmentUrl: '' },+ ]) {+ resolved = incomplete;+ await assert.rejects(main(args), /Could not resolve a Dataverse environment URL and tenant ID/);+ }+ assert.strictEqual(output.mock.callCount(), 0);+ resolved = environment;+ await main(args);+ assert.strictEqual(output.mock.callCount(), 1);+ assert.deepStrictEqual(JSON.parse(output.mock.calls[0].arguments[0]), environment);+ assert.deepStrictEqual(resolution.mock.calls[0].arguments[3], {+ noCache: true, target: args[0], requireTenant: true,+ });+});++test('resolver export retains project lookup while the CLI requires an explicit target', async (t) => {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-export-'));+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ const environment = {+ environmentId: '11111111-1111-1111-1111-111111111111',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: '22222222-2222-2222-2222-222222222222',+ };+ fs.writeFileSync(path.join(projectRoot, 'power.config.json'), JSON.stringify({+ environmentId: environment.environmentId,+ }));+ for (const allowLegacyCache of [false, true]) {+ const cached = allowLegacyCache ? environment : {+ ...environment, clusterEnvironment: 'Prod', clusterGeoName: 'EU',+ };+ fs.writeFileSync(path.join(projectRoot, '.resolved-environment.json'), JSON.stringify(cached));+ const result = await resolveEnvironment(null, projectRoot, allowLegacyCache);+ assert.strictEqual(result.environmentId, environment.environmentId);+ assert.strictEqual(result.environmentUrl, environment.environmentUrl);+ assert.strictEqual(result.source, 'cache');+ }+ const cli = spawnSync(process.execPath, [resolverPath, '--no-cache'], {+ cwd: projectRoot,+ encoding: 'utf8',+ timeout: 5000,+ env: { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ });+ assert.strictEqual(cli.status, 1, cli.stderr);+ assert.match(cli.stderr, /Usage:.*<environment-url-or-id>/);+ assert.strictEqual(cli.stdout, '');+});++test('resolver CLI and exported API leave cached project files byte-identical in no-cache mode', async (t) => {+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-cli-no-cache-'));+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ const environment = {+ environmentId: '11111111-1111-1111-1111-111111111111',+ environmentUrl: 'https://example.crm.dynamics.com',+ tenantId: '22222222-2222-2222-2222-222222222222',+ };+ const authPath = path.join(projectRoot, 'auth.config.json');+ const appPath = path.join(projectRoot, 'app.json');+ const cachePath = path.join(projectRoot, '.resolved-environment.json');+ fs.writeFileSync(path.join(projectRoot, 'power.config.json'), JSON.stringify({+ environmentId: environment.environmentId,+ }));+ fs.writeFileSync(appPath, JSON.stringify({+ expo: { extra: { telemetry: { appInstanceId: environment.environmentId, cluster: null } } },+ }));+ const appBefore = fs.readFileSync(appPath);++ for (const clusterMetadata of [{}, { clusterEnvironment: 'Prod', clusterGeoName: 'EU' }]) {+ const cached = { ...environment, ...clusterMetadata };+ const authConfig = {+ msal: { clientId: '', tenantId: '' },+ environment: cached,+ };+ fs.writeFileSync(authPath, `${JSON.stringify(authConfig, null, 2)}\n`);+ const before = fs.readFileSync(authPath);+ for (const existingSidecar of [false, true]) {+ if (existingSidecar) fs.writeFileSync(cachePath, JSON.stringify(cached));+ const filesBefore = fs.readdirSync(projectRoot).sort();+ const result = spawnSync(+ process.execPath,+ [resolverPath, environment.environmentId, '--no-cache', '--require-tenant'],+ {+ cwd: projectRoot,+ encoding: 'utf8',+ timeout: 5000,+ env: { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ },+ );+ assert.strictEqual(result.status, 0, result.stderr);+ const exportedResult = await resolveEnvironment(null, projectRoot, false, { noCache: true });+ assert.deepStrictEqual(exportedResult, JSON.parse(result.stdout));+ assert.deepStrictEqual(fs.readFileSync(authPath), before);+ assert.deepStrictEqual(fs.readFileSync(appPath), appBefore);+ assert.deepStrictEqual(fs.readdirSync(projectRoot).sort(), filesBefore);+ assert.strictEqual(JSON.parse(result.stdout).source, 'cache');+ assert.strictEqual(JSON.parse(result.stdout).clusterGeoName, clusterMetadata.clusterGeoName || null);+ if (existingSidecar) {+ assert.strictEqual(fs.readFileSync(cachePath, 'utf8'), JSON.stringify(cached));+ fs.unlinkSync(cachePath);+ }+ }+ }+});++test('HTTP diagnostics report status and safe response shape without body contents', () => {+ const cases = [+ [401, {}, 'empty object'],+ [403, { error: { code: 'Forbidden', message: 'secret response detail' } }, 'object keys [error]'],+ [404, null, 'null body'],+ [500, 'not-json-secret', 'text(15)'],+ ];++ for (const [statusCode, data, shape] of cases) {+ const message = formatRequestFailure('Environment lookup failed', { statusCode, data });+ assert.match(message, new RegExp(`HTTP ${statusCode}`));+ assert.match(message, new RegExp(shape.replace(/[()[\]]/g, '\\$&')));+ assert.doesNotMatch(message, /secret response detail|not-json-secret/);+ }+});++test('diagnostic redaction removes bearer tokens, JWTs, and token query values', () => {+ const jwt = `eyJ${'a'.repeat(24)}.${'b'.repeat(24)}.${'c'.repeat(12)}`;+ const redacted = redactDiagnostic(+ `Bearer abc.def.ghi ${jwt} https://example.test?access_token=top-secret`,+ );+ assert.doesNotMatch(redacted, /abc\.def\.ghi|top-secret|eyJ/);+ assert.match(redacted, /\[redacted\]/);+});++test('response shape distinguishes empty, malformed, and structured payloads', () => {+ assert.strictEqual(describeResponseShape({}), 'empty object');+ assert.strictEqual(describeResponseShape('bad-json'), 'text(8)');+ assert.strictEqual(describeResponseShape({ error: {}, traceId: 'x' }), 'object keys [error, traceId]');+});diff --git a/plugins/mobile-apps/scripts/tests/resolve-environment.test.js b/plugins/mobile-apps/scripts/tests/resolve-environment.test.jsindex 2599e4288..976fe8153 100644--- a/plugins/mobile-apps/scripts/tests/resolve-environment.test.js+++ b/plugins/mobile-apps/scripts/tests/resolve-environment.test.js@@ -290,4 +290,18 @@ test('resolveClusterEnvironment refreshes legacy metadata, skips saved lookups,assert.equal(await resolveClusterEnvironment(root), null);assert.equal(requests.length, 2);assert.deepEqual(JSON.parse(fs.readFileSync(appPath, 'utf8')), app);++ offline = false;+ const readOnlyEnvironmentId = '33333333-3333-4333-8333-333333333333';+ const beforeReadOnly = [appPath, authPath, powerPath].map(filePath => fs.readFileSync(filePath));+ const readOnlyResult = await resolverModule.exports.resolveEnvironment(+ readOnlyEnvironmentId, root, false, { noCache: true },+ );+ assert.equal(readOnlyResult.source, 'environment-id');+ assert.equal(readOnlyResult.environmentId, readOnlyEnvironmentId);+ assert.equal(readOnlyResult.clusterEnvironment, 'Prod');+ assert.equal(readOnlyResult.clusterGeoName, 'US');+ assert.equal(requests.length, 3);+ assert.equal(fs.existsSync(cachePath), false);+ assert.deepEqual([appPath, authPath, powerPath].map(filePath => fs.readFileSync(filePath)), beforeReadOnly);});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/validate-dataverse-planning-decisions.js b/plugins/mobile-apps/scripts/validate-dataverse-planning-decisions.jsnew file mode 100644index 000000000..0e9e70890--- /dev/null+++ b/plugins/mobile-apps/scripts/validate-dataverse-planning-decisions.js@@ -0,0 +1,233 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { derivedExpected, isComputedColumn, validateContract } = require('./build-dataverse-operation-manifest');+const { compareDerivedColumn } = require('./lib/derived-metadata');+const { validateSnapshot } = require('./create-dataverse-snapshot');++const FULL_DETAIL_DECISIONS = new Set(['reuse', 'extend', 'adapt']);+const CONTEXT_GATE_ERRORS = new Set([+ 'reuse, extend, and adapt decisions require full Dataverse detail evidence',+ 'create and adapt decisions require proposed-name collision evidence',+]);++function normalize(value) {+ return String(value || '').trim().toLowerCase();+}++function getBlockingErrors(result) {+ return result.errors.filter(+ (error) => error.startsWith('contract: ') || error.startsWith('snapshot: '),+ );+}++function getRevisionErrors(result) {+ return result.errors.filter(+ (error) => (+ !CONTEXT_GATE_ERRORS.has(error)+ && !error.startsWith('contract: ')+ && !error.startsWith('snapshot: ')+ ),+ );+}++function validatePlanningDecisions(contract, snapshot) {+ const errors = [];+ const contextNames = new Set();+ const fullDetailContextNames = new Set();+ const proposedContextNames = new Set();+ const contractValidation = validateContract(contract);+ if (!contractValidation.valid) {+ errors.push(...contractValidation.errors.map((error) => `contract: ${error}`));+ }+ const snapshotValidation = validateSnapshot(snapshot);+ if (!snapshotValidation.valid) {+ errors.push(...snapshotValidation.errors.map((error) => `snapshot: ${error}`));+ }+ if (errors.length > 0) {+ return {+ valid: false,+ errors,+ contextNames: [],+ proposedContextNames: [],+ };+ }++ const detailed = new Map(snapshot.tables.map((table) => [normalize(table.logicalName), table]));+ const unavailableDetails = new Set(+ (snapshot.detailLoadFailures || []).map((failure) => normalize(failure.logicalName)),+ );+ const deferRequiredNames = new Set();+ const proposedChecks = new Map(+ (snapshot.proposedNameChecks?.checked || []).map(+ (check) => [normalize(check.logicalName), normalize(check.status)],+ ),+ );+ for (const table of contract.tables || []) {+ const decision = normalize(table.plannedDecision);+ // Unverified remains valid for legacy discovery contracts, but a trusted+ // snapshot requires a grounded decision or explicit deferral before approval.+ for (const [kind, components] of [+ ['table', [table]],+ ['column', table.columns || []],+ ['relationship', table.relationships || []],+ ['alternate key', table.alternateKeys || []],+ ]) {+ for (const component of components) {+ if (normalize(component.plannedDecision) !== 'unverified') continue;+ const name = component.logicalName || component.schemaName;+ errors.push(`${kind} ${name} is unverified; revise the decision from snapshot evidence or defer it`);+ }+ }+ if (unavailableDetails.has(normalize(table.logicalName)) && decision !== 'defer') {+ contextNames.add(table.logicalName);+ deferRequiredNames.add(table.logicalName);+ }+ if (FULL_DETAIL_DECISIONS.has(decision)) {+ const evidence = detailed.get(normalize(table.logicalName));+ if (!evidence || evidence.detailLevel !== 'full') {+ contextNames.add(table.logicalName);+ fullDetailContextNames.add(table.logicalName);+ } else {+ for (const column of table.columns || []) {+ if (!isComputedColumn(column) || normalize(column.plannedDecision) === 'defer') continue;+ const liveColumn = evidence.columns.find(+ (item) => normalize(item.logicalName) === normalize(column.logicalName),+ );+ const computed = liveColumn?.computed;+ const label = `required computed column ${table.logicalName}.${column.logicalName}`;+ if (computed?.metadataStatus !== 'available'+ || !Number.isInteger(computed.sourceType) || ![1, 2, 3].includes(computed.sourceType)+ || !Number.isInteger(computed.sourceTypeMask) || computed.sourceTypeMask < 0+ || typeof computed.formulaDefinition !== 'string' || !computed.formulaDefinition.trim()) {+ errors.push(`${label} has unavailable metadata; defer the column or revise the requirement`);+ continue;+ }+ const comparison = compareDerivedColumn(derivedExpected(table.logicalName, column), {+ ...computed,+ type: liveColumn.type,+ });+ if (!comparison.compatible) {+ errors.push(`${label} does not match its metadata: ${comparison.reasons.join('; ')}`);+ }+ }+ }+ }+ if (decision === 'create' || decision === 'adapt') {+ const effectiveName = decision === 'adapt' ? table.adaptedLogicalName : table.logicalName;+ const status = proposedChecks.get(normalize(effectiveName));+ if (!status) {+ proposedContextNames.add(effectiveName);+ } else if (status !== 'missing') {+ errors.push(`proposed table name ${effectiveName} is not available (${status})`);+ }+ }+ for (const relationship of table.relationships || []) {+ const relationshipDecision = normalize(relationship.plannedDecision);+ if (relationship.kind !== 'many-to-many'+ || !['create', 'adapt'].includes(relationshipDecision)) continue;+ const effectiveIntersect = relationshipDecision === 'adapt'+ ? relationship.adaptedIntersectTable+ : relationship.intersectTable;+ const status = proposedChecks.get(normalize(effectiveIntersect));+ if (!status) {+ proposedContextNames.add(effectiveIntersect);+ } else if (status !== 'missing') {+ errors.push(+ `proposed intersect table name ${effectiveIntersect} is not available (${status})`,+ );+ }+ }+ }+ return {+ valid: contextNames.size === 0 && proposedContextNames.size === 0 && errors.length === 0,+ errors: [+ ...(fullDetailContextNames.size === 0+ ? []+ : ['reuse, extend, and adapt decisions require full Dataverse detail evidence']),+ ...(deferRequiredNames.size === 0+ ? []+ : ['tables with attempted unavailable detail metadata must be deferred']),+ ...(proposedContextNames.size === 0+ ? []+ : ['create and adapt decisions require proposed-name collision evidence']),+ ...errors,+ ],+ contextNames: [...contextNames].sort((left, right) => left.localeCompare(right)),+ proposedContextNames: [...proposedContextNames]+ .filter(Boolean)+ .sort((left, right) => left.localeCompare(right)),+ };+}++function parseArgs(argv) {+ const args = {};+ for (let index = 2; index < argv.length; index += 1) {+ if (argv[index] === '--contract') args.contract = argv[++index];+ else if (argv[index] === '--snapshot') args.snapshot = argv[++index];+ else if (argv[index] === '--json') args.json = true;+ }+ return args;+}++function main(argv = process.argv) {+ const args = parseArgs(argv);+ if (!args.contract || !args.snapshot) {+ process.stderr.write(+ 'Usage: node validate-dataverse-planning-decisions.js '+ + '--contract <json> --snapshot <json> [--json]\n',+ );+ return 2;+ }+ try {+ const contract = JSON.parse(fs.readFileSync(path.resolve(args.contract), 'utf8'));+ const snapshot = JSON.parse(fs.readFileSync(path.resolve(args.snapshot), 'utf8'));+ const result = validatePlanningDecisions(contract, snapshot);+ if (args.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ const blockingErrors = getBlockingErrors(result);+ if (blockingErrors.length > 0) {+ blockingErrors.forEach((error) => process.stderr.write(`${error}\n`));+ return 2;+ }+ const revisionErrors = getRevisionErrors(result);+ if (revisionErrors.length > 0) {+ process.stderr.write('NEEDS_REVISION: dataverse-plan-validation\n');+ revisionErrors.forEach((error) => process.stderr.write(`${error}\n`));+ return 4;+ }+ if (result.contextNames.length > 0) {+ process.stderr.write(+ `NEEDS_CONTEXT: detailed-dataverse-metadata:${result.contextNames.join(',')}\n`,+ );+ return 3;+ }+ if (result.proposedContextNames.length > 0) {+ process.stderr.write(+ `NEEDS_CONTEXT: proposed-dataverse-names:${result.proposedContextNames.join(',')}\n`,+ );+ return 3;+ }+ if (!result.valid) {+ result.errors.forEach((error) => process.stderr.write(`${error}\n`));+ return 2;+ }+ if (!args.json) process.stdout.write('Dataverse planning decisions have full evidence.\n');+ return 0;+ } catch (error) {+ process.stderr.write(`validate-dataverse-planning-decisions: ${error.message}\n`);+ return 2;+ }+}++if (require.main === module) process.exitCode = main();++module.exports = {+ CONTEXT_GATE_ERRORS,+ FULL_DETAIL_DECISIONS,+ getBlockingErrors,+ getRevisionErrors,+ main,+ validatePlanningDecisions,+};\ No newline at end of filediff --git a/plugins/mobile-apps/skills/add-dataverse/SKILL.md b/plugins/mobile-apps/skills/add-dataverse/SKILL.mdindex 097d88b6c..158541a4c 100644--- a/plugins/mobile-apps/skills/add-dataverse/SKILL.md+++ b/plugins/mobile-apps/skills/add-dataverse/SKILL.md@@ -499,17 +499,40 @@ This retains prior checkpoint bindings/tables as integrity-protected history,keeps earlier successful tables publication-pending, and maps only thejournal-proven failed collision table to its revised in-contract alias. Itfails 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.+change definition: completed tables/inline columns, extension columns, image+configuration PUTs, relationships (including cascade behavior), and alternate keys must each map+to an equivalent revised structured component. Completed image PUTs retain their+full hash-bound definitions only when the revised image requirements remain+compatible; they stay publication-pending without replaying the update. 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. Reusedcomputed 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+unsupported projections are explicit `defer` rows. After the `publish` phase succeeds, delete the publish checkpoint and invalidate the planning-only inventory cache:++```bash+node -e "const checkpoint = process.argv[1]; if (checkpoint) require('node:fs').rmSync(checkpoint, { force: true });" \+ "${PUBLISH_CHECKPOINT:-}"+if ! node "${PLUGIN_ROOT}/scripts/dataverse-inventory-cache.js" \+ --file "<working_dir>/.tmp/dataverse-inventory-cache.json" --invalidate; then+ printf 'NEEDS_RECOVERY: dataverse-inventory-cache\n' >&2+ exit 2+fi+```++**Cache-invalidation recovery (both publish paths):** a nonzero exit returns+control to the foreground agent for local recovery, not success. Diagnose the+cache path or filesystem permission error and allow at most two targeted retries+of the invalidation command. Preserve the successful publish result and execution+journal; do not replay metadata writes or publish to repair a local cache failure.+Do not reuse the failed cache or continue to service generation, verification,+sample data, or offline setup until invalidation exits `0`. If local recovery+cannot complete, report the remaining blocker and resume this cleanup after it is+resolved; never mark the phase complete just because publication succeeded.++Only after successful invalidation continue to Step 6. When there were zero writes and no checkpoint,+continue without deleting anything. Skip thefallback mutation instructions in Steps 5a–5d and skip Step 6b because publishwas already part of the validated phase order.@@ -1082,6 +1105,20 @@ Build the entity list from all tables that were **created or extended** in StepsIf the publish call returns a non-2xx status, report the error and stop — do not proceed. The user must resolve before the tables are usable.+After a 2xx publish, invalidate the planning-only inventory cache before+verification so a later planning run cannot reuse pre-publication inventory:++```bash+if ! node "${PLUGIN_ROOT}/scripts/dataverse-inventory-cache.js" \+ --file "<working_dir>/.tmp/dataverse-inventory-cache.json" --invalidate; then+ printf 'NEEDS_RECOVERY: dataverse-inventory-cache\n' >&2+ exit 2+fi+```++Apply the same cache-invalidation recovery rule from the validated publish path+above. Continue to Step 6c only after invalidation exits `0`.+### Step 6c — Verify tables exist**Telemetry checkpoint: `verify_dataverse_schema`**diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.mdindex ec945c460..8e667a291 100644--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md@@ -175,7 +175,9 @@ the block below. Connector-only runs set`$DETECTED_PUBLISHER_PREFIX = ""` and make no Dataverse prefix query.```bash-node "${PLUGIN_ROOT}/scripts/detect-publisher-prefix.js" "$ACTIVE_ENV_URL" --tenant-id "$ACTIVE_TENANT_ID"+PUBLISHER_PREFIX_JSON=$(node "${PLUGIN_ROOT}/scripts/detect-publisher-prefix.js" \+ "$ACTIVE_ENV_URL" --tenant-id "$ACTIVE_TENANT_ID")+echo "$PUBLISHER_PREFIX_JSON"```Output is one line of JSON, e.g.:@@ -227,7 +229,7 @@ downstream planning must retain platform-specific behavior for each.**App slug is auto-derived** from the display name (`slugify(displayName)` — kebab-case, ASCII-only, strip non-alphanumerics). Do NOT ask the user; the derived slug is correct >95% of the time. Show the resolved slug as part of Step 2c's plan preview so the user can override via `edit` if needed.-**Environment override branch:** If the user picks "use a different environment", ask for the Power Platform environment ID via `AskUserQuestion`, then run `scripts/resolve-environment.js` again and refresh `$ACTIVE_ENV_ID` / `$ACTIVE_ENV_URL` / `$ACTIVE_TENANT_ID`.+**Environment override branch:** If the user picks "use a different environment", ask for the Power Platform environment ID via `AskUserQuestion`, then run `scripts/resolve-environment.js <id> --no-cache` again and refresh `$ACTIVE_ENV_ID` / `$ACTIVE_ENV_URL` / `$ACTIVE_TENANT_ID`. Do not persist the selection before Step 2c approval.**App-name collision pre-flight.** Once `<displayName>` is fixed, check the chosen env for a name collision:@@ -374,7 +376,7 @@ Set tentative defaults (the preview preference applies at Step 6.75):| Tables | Distinct nouns in confirmed brief | `count(unique_nouns) × [0.7, 1.3]` rounded | low — architect may merge or split || Connectors | Connector keywords in the confirmed brief | `len(candidates)` | low — Gate 1 confirms the actual list || Screens | Confirmed features in brief | `count(features) × [2, 3]` | low — depends on navigation choice |-| 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 |+| 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 2 data-model 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 |@@ -432,10 +434,11 @@ Proceed, edit brief, or abort? [proceed/edit/abort]>> 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+> seconds of starting metadata work after Gate 1 approval. 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+> percentages. If Gate 2 has not surfaced after 15 minutes of data-model planning, inspect the last> applicable milestone before interrupting."### Step 2d — Template-only mode@@ -493,11 +496,16 @@ call `detect-publisher-prefix.js`.### Foreground Dataverse planning snapshot and evidence-Planning stays read-only. Branch on the Gate 1-approved+Planning stays read-only. The resolver's `--no-cache` mode may read existing+identity metadata, but must not persist the environment cache, auth settings,+or telemetry cluster, and must not replay pending telemetry. Normal resolution+in Step 4 retains those post-approval behaviors.++Branch on the Gate 1-approved`<dataverse_planning_mode>`:- `connector-only` — skip every command in this section. Set `SNAPSHOT_PATH`- and `EVIDENCE_PATH` to empty/not supplied, print+ and `ARCHITECT_EVIDENCE_PATH` to empty/not supplied, print`↷ Foreground planning snapshot skipped — the confirmed brief is connector-only.`, andcontinue to planner dispatch. Connector-only planning does not performDataverse metadata reads; the skill's existing global prerequisites remain@@ -507,19 +515,29 @@ Planning stays read-only. Branch on the Gate 1-approvednested planner or architect rediscover the tenant.```bash-PLANNING_ENV_JSON=$(node "${PLUGIN_ROOT}/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+node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$ACTIVE_ENV_ID" --no-cache --require-tenant+```++The command validates both required fields before returning JSON. On exit `0`,+use its `environmentUrl` as `$ACTIVE_ENV_URL` and `tenantId` as+`$ACTIVE_TENANT_ID` in the following commands, replacing the previous values.+Read these fields directly from the structured command result; do not run+separate JSON-extraction commands. On a nonzero exit, follow foreground+recovery below and do not create a snapshot or reuse stale environment values.++Build `<working_dir>/.tmp/dataverse-concepts.json` as a JSON array of typed+concepts from the confirmed brief and Gate 1-approved architecture. Account for+approved native capture/storage targets. Discover only app-owned Dataverse+records or explicitly approved Dataverse projections; exclude connector-owned+records from Dataverse candidate selection. Each item has `phrase`, `kind`,+`discoverTable`, and a short `evidence` quote. Use `kind: entity` and+`discoverTable: true` only for a plausible persistent business record with an+independent lifecycle; classify people/actors as `role`, fields as `attribute`,+workflow verbs as `action`, enum values as `status`, and operating limits as+`constraint`, all with `discoverTable: false`. Preserve multiword/header-child+families such as `medical assessments`, `care activities`, `release events`,+`custody transfers`, `test results`, and `evidence attachments`. Do not turn+every noun into an entity merely to increase recall. Add known standard orrequired-existing logical names to `<EXPLICIT_TABLES>`. Build`<PROPOSED_TABLES>` from the detected publisher prefix for every clearlyproposed custom table so collisions and missing names are explicit; leave a@@ -532,58 +550,106 @@ Detailed advisory discovery is quality-bounded:capacity.- A concept credibly covered by an exact table does not receive speculativeadvisory 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.+- Every typed entity concept receives its primary candidate and at most one+ ambiguity candidate. Roles, attributes, actions, statuses, and constraints+ never trigger table discovery.+- A lower-ranked proposed-name collision is promoted only when its display+ phrase strongly matches a multiword entity concept.+- Strong exact/suffix/contains matches and explicit/collision candidates load+ full details. Weak advisory candidates load `core` details and cannot+ authorize Reuse, Extend, or Adapt until bounded expansion upgrades them.+- Inventory-only alternatives remain available for bounded exact-name+ expansion, at most once per newly selected logical name.```bashSNAPSHOT_PATH="<working_dir>/.tmp/dataverse-foreground-planning-snapshot.json"-EVIDENCE_PATH="<working_dir>/.tmp/dataverse-planning-evidence.md"+CONCEPTS_PATH="<working_dir>/.tmp/dataverse-concepts.json"+ARCHITECT_EVIDENCE_PATH="<working_dir>/.tmp/dataverse-architect-evidence.json"+INVENTORY_CACHE_PATH="<working_dir>/.tmp/dataverse-inventory-cache.json"-node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \+run_dataverse_planning_attempt() {+if ! node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \--env-url "$ACTIVE_ENV_URL" \--tenant-id "$ACTIVE_TENANT_ID" \--output "$SNAPSHOT_PATH" \- --concepts "<DATAVERSE_CONCEPTS>" \+ --concepts-file "$CONCEPTS_PATH" \--tables "<EXPLICIT_TABLES>" \- --proposed-tables "<PROPOSED_TABLES>"+ --proposed-tables "<PROPOSED_TABLES>" \+ --progressive-detail \+ --combined-base-read \+ --read-concurrency 1 \+ --inventory-cache "$INVENTORY_CACHE_PATH"; then+ printf 'NEEDS_RECOVERY: dataverse-snapshot\n' >&2+ return 2+fi-node "${PLUGIN_ROOT}/scripts/render-dataverse-planning-evidence.js" \+if ! node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \--snapshot "$SNAPSHOT_PATH" \- --output "$EVIDENCE_PATH"+ --output "$ARCHITECT_EVIDENCE_PATH" \+ || ! node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \+ --snapshot "$SNAPSHOT_PATH" --output "$ARCHITECT_EVIDENCE_PATH" --validate-only; then+ printf 'NEEDS_RECOVERY: dataverse-evidence\n' >&2+ return 2+finode -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(`✓ Candidate selection: ${s.candidateRanking.length} concepts → ${d.attemptedCandidates} detailed (${d.primaryCandidates || 0} primary, ${d.ambiguityCandidates || 0} ambiguity, ${d.strongCollisionCandidates || 0} strong collision, ${d.deferredCandidates || 0} deferred; ${t.candidateSelectionMs} ms)`);+ console.log(`✓ Detail loading: ${d.loadedCandidates} loaded (${d.coreCandidates || 0} core, ${d.fullCandidates || 0} full), ${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.+' "$SNAPSHOT_PATH" || return 2+echo "✓ Compact architect evidence: $ARCHITECT_EVIDENCE_PATH"+}+run_dataverse_planning_attempt+```++`--combined-base-read` loads attributes, three relationship collections, and+alternate keys through one entity-definition GET per selected table, following+any nested continuation links before normalization. Typed constraints, choices,+lookup targets, and computed metadata remain separate full-detail GETs.+`--read-concurrency 1` is the production default. Concurrency `2` through `8`+is an explicit operator choice only; metadata writes are never sent+through this read worker pool. The inventory cache stores inventory-level facts+only, has a five-minute TTL, fails open on corruption or identity mismatch, and+is never read by `--reconcile-exact`. After any metadata publish, invalidate it+with `dataverse-inventory-cache.js --file "$INVENTORY_CACHE_PATH" --invalidate`.++**Foreground recovery, not agent termination.** A nonzero command result or+`NEEDS_RECOVERY` returns control to the foreground agent. Keep working on the+failure; only dependent summaries, architect dispatch, approval, and mutation+wait for trustworthy evidence. This also applies to environment resolution,+token acquisition, transport access, broad inventory, exact-name identity+resolution, parsing, and evidence validation failures in this step.++- Diagnose the actual error, then repair recoverable project-local command,+ path, or concept-input mistakes. Let the request executor handle its bounded+ transient retries; do not launch parallel retry loops or repeat an unchanged+ permanent error. Invalid cached or old-format metadata is regenerated from+ live reads, never edited into apparent validity.+- After a targeted repair, rerun `run_dataverse_planning_attempt` (or+ rerun the block with that invocation if the shell function is unavailable).+ Allow at most two repair-and-retry attempts per failing stage. Re-resolve the+ selected environment first if resolution failed.+- Resume automatically only after the current attempt succeeds and its fresh+ snapshot and matching evidence validate. File existence is not success:+ prior artifacts can survive a failed atomic write. Never substitute stale+ evidence, invent metadata, change the selected account/environment, relax+ validation, or downgrade a requirement to make the check pass.+- Ask the user only when recovery needs interactive sign-in, missing privileges,+ an explicit scope decision, or the bounded repairs are exhausted. Preserve+ the working context and resume this stage after that blocker is resolved;+ a recoverable command failure alone is not terminal `BLOCKED`.+- Individual table-detail failures do not stop planning. Keep the snapshot,+ record each failure in `detailLoadFailures`, list it in the evidence+ appendix, and classify the affected exact or advisory table as `Defer` at+ Gate 2 unless the user chooses a materially different business design.+- `Defer` is non-executable. Step 8 still requires fresh complete evidence for+ every approved `Reuse`, `Extend`, `Create`, or `Adapt` operation; unresolved+ metadata never authorizes a write.- `--proposed-tables` performs collision checks only. Missing proposed namesare not required-table failures and must never be selected for detail loadingsolely because they were proposed.@@ -596,15 +662,14 @@ milestone ID once with its counts and elapsed time. The first environment orsnapshot milestone must be visible within 30 seconds. The foregroundorchestrator 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).+For `required`, pass `SNAPSHOT_PATH` and `ARCHITECT_EVIDENCE_PATH` verbatim to+the planner prompt and every direct `data-model-architect` fallback/revision.+The model reads the compact sidecar, not the full snapshot; deterministic tools+retain the full snapshot for hash binding and validation. A supplied matching+pair 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.**Hard rule — planner writes are restricted during Step 3.** The planner (and any sub-agents it spawns) is permitted to write to **only**:@@ -649,7 +714,7 @@ Prompt:Dataverse planning mode: <required | connector-only>Dataverse planning failure reason: noneNormalized 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>+ Compact Dataverse architect evidence: <absolute ARCHITECT_EVIDENCE_PATH verbatim for required; otherwise NOT SUPPLIED>Structured schema contract: <absolute`<working_dir>/.tmp/dataverse-schema-contract.json` for required; otherwiseNOT SUPPLIED>@@ -698,8 +763,10 @@ Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:**MUST forward the approved architecture in the direct architect prompt.**Include the exact Gate 1-approved native capabilities and connectors. In- `required`, also forward `SNAPSHOT_PATH` and `EVIDENCE_PATH` verbatim and do- not resolve the environment or run Dataverse discovery again. A+ `required`, pass `Dataverse planning mode: required` and forward+ `SNAPSHOT_PATH` and `ARCHITECT_EVIDENCE_PATH` verbatim. The full snapshot is+ validator input only; read only the compact evidence. Do not resolve the+ environment or run Dataverse discovery again. A`connector-only` run never dispatches this architect.**MUST forward `$DETECTED_PUBLISHER_PREFIX` from Step 1.7 in the architect prompt:** *"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`).@@ -709,6 +776,14 @@ Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:A draft Markdown section without that sidecar is not an executable Gate 2result.+ Before presenting Gate 2, run+ `validate-dataverse-planning-decisions.js --contract <contract> --snapshot <snapshot>`.+ Apply the native planner's Step 5 decision-validation handling: preserve the+ exact metadata signal on exit `3`, revise against the same compact evidence+ on exit `4`, and permit approval only on exit `0`. This check also applies to+ every direct revision and the fully-inline fallback; architecture approval+ never substitutes for data-model approval.+**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. **Prepare and approve screens in order.** Create the `native-app-plan.md` skeleton@@ -766,8 +841,9 @@ Then execute, in order, using your own `EnterPlanMode` + `AskUserQuestion`:If the orchestrator's OWN `Task` tool is unavailable (rare — would mean evenleaf agents cannot be spawned), fall further to fully-inline mode. Draft andapprove native capabilities, connectors, and data platform first. In-`required`, then draft the data model from `SNAPSHOT_PATH` plus `EVIDENCE_PATH`-with no live OData probe and write/normalize the same structured schema+`required`, then draft the data model from `ARCHITECT_EVIDENCE_PATH`, using+`SNAPSHOT_PATH` only through deterministic validation. With no live OData probe,+write/normalize the same structured schemacontract required by `agents/data-model-architect.md`. In `connector-only`,write an explicit zero-table/no-Dataverse `## Data Model` section and nocontract or Data Model gate. Then draft the screen graph + specs against@@ -811,19 +887,57 @@ For all other first lines, use the plugin-wide protocol in[`AGENTS.md`](${PLUGIN_ROOT}/AGENTS.md) rule #12 for every `Task` return.`DONE` continues after output validation; `DONE_WITH_CONCERNS:` surfaces andqueues concerns for the memory bank; `NEEDS_CONTEXT:` re-dispatches with missing-context, capped at 2 retries; `BLOCKED:` reports the blocker. Unknown first+non-Dataverse context, capped at 2 retries; `BLOCKED:` reports the blocker. Unknown firstlines are malformed. Recoverable artifact/input failures return to theirowning phase for repair; they never authorize skipping an applicable gate.+The structured Dataverse signals below use monotonic name tracking or+deterministic revision instead of the generic retry cap. In `required` only,+initialize two in-memory sets from the current validated snapshot before+handling either metadata signal:++- `DETAIL_ATTEMPTED_NAMES` — every logical name already present in+ `selectedTables` with `detailLevel: full`,+ `exactNameResolution.unavailableTables`, or `detailLoadFailures`. A+ `selectedTables` entry with `detailLevel: core` is not fully attempted and+ remains eligible for one full-detail expansion.+- `PROPOSED_CHECKED_NAMES` — every logical name in+ `proposedNameChecks.checked`.++Expansion is monotonic: each network request contains only names not already in+the applicable set, and no expansion reruns broad inventory discovery. There+is no fixed expansion-round count. Continue automatically while the planner+identifies new exact names derived from the approved brief or current evidence.+Every re-dispatch preserves the approved architecture and `complete` phase;+metadata recovery does not reopen Gate 1 or change connector ownership.++**Data-model deterministic revision:** when the planner returns+`NEEDS_CONTEXT: dataverse-plan-revision:<short-safe-classification>`, do not+route it through the generic `NEEDS_CONTEXT` retry cap. Immediately run the+existing inline data-model revision path with the same snapshot, compact+evidence, and approved architecture. Perform no metadata read and ask no user+question. Reclassify known collisions or attempted unavailable detail as+`Reuse`, `Extend`, `Adapt`, or `Defer` as the verified evidence permits,+regenerate and validate the contract, and then present Gate 2. Ask the user+only if the remaining alternatives change business semantics.+**Data-model exact-name expansion:** when the planner or direct architectreturns exactly`NEEDS_CONTEXT: detailed-dataverse-metadata:<logical names>`, sort andde-duplicate those names. This signal is valid only in `required` mode with avalidated base snapshot, whether it came from the planner or the directarchitect 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:+Compute `NEW_DETAIL_NAMES = requested names - DETAIL_ATTEMPTED_NAMES`.++- If `NEW_DETAIL_NAMES` is non-empty, perform the exact foreground expansion+ below for only those names. Reuse the existing snapshot inventory and do not+ run another broad inventory query.+- If it is empty, do not issue another network request. Re-dispatch with the+ explicit fact that every requested name was already attempted. The architect+ must use the current full evidence, or classify an unavailable/incompatible+ dependency as `Defer`. It may ask the user only when a genuine business+ choice remains, such as choosing between a shared existing system of record+ and a new app-owned table.```bashnode "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \@@ -831,11 +945,13 @@ node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \--tenant-id "$ACTIVE_TENANT_ID" \--base-snapshot "$SNAPSHOT_PATH" \--output "$SNAPSHOT_PATH" \- --tables "<exact comma-separated logical names>"+ --tables "<NEW_DETAIL_NAMES as exact comma-separated logical names>" \+ --combined-base-read \+ --read-concurrency 1-node "${PLUGIN_ROOT}/scripts/render-dataverse-planning-evidence.js" \+node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \--snapshot "$SNAPSHOT_PATH" \- --output "$EVIDENCE_PATH"+ --output "$ARCHITECT_EVIDENCE_PATH"node -e 'const s=require(process.argv[1]);@@ -850,15 +966,26 @@ node -e '```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.+immediately, add every attempted name to `DETAIL_ATTEMPTED_NAMES`, then+re-dispatch the same planner or architect with the same+snapshot/architect-evidence paths. A later detail signal is handled by the same+set-difference rule. Never repeat a name, broaden concepts, or defer exact+validation to mutation.**Data-model proposed-name expansion:** when the planner or direct architectreturns exactly`NEEDS_CONTEXT: proposed-dataverse-names:<logical names>`, sort and de-duplicatethose names. This signal is valid only in `required` mode with a validated-snapshot. Perform one collision-only foreground expansion:+snapshot. Compute+`NEW_PROPOSED_NAMES = requested names - PROPOSED_CHECKED_NAMES`.++- If `NEW_PROPOSED_NAMES` is non-empty, perform the collision-only foreground+ expansion below for only those names.+- If it is empty, do not issue another network request. Re-dispatch with the+ existing present/missing results. A checked-missing name can support+ `Create`; a collision must be reconciled as `Reuse`, `Extend`, or `Adapt`.+ If `Adapt` produces a new final logical name, that new name flows through+ this same set-difference rule automatically.```bashnode "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \@@ -866,18 +993,30 @@ node "${PLUGIN_ROOT}/scripts/create-dataverse-snapshot.js" \--tenant-id "$ACTIVE_TENANT_ID" \--base-snapshot "$SNAPSHOT_PATH" \--output "$SNAPSHOT_PATH" \- --proposed-tables "<exact comma-separated logical names>"+ --proposed-tables "<NEW_PROPOSED_NAMES as exact comma-separated logical names>" \+ --combined-base-read \+ --read-concurrency 1-node "${PLUGIN_ROOT}/scripts/render-dataverse-planning-evidence.js" \+node "${PLUGIN_ROOT}/scripts/render-dataverse-architect-evidence.js" \--snapshot "$SNAPSHOT_PATH" \- --output "$EVIDENCE_PATH"+ --output "$ARCHITECT_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.+as required existing tables or load their details. Add every checked name to+`PROPOSED_CHECKED_NAMES` and re-dispatch. Later proposed-name signals use the+same set-difference rule. If a collision is found and the architect needs+compatibility facts, it may request incremental+`detailed-dataverse-metadata` for that existing table.++**No-progress fallback:** if an agent repeats a metadata signal containing only+already-attempted names after receiving the explicit no-new-names instruction,+do not block the create flow for another metadata retry. Run the existing+inline data-model revision path against the current compact evidence. Preserve+safe decisions, classify unresolved required-existing or incompatible targets+as `Defer`, regenerate and validate the contract, and present the result at+Gate 2. Ask the user only when the remaining choice changes business semantics;+do not ask merely because metadata is unavailable.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.@@ -891,7 +1030,7 @@ INDUSTRY_CONFIRM_REQUESTED: <inferred-industry>|<reason-code>|<top-3-alternativeExample: `INDUSTRY_CONFIRM_REQUESTED: productivity|no-keywords|field-ops,healthcare,e-commerce`-This fires before Gate 1 — it's not a gate, just a confidence check so the wrong industry doesn't silently lock in the design language for the entire app.+This fires during the completion pass before screen planning — it's not a gate, just a confidence check so the wrong industry doesn't silently lock in the design language for the entire app.**Skip this section if `<design_vibe_opt_in>` is `yes`, `done`, `deferred`, or`skip`**. The normal create flow uses `deferred`, so `/design-system` owns the@@ -1002,11 +1141,29 @@ test -f "$WORKING_DIR/.tmp/dataverse-schema-contract.json"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"-```--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.+node "${PLUGIN_ROOT}/scripts/validate-dataverse-planning-decisions.js" \+ --contract "$WORKING_DIR/.tmp/dataverse-schema-contract.json" \+ --snapshot "$SNAPSHOT_PATH"+```++The same validation MUST run before Gate 2 is shown in the planner and inline+paths. On exit `3`, preserve and branch on the exact stderr first line:+`NEEDS_CONTEXT: detailed-dataverse-metadata:<sorted-names>` uses the incremental+detail set-difference path, while+`NEEDS_CONTEXT: proposed-dataverse-names:<sorted-names>` uses the separate+incremental collision-check path. Never rewrite one signal as the other or+repeat a network request for an already-attempted name.+On exit `4`, preserve+`NEEDS_REVISION: dataverse-plan-validation` plus its safe error lines and route+them through the existing planner/direct-architect revision path with the same+snapshot and compact evidence. This path performs no metadata read and asks no+user question. If the same conflict survives re-dispatch, use the inline+data-model revision path; ask the user only when choosing among materially+different business designs. Exit `2` is reserved for an invalid+contract/snapshot artifact and is `BLOCKED`. Do not approve Reuse, Extend, or+Adapt from `core` or missing detail, or Create/Adapt names without+checked-missing collision evidence. Do not fall back to parsing the Markdown+ER diagram when a sidecar is missing or malformed.### Step 4 — Auth & environment selection@@ -2525,6 +2682,9 @@ Data model : <N tables — M reuse, K extend, L create>Native caps : <list>Connectors : <list>Screens : <N total — M from template, K built in parallel>+Planning : metadata <N ms> | local <N ms> | architect <N ms> | screens <N ms>+Approval wait : <N ms> (excluded from agent performance)+Execution : scaffold <N ms or not recorded> | mutation <N ms or not recorded>App Insights : <enabled for selected customer-owned resource | disabled>Dev server : Metro running on port <port>Debug logs : .powernative/metro-logs/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.mddeleted file mode 100644index 3b30f8bf7..000000000--- a/plugins/mobile-apps/skills/create-mobile-app/references/dataverse-planning-benchmark.md+++ /dev/null@@ -1,31 +0,0 @@-# 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.