A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps: dashboard ownership, teardown safety, routing description and form section moves (#619)
Akshay Maloo288a5c818325
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex a9fed88e4..c8dd690b2 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -207,6 +207,18 @@ the pipeline and delegates each script's **behavioral spec** to the entries belothis looked unavailable for a long time. Best-effort: the feature rolls out by tenant, so a failurewarns and records `created.newLook: false` rather than failing an otherwise-good build or reportinga silent success.+ **`app.aiDescription` (the routing description) is written only when the spec sets it** — at create,+ and on an existing app when it differs from the fetched draft, riding that run's app push. The+ platform may author this text itself, so an omitted field is never written or blanked. A 412 on the+ appmodule row over an UNPUBLISHED header change (componentstate 1, proven by a draft read) halts with+ `app-header-unpublished` — publish, then re-run — after resetting the workspace copy, which a plain+ re-fetch would otherwise refuse to replace (`LOCAL_EDITS_WOULD_BE_LOST`). A 412 on the sitemap is a+ concurrent edit even then (the push writes the header first, so its own write left that layer). Any+ other failed push that carried the change resets the copy too — except a concurrent edit+ (`VERSION_CONFLICT` / a code-less 412), where the unrecorded copy is what stops a blind re-run — and+ without the pages phase the change is applied only after the live-page gate, so a gate halt leaves+ nothing behind; a page-backed app's standalone header push refuses a copy still holding an earlier+ run's unpushed edits (`app-copy-unpushed-edits`) rather than replay them.**DATA-MODEL Dataverse labels are stamped with the ORGANIZATION's base language, not a hardcoded1033.** `resolveLanguageCode` (`scripts/lib/entity-provision.js`) reads `organization.languagecode`once per build and threads it into every label-emitting SDK call in that phase (tables, columns,@@ -347,14 +359,20 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloThe empty solution container goes last — but a **built-insystem solution** (`Active`/`Default`/`Basic`) is **skipped** (Dataverse 400s any delete of a restrictedsolution), so a downloaded spec whose real solution could not be recovered (and defaulted to `Default`)- still tears down cleanly instead of erroring. Command teardown+ still tears down cleanly instead of erroring. It is also **kept while any earlier step failed**:+ dashboards are found by name, and the app's own are the ones its solution holds (a built-in container+ holds every dashboard, so with no real solution teardown deletes none), which makes the solution the+ only proof a re-run has — deleted after a failure, the retry kept the app's dashboards for good. A+ membership read that fails is itself a failed step, never a skip or a not-found (as either, the+ solution was deleted right after it). Command teardownremoves the whole command bar for an entity the spec authored commands on (the SDK models a command barper entity, not per button). Every id is resolved from a spec-declared name/logical/uniquename via anexact-match OData filter, so it can never wildcard-scan an org. **Dry-run by default** (`--apply`writes); best-effort continue (a failed step is recorded, teardown proceeds). A not-found (already-gone)error is treated as deleted, the table delete's **not-found-on-success** is tolerated (`tolerateNotFound`),and system/managed artifacts that cannot be deleted are recorded as `skipped` rather than failing.- `--clear-workspace` prunes `.maker-workspace/` after a clean apply. `planTeardown(spec)` is pure (dry-run ++ `--clear-workspace` prunes `.maker-workspace/` after a clean apply (not while another teardown of it+ still holds the changed-only fence). `planTeardown(spec)` is pure (dry-run +unit-test surface); reuses `appUniqueName`/`commandsByEntity`/`topoOrderEntities` from the build engine (DRY).- **`scripts/download-model-app.js` → `scripts/lib/hydrate-spec.js`** — the **edit flow**: pulls a*deployed* app back into an editable App Spec + page code (sitemap → `appShell` with icons, **every**@@ -419,7 +437,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloa downgrade there silently stops custom nav icons from round-tripping. Recovered **tables are flagged`existing: true`**, so a teardown of a downloaded spec never deletes a table (+ its data) this buildcannot prove it created — download can't distinguish app-created from merely-referenced tables, so it- fails safe (an orphaned table is recoverable; deleted customer data is not).+ fails safe (an orphaned table is recoverable; deleted customer data is not). The **same flag is set on+ every recovered relationship and global choice** and teardown honours it for all three (#587 item 6):+ deleting a relationship strips its lookup column off a retained table, and an option set is org-wide.+ An app in **several unmanaged solutions** is never resolved to one of them (#587 item 9): Dataverse+ has no "owning" solution, a rebuild adds to the spec's solution and teardown deletes it, and the+ app-name heuristic is the unreliable guess above. The spec keeps `Default` (never torn down), the+ download names the candidates in `solutionCandidates` and scopes its inventory by all of them, and+ keeps a publisher prefix only when every candidate's publisher agrees. A membership that cannot be+ read is reported as such — business rules and solution-owned global choices become "unknown" —+ rather than read as "no solution".Edit the downloaded spec and re-run the build (idempotent) — create and edit share one path. Alwayspull fresh at the start of an edit session (the build reads an etag; a write against an artifactchanged in Maker throws a version conflict → re-pull, never clobber). **Classic DashBoard subareas@@ -455,7 +482,18 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloview's **column set** (parsed from `layoutxml` — the additive `reconcileView` won't drop a removed speccolumn, so this flags it), plus **relationship** and **command-bar existence** (previously unchecked).Content checks are additive + reader-gated (they only fire when the reader supplies `layoutxml` /- `entityRelationships` / `commandBar`), so existence-only callers are unaffected. It also reconciles+ `entityRelationships` / `commandBar`), so existence-only callers are unaffected. **Dashboards** are+ checked too (#586): each declared dashboard must exist. A name can also match another app's+ dashboard, so when it matches several, verify checks the one the app's solution holds — the one the+ build reuses (`dashboardsInSolution`, shared with the build and teardown) — and fails only when the+ solution cannot single one out. All three find the candidates with `findDashboardsByName`: the+ vendored lookup reads one page of ten in no defined order, so a full page is re-read in full and the+ app's own cannot sort out of sight. The sitemap subarea check asks the same question (one lookup per+ name, shared), so the two cannot pick different dashboards — it used to take the first match, and live+ a same-named dashboard of another app sorted first and failed a correctly wired nav entry. When the reader supplies `dashboardComponents`, every chart tile's+ visualization and view must belong to the tile's `TargetEntityType` — the cross-wiring a same-named+ chart on another table produced. A tile whose owner rows cannot be read is reported unverified, not+ passed. It also reconciles**AI app features**: for every `ai.appFeatures` entry it proves an APP-SCOPE OVERRIDE ROW exists in`appsettings` holding the requested value. Verify previously had no awareness of `spec.ai` at all, soa run whose every AI feature was skipped (admin gate off) or silently not persisted still reported a@@ -663,7 +701,7 @@ scripts/content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only)classify-changes.js ← changed-only: classify a spec diff → fast (page-content) | full | noop + sticky debtapply-snapshot.js ← changed-only: pure eligibility state machine (identity bind, debt, tombstone, generation CAS)- apply-snapshot-store.js ← changed-only: atomic snapshot write + workspace lease + invalidate/tombstone/delete+ apply-snapshot-store.js ← changed-only: atomic snapshot write + workspace lease + invalidate/claim/tombstone/delete + distrust markerapply-snapshot-index.js ← changed-only: build result.created → snapshot artifact mapworkspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanupchanged-only-flow.js ← changed-only: --changed-only orchestration (decide fast/full, live identity, snapshot lifecycle)diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex fce029b81..6f9229cf1 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -12,6 +12,14 @@ downloads that round-trip Choice columns.### Added+- **`app.aiDescription` — a routing description for agents** ([#583]). The text an orchestrator reads+ to choose between sibling apps over the same tables, kept apart from the tile's `app.description`.+ It is written to the platform's `appmodule.aiappdescription` at create, and on an existing app when+ it differs. A download carries it back, and `--verify` checks it. Leave it out and the build never+ touches the deployed value. If the app has an unpublished change in Maker, the build halts and tells+ you to publish first, rather than failing with a remedy that cannot work. A workspace copy of the app+ holding an earlier run's unpushed edits — an interrupted build, say — is refused before anything is+ applied, rather than pushed along with this run's changes, and a failed push of the app resets it.- **`personas[].excludes[]` records what the app deliberately leaves out** ([#583]), rendered as**Deliberately out of scope** beside the traceability table. Documentary only.- **Richer form layouts**: multi-column tabs (`tabs[].columns[]` with a `width`), cell@@ -29,6 +37,17 @@ downloads that round-trip Choice columns.### Fixed+- **A named form section moves to the tab the spec puts it in.** A section found elsewhere on the+ deployed form — dragged in Maker, or moved in the spec — used to be updated where it stood, so the+ build succeeded, the section stayed in the old tab, and `--verify` failed the form. It is now moved+ (the same section, fields and all), and a neighbour with the same label can no longer take it over.+ A section of yours that shares its name with the engine's own host (`section_notes`) never takes+ the timeline or a sub-grid host — by name, label or position, and even after a maker added a field to+ the host: it gets a section of its own. With notes on, the timeline no longer takes over a+ `section_notes` of yours, or a section a maker added, either — their fields stay put, and an existing+ form gets its timeline too — and a section you declared with no fields keeps its name even after a+ maker puts a web resource or sub-grid in it. An emptied copy of a section you named like a generated+ one (`section_1_0`) is no longer reported with advice to give it a name.- **A page NAME can no longer forge the page listing.** The "Found N pages" summary was matchedanywhere in pac's output, so a page called `Found 1 generated page` made a listing with no realsummary read as authoritative — and a truncated-but-authoritative listing is what drives a@@ -181,6 +200,66 @@ downloads that round-trip Choice columns.- **An `already-exists` halt names the step that clears it.** A plain re-run keeps the workspace copythat was never recorded as pushed and halts again; the message now says to delete `.maker-workspace`first.+- **Same-named charts on different tables no longer cross-wire a dashboard tile** ([#586]). A tile+ plotted one table's chart over another table's view. Chart identity now includes its table; a tile+ whose view name exists on several tables must say which with `entity`, and verify checks that each+ chart tile's chart and view belong to the tile's table — on the published dashboard: one with+ unpublished changes is reported unverified, and the tiles are read into a throwaway workspace, never+ through the build's copy, which may hold unpushed edits. A draft saved and put back while the tiles are+ read is caught too, by the draft's version rather than its content.+- **Two dashboards whose names Dataverse treats as one are refused** ([#586]) — it compares names+ ignoring case, accents and trailing spaces — because a rebuild would collapse them into one and drop+ the other from the nav. A download withholds such a pair and says why, and it withholds a dashboard+ whose name cannot be read rather than naming it after its sitemap title.+- **A dashboard belongs to the app through the app's solution** ([#586]). A name can also match another+ app's dashboard, and teardown used to delete every match. It now deletes only the dashboards the app's+ solution holds, none when the spec has no real solution to ask, and keeps the solution while any step+ failed — a solution it could not read counts as one — so a re-run can still tell. When several+ match, the build reuses the solution's own or halts instead of reusing an arbitrary one, and verify+ checks that same one — including the sitemap entry that opens it, which took the first match and+ failed a correctly wired app. A dashboard the build cannot add to its solution is removed again+ rather than left outside it; if that fails too, the build halts naming it and does not auto-retry,+ since a retry would reuse it outside the solution. A lone match outside the solution is still reused+ (a downloaded app's dashboard may never have joined the solution that holds the app), and the build+ now warns that nothing proves it is this app's rather than another app's namesake.+- **A Choice written as a label, its translation, or its number is one sample-data key** ([#586]). The+ loader always saw them that way; the spec gate compared them as written, so a duplicate passed it+ and the seed then failed after tables and forms had deployed. A Choice column with no `schemaName`+ on a table with sample data is now reported by name instead of crashing validation.+- **A download reports only the app's own global choices as not round-tripped** ([#586]) — the ones+ its solution owns or its columns bind — instead of every unmanaged option set in the environment.+- **A teardown fences any `--changed-only` run already in flight** ([#587]). Its tombstone kept the+ snapshot's generation, so a run that had read the snapshot first could re-bless it over the+ tombstone. A first build, which has no snapshot yet, is fenced too: it claims one before it builds,+ and a teardown tombstones even a workspace with none. When two teardowns of one workspace overlap,+ the fence stays until the last of them finishes, a `--changed-only` build waits while one is still+ running — and a build that cannot resolve its live identity also refuses when one began while it was+ looking — and `--clear-workspace` leaves a workspace that still holds the fence. Teardown now also+ **refuses to delete anything when it cannot write that fence**, instead of warning and carrying on.+ The workspace lease that guards the fence is never taken from a holder that is still alive, however+ long it has held it: one paused mid-write, on a machine that slept, would otherwise commit its stale+ view over the fence when it resumed. An old lease names the file to delete if its holder's pid was+ reused by another process, and so does a reclaim of it abandoned by a crash: it is never removed by+ another writer, which let two writers hold the lease. `--clear-workspace` clears under the same lease,+ and only when no fence has appeared since the teardown finished. A build that another build or a+ teardown ran alongside fails, and makes whatever snapshot it then finds ineligible; when even that is+ refused, because the other writer holds the lease or the snapshot cannot be read, the refusal is+ recorded beside the snapshot and the next `--changed-only` run builds in full.+- **Tearing down a downloaded spec keeps its relationships and global choices** ([#587]), as it+ already kept its tables: a download flags all three `existing: true`. Deleting a relationship+ removed its lookup column — and that column's data — from a table teardown kept.+- **An app in several unmanaged solutions downloads the same way every time** ([#587]). The spec keeps+ `Default` and names the candidates in `solutionCandidates` — never whichever row the server happened+ to return first, which teardown would then delete. Its business rules and option sets are still+ reported across all of them, and a membership that cannot be read is reported as unknown. When the+ candidates' publishers do not share one prefix, or the solutions or a publisher cannot be read — the+ one solution's included — the spec's publisher prefix is not guessed from the app name: it stays the+ unverified `new`, relationships keep their deployed names, and the download says to set it.+- **The teardown summary no longer calls every skip "not found".** Steps kept on purpose and steps+ never attempted after a failed app delete are counted as what they are.+- **A failure after the app is already deleted no longer strands the rest of the teardown.** The SDK+ tidies its local copy after the remote delete; when that step failed, teardown stopped as though+ the app still existed. It now asks the platform, and carries on when the app is gone.### Changed@@ -207,7 +286,10 @@ downloads that round-trip Choice columns.[#575]: https://github.com/microsoft/power-platform-skills/issues/575[#581]: https://github.com/microsoft/power-platform-skills/issues/581[#583]: https://github.com/microsoft/power-platform-skills/issues/583+[#585]: https://github.com/microsoft/power-platform-skills/issues/585+[#586]: https://github.com/microsoft/power-platform-skills/issues/586[#587]: https://github.com/microsoft/power-platform-skills/issues/587+[#588]: https://github.com/microsoft/power-platform-skills/issues/588[#589]: https://github.com/microsoft/power-platform-skills/issues/589[#591]: https://github.com/microsoft/power-platform-skills/issues/591diff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.mdindex 1b7eb95f9..e2b602269 100644--- a/plugins/model-apps/docs/app-builder-design.md+++ b/plugins/model-apps/docs/app-builder-design.md@@ -586,13 +586,53 @@ ONLY after effective success (apply+verify).## Eligibility state machine (durable, fail-closed)- **INVALIDATE (→false) before any write** of every full/unsupported/fast apply and teardown; abort if- the invalidation write fails.+ the invalidation write fails. A `--changed-only` invalidate is **fenced** to the generation its+ decision was read at: a snapshot tombstoned, rewritten or deleted since that read aborts the run+ before it writes anything. A run that read **no** snapshot (a first build) **claims** one instead — an+ ineligible, debt-free placeholder written under the lease only while there is still none — so its+ baseline write has a generation to be fenced by; a claim refused because a snapshot appeared aborts+ the run the same way.- **debt** accrues on any unsupported change/removal; `eligible:true` requires empty debt; debt clearsONLY by proven-fresh recreation (artifact absent before build) or an exact verifier — never by a plainfull rebuild that re-skips a stale artifact.- **teardown TOMBSTONE**: teardown writes `eligible:false` + `teardown-in-progress` debt BEFORE deletinganything, and deletes the envelope ONLY after teardown success + verified live absence; a partial/- crashed teardown leaves the tombstone (so a surviving artifact can't be rebaselined).+ crashed teardown leaves the tombstone (so a surviving artifact can't be rebaselined). The tombstone+ also **rotates the generation** — without that, a run that read the snapshot first still matched it+ and re-blessed its stale view over the tombstone — and a teardown that cannot write it **deletes+ nothing**. The CAS write takes the workspace lease itself, so a tombstone cannot land between its+ compare and its write. A workspace with **no** snapshot gets a fresh tombstone too (creating the folder+ if needed, and removing it again after a clean teardown): with none, a first build's baseline write+ expected "none", nothing ever changed that, and the build blessed the app the teardown was deleting.+ The tombstone **lists every teardown in flight** (id, pid, start time), and every teardown that+ finishes removes its own entry, under the lease (retried briefly if another writer holds it): one+ that failed or threw keeps the tombstone. After a clean teardown the snapshot is deleted when the last+ live entry goes — whatever it has become by then — and until then it stays tombstoned, its generation+ rotated, fencing the deletes still running. A `--changed-only` build that reads a tombstone listing a+ teardown still running refuses to build until it finishes (the no-identity fallback included, which+ writes no snapshot and so reads the workspace again before it builds, refusing when the generation moved+ during identity discovery). A+ running teardown refreshes its entry every minute, and an entry whose process is gone, or that has not+ been seen for five minutes, no longer counts — so a killed teardown's entry stops blocking within+ minutes, even under a reused pid. `--clear-workspace` leaves a workspace whose fence is still held. A+ workspace lease is reclaimed only from a DEAD holder — or, for a lock with no readable token, one older+ than five minutes — never from a live one however old: a holder paused mid-write would commit its stale+ view over the fence on resuming. It is reclaimed by one writer only (an exclusive claim file, itself+ abandoned only once its claimer is dead, and a re-check of the lock); a reclaim that fails after its+ write releases what it wrote. An old lease whose holder's pid is alive names the file to delete, in case+ that pid was reused.+- **overlap**: a `--changed-only` run whose generation moved while it built, or whose baseline write+ another writer refused, reports failure whatever its build returned, and **invalidates** whatever+ snapshot it then finds (fenced to the generation it read, retried briefly): a baseline another writer+ blessed meanwhile would certify a state this run may since have changed. When every attempt is refused,+ the lease held by a live writer or a snapshot there that cannot be read (only a provably absent one+ leaves nothing to distrust), the refusal is recorded in a **distrust marker**+ (`<workspace>/apply-snapshot.distrust.<id>.json`, one file per refusal), written beside the snapshot and+ outside the lease. The next `--changed-only` run builds in full however eligible the snapshot reads; a+ full build that lands its baseline deletes the markers it found at its start, by name, never one written+ since; the last clean teardown deletes them all with the snapshot. An unreadable marker still counts. A+ marker is only ever created or deleted, never moved or rewritten, so a concurrent reader always sees+ every other run's.## Projection/verifier framework (`scripts/lib/projection.js` — deliverable #1, DONE)Pure, id-free, normalized projections that serve as the EXACT post-apply verifiers (static classificationdiff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex b6b27bb62..2a266feaa 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -17,6 +17,10 @@ and ~24% of it described features most apps never use.[ { "name": "new_priority", "displayName": "Priority", "options": ["Low","Medium","High"] } ]```Reference from a column via `"globalChoice": "new_priority"` (built before the columns that bind it).+- **`existing`** *(optional, download-emitted)* — `true` on a set **download** declared: an option set+ is org-wide and may be shared with other apps, and a download cannot prove this app created it. The+ build still creates it if missing (reuses it if present); teardown **retains** it, exactly as it+ retains an `existing: true` table.## webResources[] (optional — client-side logic)@@ -231,6 +235,23 @@ works through.- A **chart** tile needs both a declared `chart` (the visualization) **and** a declared `view` (itsdata); a **list** tile needs a declared `view`. The target entity is derived from the view. `name`defaults to the chart/view name; `colspan`/`rowspan` optional (default 1×4).+- **View and chart names are unique only per table.** When the tile's view name is declared on more+ than one table, set the tile's `entity` to say which; the chart must be declared on that **same**+ table. Both are rejected at the spec gate otherwise — a same-named chart on another table would+ plot a different table's data over this view.+- **Dashboard names must be unique**, compared the way Dataverse compares them: ignoring case,+ accents, full/half width and trailing spaces (`Overview`, `OVERVIEW `, `Café`/`Cafe`) — but not a+ leading space, and not a vowel sign in scripts where it is a letter. A dashboard has no other+ identity in the spec — a sitemap subarea names it and a rebuild finds it by name — so two that+ compare equal would collapse into one. A download **withholds** such a pair and says why, rather+ than emit a spec that cannot be rebuilt: rename one in Maker and download again. Because a name can+ also match **another app's** dashboard, ownership comes from the app's solution, which holds every+ dashboard the build creates (one the build cannot add to it is removed again, or named in the halt+ when that fails too). When several in the+ environment match, the build reuses — and verify checks, its sitemap entry included — the one the+ solution holds, and halts if that does not single one out; a single match is used as it is. Teardown+ deletes only the ones the solution holds, never a namesake, and none when the spec has no real+ solution to ask (`Default`) or that solution is already gone.- Built after views/charts (it references their ids). The dashboard is **global** (not entity-scoped)and added to the solution. To surface it in the app nav, add a `dashboard` sitemap subarea (below) —that also auto-pins it as an app component.diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 694a5f91a..7cafe3aed 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -47,7 +47,7 @@ sample data (incl. multi-parent junction links + status reasons), and publish.```jsonc{"solution": { "uniqueName": "ContosoSupportDesk", "displayName": "Contoso Support Desk", "publisherPrefix": "new" },- "app": { "name": "Support Desk", "description": "Track tickets", "icon": "new_appicon" },+ "app": { "name": "Support Desk", "description": "Track tickets", "icon": "new_appicon" /* , "aiDescription": "…" — optional routing description */ },"entities": [ /* tables — see below */ ],"relationships": [ /* 1:N links — see below */ ],"globalChoices": [ /* optional shared option sets */ ],@@ -104,6 +104,19 @@ sample data (incl. multi-parent junction links + status reasons), and publish.**existing** app by identity — even after you **rename** the display `app.name` — instead of creating a**duplicate** app. You normally never hand-author this: an authored create-fresh spec omits it, and thebuild derives the uniquename deterministically from `solution.publisherPrefix` + `app.name`.+- **`app.aiDescription`** *(optional)* — the app's **routing description**: what an agent or router+ reads to decide whether *this* app is the right place for a request. It is **separate from+ `app.description`**, the text on the app tile, and maps to the platform's+ [`appmodule.aiappdescription`](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule#BKMK_aiappdescription)+ column. Write who the app is for, the tasks it covers, what it deliberately excludes and — when+ sibling apps expose the same tables — how to tell them apart (see *Descriptions* below).+ **Absent means "leave it alone":** the platform can write this text itself, so the build writes the+ field only when the spec sets it (at create, or on an existing app when the value differs) and never+ blanks it. A download carries it back when the app has one, and `--verify` checks the deployed value+ whenever the spec sets one. Changing it on an app that has an **unpublished** change to its name,+ description or routing description (saved in Maker but not published) halts the build: Dataverse+ refuses the write until that change is published, so publish the app (or discard the change) first.+ **Rules:** a non-empty string of at most 1,048,576 characters, the column's maximum.- **`languageCode`** *(optional)* — the [LCID](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/)stamped on the Dataverse labels the build creates: data-model labels (table, column, choice, statusreason, relationship and alternate-key display names) **and** form, dashboard and sitemap labels.@@ -234,18 +247,6 @@ agent later inspects an app it did not build — to extend it, debug it, or answGood: `"Severity 1-5; drives the escalation rule and the SLA clock."`Weak: `"The priority column."` (restates the name and adds nothing)-**`app.description` additionally has to ROUTE.** It is the one field an orchestrator reads to decide-whether *this* app is the right place to send a request, and there is no separate "AI description"-field — the SDK's app surface has nowhere to put one, so anything extra would be silently dropped.-Write the routing signal into `app.description` itself: who the app is for, the tasks it covers,-what it deliberately **excludes**, and — when two apps expose the same tables — how to tell them-apart. Sibling apps over the same data are precisely where a purpose-only description fails.--Good: `"Project-manager and portfolio work: planning projects, assigning and reprioritizing work,-and managing sprints, budgets, risks and releases. Prefer the My Work app when the request is about-the signed-in contributor's own assigned items."`-Weak: `"An app for managing projects."` (no persona, no scope boundary, nothing to disambiguate)-**Rules:** must be a non-empty string, max 2000 characters (the Dataverse ceiling — the platformtruncates silently past it, so it is rejected at author time instead). Omit the field entirely ratherthan setting `""`; every write site omits an absent description, so **a rebuild never blanks one a@@ -270,6 +271,26 @@ created and is not revisited: tables, columns, the solution, global choices, `we`app.description`, forms, dashboards and business rules. Adding a description to one of those *after*it exists is accepted by validation, builds green, and does not change the deployed artifact.+**The routing signal goes in `app.aiDescription`, not `app.description`.** An orchestrator deciding+whether *this* app is the right place to send a request needs more than the app tile can hold, so the+routing text has its own field (`appmodule.aiappdescription`), leaving `app.description` short. Write+who the app is for, the tasks it covers, what it deliberately **excludes**, and — when two apps expose+the same tables — how to tell them apart. Sibling apps over the same data are precisely where a+purpose-only description fails.++Good: `"Project-manager and portfolio work: planning projects, assigning and reprioritizing work,+and managing sprints, budgets, risks and releases. Prefer the My Work app when the request is about+the signed-in contributor's own assigned items."`+Weak: `"An app for managing projects."` (no persona, no scope boundary, nothing to disambiguate)++It follows its own rules, not the ones above: up to **1,048,576** characters, and **one string for+every language** — the column is not localizable, so it takes no LCID map. Unlike `app.description`+it is **reconciled on an existing app**: a rebuild writes it whenever it differs from the deployed+value. A download copies the deployed value into the spec — including one the platform generated —+and from then on the spec owns it: if the platform later rewrites it, `--verify` reports the+difference and the next full build restores the spec's value (a `--changed-only` apply compares the+spec with its last snapshot, not with the deployed row, so it does not notice).+## entities[]```jsonc{@@ -505,6 +526,13 @@ rather than silently dropped:have (a bridge to a *standard* table like `systemuser`/`account` is kept — every org has one);- an **N:N whose partner table is outside the app**.+Every relationship a download reconstructs carries **`"existing": true`** — the same ownership flag its+tables carry, for the same reason: a download cannot prove this app created it. The build still creates+a missing one; **teardown retains it**, because deleting a relationship removes its lookup column (and+that column's data) from a table teardown also retains. An author-built relationship has no flag and is+torn down with the app as before. If you set the flag on a relationship yourself, set it on its+`referenced` table too: teardown cannot delete a table that a retained relationship still points at.+A polymorphic lookup's **shadow attributes** (`<lookup>name`, `<lookup>yominame`) are excluded from`columns[]` along with it, so a rebuild does not gain invented Text columns where the lookup used tobe. Every lookup has shadows; a polymorphic one's are physically stored rather than logical, which is@@ -731,24 +759,48 @@ explicit layout.**Editing an existing form.** An explicit layout is converged onto the deployed form rather thanflattened into its first section: missing tabs, form-columns and sections are **created**, a-section's `columns`/`label`/`showLabel`/`visible` are **updated in place**, and a field sitting in-the wrong section is **moved** (never duplicated — the cell keeps its id and any control state a+section's `columns`/`label`/`showLabel`/`visible` are **updated in place**, a named section that+sits in another tab or form-column is **moved** to where the layout places it, and a field sitting+in the wrong section is **moved** (never duplicated — the cell keeps its id and any control state amaker edited). Containers are matched by `name`, then `label`, then position, so a form built by anearlier `auto` layout — or by hand in Maker — converges instead of gaining a duplicate tab. Nothingis renamed, because form scripts and business rules can reference a section by name.-Two rules keep that matching from claiming the wrong container. An index an earlier tab or section+Three rules keep that matching from claiming the wrong container. An index an earlier tab or sectionalready matched is **not reused**, because an unlabeled container compiles to a default label(`General` for a tab, `Details` for a section) and several of them would otherwise all match the-first one. And sections the **engine** owns — a sub-grid host, the notes/timeline section — are+first one. A section whose name another section in the layout declares is matched only **by that+name**, so it can be moved to its own place instead of being taken over by a neighbour with the same+label. And sections the **engine** owns — a sub-grid host, the notes/timeline section — arematched only by `name`: a label or a position is not evidence about what a container *is*, andmatching one positionally would relabel a sub-grid and place fields in the row holding its grid.--⚠ Containers are only ever added or updated, never removed. Moving a section between form-columns or-tabs while letting its `name` be generated therefore leaves the original behind as an **empty-section with the same label** — generated names encode position (`section_<tab>_<column>_<index>`),-so the moved section is a different identity. Give a section an explicit `name` when you intend to-move it, and delete a section you no longer want in Maker.+Their name is the engine's own, so a section **you** declare never takes one even by name: a section+of yours called `section_notes` gets a section of its own rather than the timeline host of that name.+A host is known by that name *and* by what it holds: only controls without a field, or the control the+host exists for — the timeline in `section_notes`, a sub-grid in `section_grid_…` — even after a maker+added a field beside it. A section of yours that a maker filled with a web resource or sub-grid keeps+its own name, and is still found by it. (One you name `section_notes` or `section_grid_…` is+indistinguishable from a host when it has no fields, or when a maker puts that host's control into it:+the build then gives your fields a section of their own beside it. Give it another name. And a host+that a maker both renamed and gave a field carries neither mark, so it is matched like any other+section — keep the engine's section names when you customise its sections in Maker.)++⚠ **Moving a section.** A section with an explicit `name` is found wherever it is on the deployed+form and moved to the tab and form-column the layout places it in — the same section, so its fields,+id and anything set on it in Maker travel with it, and the build reports the move. It lands after+every section the layout places before it in that column (or first, when there is none). A section+whose `name` is **generated** is a different identity once it moves — generated names encode+position (`section_<tab>_<column>_<index>`) — so it is created in the new place, its fields are moved+into it, and the original, left empty by this run, is removed (unless `"prune": false`). Give a+section an explicit `name` when you intend to move it. A section the layout stops mentioning is+removed only when this run empties it — its fields pruned, or moved into another section — and+`prune` is on; anything else it still holds keeps it, and a section it leaves alone is yours to+remove in Maker.++⚠ **Field order.** A field the form lacks is appended to the end of its section; a field it already+has stays where it is. So reordering a section's `fields` list on an existing form changes nothing+(`--verify` does not check order either). Position a field explicitly with `fieldOptions[x].after`,+below.⚠ Declaring explicit `tabs` also switches **pruning** on: a field the deployed form carries and thelayout does not list is removed (never the primary field). Set `"prune": false` to restyle ordiff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.mdindex 74133e3a1..2d8a079cd 100644--- a/plugins/model-apps/references/authoring-flow.md+++ b/plugins/model-apps/references/authoring-flow.md@@ -745,6 +745,7 @@ even though the underlying spec stores the schemaName as provided:### App- Name: [app name]- Description: [description]+- Routing description: [app.aiDescription — omit the line when the spec does not set one]- Action: [Create new | Use existing: <app-id>]### Solution@@ -843,7 +844,7 @@ The spec shape follows `plugins/model-apps/samples/app-spec.support-desk.json`:{"schemaVersion": 2,"solution": { "uniqueName": "...", "displayName": "...", "publisherPrefix": "..." },- "app": { "name": "...", "description": "..." },+ "app": { "name": "...", "description": "...", "aiDescription?": "..." },"entities": [ { "schemaName", "displayName", "pluralName", "primaryAttribute", "columns" } ],"relationships": [ { "type", "referenced", "referencing", "lookup" } ],"forms": [ { "entity", "type", "name", "layout", "subgrids?" } ],diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 08a2e1725..4fa8a3386 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -36,7 +36,7 @@ const { envTruthy } = require('./lib/interaction-mode.js');// `verify-model-app.js` pass. Reuses the read-only reconcile core + the SDK reader (DRY — same code the// standalone verifier runs). The sibling CLI is safe to require (it has a `require.main` guard).const { verifySpec } = require('./lib/verify-spec.js');-const { readerFor } = require('./verify-model-app.js');+const { readerFor, isolatedReaderFor } = require('./verify-model-app.js');const { makeGenpageCli } = require('./lib/genpage-cli.js');// Construct the SDK against the vendored bundle + an az-token HttpClient. Two clients:@@ -93,12 +93,17 @@ async function makeSdk(env, spec, workspaceDir, languageCode) {cleanup();throw err;}- // Only the two SDK instances and the cleanup are returned. The raw `httpClient` used to come back- // with them so the caller could wire verify's role-privilege reader — that read had no SDK surface- // and had to compose an absolute `EntityDefinitions(...)?$select=Privileges` request itself. The- // vendored bundle now exposes `getEntityPrivileges`, so the reader takes the SDK and the raw client- // has no caller. Returning it anyway would advertise a bypass this file no longer takes.- return { sdk, provisionSdk, cleanup };+ // Only the two SDK instances, the cleanup and verify's isolated dashboard reader are returned. The raw+ // `httpClient` used to come back with them so the caller could wire verify's role-privilege reader — that+ // read had no SDK surface and had to compose an absolute `EntityDefinitions(...)?$select=Privileges` request+ // itself. The vendored bundle now exposes `getEntityPrivileges`, so the reader takes the SDK and the raw+ // client has no caller. Returning it anyway would advertise a bypass this file no longer takes.+ //+ // The isolated reader is built HERE so it shares this client, and with it the Azure CLI token: made by the+ // caller, it created a client of its own, and a second `az account get-access-token`, for every build's+ // dashboard verify. Each read still gets its own throwaway workspace and SDK (verify-model-app.js).+ const isolatedReader = isolatedReaderFor(env, { httpClient });+ return { sdk, provisionSdk, cleanup, isolatedReader };}// Turn engine progress events into a phase-grouped, status-marked build log:@@ -449,6 +454,12 @@ async function buildModelApp(spec, opts, deps) {// "re-runnable phase", NOT "transient error", so it is deliberately NOT used here.function isTransientHalt(err) {if (!err) return false;+ // An error that says it must not be retried wins over any status or text it carries. A dashboard+ // the build could neither add to its solution nor remove again is one (sdk-build.js): its message+ // quotes the causes verbatim — a customization lock, "try again later" — but a retry would find the+ // dashboard as a lone name match and reuse it outside the solution, the state the undo exists to+ // prevent.+ if (err.transient === false || (err.cause && err.cause.transient === false)) return false;const status = (err.cause && err.cause.statusCode) || err.statusCode;const msg = String((err.message || '') + ' ' + ((err.cause && err.cause.message) || ''));return (@@ -630,7 +641,7 @@ async function main() {opts.preResolvedLanguageCode = authoringLanguageCode;// Construct for both dry-run and apply: proves the vendored bundle + adapter wire up// (offline), and apply needs it. A spec validation error short-circuits before any write.- const { sdk, provisionSdk, cleanup } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode);+ const { sdk, provisionSdk, cleanup, isolatedReader } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode);// Durable build journal (apply runs only): a per-run record of steps + where a run halted,// written to <workspace>/build-log.jsonl. Resume = re-run the same command (idempotent).const journal = opts.apply@@ -690,7 +701,7 @@ async function main() {// reported a clean PASS having never checked what any persona's role grants. Caught live:// standalone verify ran 10 checks against the same app where the build's inline verify ran 8.// The reader now takes its privilege read off the SDK, so there is nothing left to forget.- verify: (s, verifyOpts) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir }), verifyOpts),+ verify: (s, verifyOpts) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpageCli: makeGenpageCli(env), workspaceDir, isolatedReader }), verifyOpts),// The set of LCIDs this organization actually has. Injected so the pure lib stays free of// transport, and only consulted for an EXPLICIT `--language-code` / spec `languageCode`.provisionedLanguages: () => readProvisionedLanguages(env),diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 53d1f8b23..cdb2ffc52 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -17,7 +17,7 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(const { reverseResolveNavIds } = require('./lib/pageref-resolver.js');const { fetchSitemap, sitemapGenPages } = require('./lib/sitemap-pages.js');const { isRestrictedSolution } = require('./lib/system-solutions.js');-const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName } = require('./lib/app-spec.js');+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey } = require('./lib/app-spec.js');const { odataGuid } = require('./lib/ai-app-settings.js');// webresourcetype (int) -> app-spec web-resource type.@@ -51,13 +51,25 @@ async function readDashboards(sdk, app, warn) {if (typeof warn === 'function') warn(`dashboard '${title || id}' (${id}) could not be read: ${e && e.message}`);continue;}- let name = title || id;+ let name = null;let description;+ let nameError = null;try {const rows = await sdk.queryRecords('systemform', { select: ['name', 'description'], filter: `formid eq ${id}`, top: 1 });if (rows && rows[0] && rows[0].name) name = rows[0].name;description = rows && rows[0] && rows[0].description;- } catch { /* keep fallback */ }+ } catch (e) { nameError = e; }+ // An App Spec refers to a dashboard by NAME, and a rebuild finds the deployed one by that name. The+ // sitemap title is only the subarea's label: standing in for an unread name, it made a rebuild create+ // (or bind to) another dashboard, and hid a real name clash from the check below. So a dashboard whose+ // name cannot be read is withheld like an unreadable one — its subarea dropped, which trips the+ // lossy-download gate with this reason.+ if (!name) {+ if (typeof warn === 'function') {+ warn(`dashboard '${title || id}' (${id}): its name could not be read (${nameError ? (nameError.message || nameError) : 'no row for it'}), and an App Spec refers to a dashboard by name, so it is left out; its sitemap subarea will be dropped. Download again once it can be read.`);+ }+ continue;+ }const tiles = [];for (const c of art.components || []) {const p = c.parameters || {};@@ -109,7 +121,23 @@ async function readDashboards(sdk, app, warn) {+ `(${(art.components || []).length} component(s)); its sitemap subarea will be dropped.`);}}- return out;+ // Two DIFFERENT dashboards whose names compare equal cannot survive the round trip (#586 item 4):+ // the App Spec names a dashboard, its sitemap subarea points at it BY NAME, and the build finds an+ // existing one by name — so both subareas would resolve to whichever dashboard a rebuild found, and+ // the other would silently leave the nav. Every dashboard sharing its name is withheld instead,+ // which drops its subarea and trips the lossy-download gate with this reason as the cause.+ // Compared with the App Spec gate's own key, so a download can never emit a spec that gate rejects.+ // `ids` is keyed by lowercased id, so one dashboard behind two subareas is a single entry here and+ // can never be mistaken for a clash with itself.+ const byName = new Map();+ for (const d of out) byName.set(dashboardNameKey(d.name), (byName.get(dashboardNameKey(d.name)) || []).concat(d));+ const ambiguous = [...byName.values()].filter((same) => same.length > 1);+ for (const same of ambiguous) {+ if (typeof warn === 'function') {+ warn(`dashboards ${same.map((d) => `${d.id} ('${d.name}')`).join(', ')} share the name '${same[0].name}' as far as Dataverse is concerned (it compares names ignoring case, and in most languages accents), and an App Spec refers to a dashboard by name, so they cannot be told apart; rename one in Maker and download again`);+ }+ }+ return ambiguous.length ? out.filter((d) => byName.get(dashboardNameKey(d.name)).length === 1) : out;}// Reconstruct relationships[] from live metadata (#567).@@ -132,7 +160,11 @@ async function readDashboards(sdk, app, warn) {// Returns { relationships, skipped } — `skipped` feeds the not-round-tripped report so a// relationship this cannot express is DECLARED missing rather than silently absent, which was the// whole complaint in #567.-async function readRelationships(sdk, logicals, publisherPrefix, warn) {+//+// `prefixUnknown`: the spec's publisher prefix is a placeholder (see runDownload), so every deployed name is+// carried as it is. Omitting one because it equals the name the build would generate is only safe under the+// REAL prefix: under the placeholder, a rebuild generates another name and creates the relationship twice.+async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixUnknown = false } = {}) {const inApp = new Set((logicals || []).map((l) => String(l).toLowerCase()));const lc = (s) => String(s || '').toLowerCase();const relationships = [];@@ -242,8 +274,13 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn) {const auto = relationshipSchemaName({ referenced, referencing }, publisherPrefix);const deployed = r.SchemaName;const prefixOk = !publisherPrefix || lc(deployed).startsWith(`${lc(publisherPrefix)}_`);- const rel = { type: 'OneToMany', referenced, referencing, lookup };- if (deployed && lc(deployed) !== lc(auto)) {+ // `existing: true` for the reason the recovered TABLES carry it (#587 item 6): nothing here can+ // prove this app created the relationship, and a teardown that deleted it would take the lookup+ // column — and its data — off a table that teardown otherwise retains. A rebuild still creates a+ // missing one; only teardown reads the flag.+ const rel = { type: 'OneToMany', referenced, referencing, lookup, existing: true };+ if (deployed && prefixUnknown) rel.schemaName = deployed;+ else if (deployed && lc(deployed) !== lc(auto)) {if (prefixOk) rel.schemaName = deployed;else if (typeof warn === 'function') {// RENAMED, not skipped. This relationship IS pushed below, so recording it in `skipped`@@ -283,10 +320,11 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn) {//// `manyToManySchemaName` SORTS the two entity names before composing, so `auto` is computed// from the same pair that is emitted rather than from the order Dataverse happened to report.- const rel = { type: 'ManyToMany', entity1: e1, entity2: e2 };+ const rel = { type: 'ManyToMany', entity1: e1, entity2: e2, existing: true }; // ownership unprovable, as for 1:N aboveconst auto = manyToManySchemaName({ entity1: e1, entity2: e2 }, publisherPrefix);const deployed = r.SchemaName;- if (deployed && lc(deployed) !== lc(auto)) {+ if (deployed && prefixUnknown) rel.schemaName = deployed;+ else if (deployed && lc(deployed) !== lc(auto)) {if (!publisherPrefix || lc(deployed).startsWith(`${lc(publisherPrefix)}_`)) rel.schemaName = deployed;else if (typeof warn === 'function') {// RENAMED, not skipped — this relationship IS carried into the spec, so recording it as@@ -566,7 +604,7 @@ async function readAppShellSettings(sdk, appId) {return out;}-async function readDescriptionInventory(sdk, appId, solutionUniqueName) {+async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlobalChoices) {// `incomplete[]` records an artifact class whose read FAILED. Without it the whole app-component// block shared one broad catch, so a 403 on `systemform` left `forms: []` — indistinguishable from// an app with no forms, which is EXACTLY the reported bug (AB#6686423) reappearing inside the fix@@ -639,32 +677,51 @@ async function readDescriptionInventory(sdk, appId, solutionUniqueName) {for (const src of APP_COMPONENT_ENTITY_SOURCES) fail(INVENTORY_KIND_BY_SET[src.set] || src.set, err);}- try {- if (solutionUniqueName && !isRestrictedSolution(solutionUniqueName)) {- const esc = String(solutionUniqueName).replace(/'/g, "''");- const sols = await sdk.queryRecords('solution', { select: ['solutionid'], filter: `uniquename eq '${esc}'`, top: 1 });- const solId = sols && sols[0] && sols[0].solutionid;- if (solId) {- // Solution component type 29 is Workflow — which is EVERY process kind, not just business- // rules: classic workflows, actions, business process flows and modern flows all land here.- // See component type values: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent- //- // So the rows must be narrowed after the fetch. A business rule is `category 2`, and `type 1`- // is the DEFINITION — activating one makes Dataverse create a second `type 2` copy of it, so- // without the type filter every active rule would appear twice in the inventory.- //- // Filtered client-side rather than in the query because `rowsByIds` batches on the id column;- // both fields are requested in the select so the decision is made on real values, and a row- // that reports NEITHER field is dropped rather than assumed to be a rule — fail closed, since- // mislabelling somebody's classic workflow as a business rule is the failure mode here.- const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid', 'componenttype'], filter: `_solutionid_value eq ${solId} and componenttype eq 29`, top: 1000 });- const ids = (comps || []).map((r) => r && r.objectid).filter(Boolean);- const processes = await rowsByIds(sdk, 'workflow', 'workflowid', ids, ['workflowid', 'name', 'primaryentity', 'description', 'category', 'type'], (r) => r);- for (const r of processes) {- if (Number(r && r.category) !== 2 || Number(r && r.type) !== 1) continue;- inventory.businessRules.push(withDescription({ id: r.workflowid, name: r.name, entity: r.primaryentity }, r.description));- }+ // The app's own solution(s), resolved ONCE: the business-rule and the global-choice reads are both+ // scoped to them. `solutionScope` is one uniquename, EVERY candidate when the app is in several+ // (#587 item 9), or an Error when its membership could not be read (runDownload decides which).+ // Built-in containers (Default/Active/Basic) hold every unmanaged customization in the org, so they+ // scope nothing and are dropped. A FAILED lookup is kept apart as `solutionError`, because "the app+ // has no solution" and "we could not look" are different facts: each dependent class must report the+ // second as unknown rather than as empty.+ let solutionError = solutionScope instanceof Error ? solutionScope : null;+ const solIds = [];+ if (!solutionError) {+ try {+ for (const name of [].concat(solutionScope || []).filter((n) => n && !isRestrictedSolution(n))) {+ const esc = String(name).replace(/'/g, "''");+ const sols = await sdk.queryRecords('solution', { select: ['solutionid'], filter: `uniquename eq '${esc}'`, top: 1 });+ if (sols && sols[0] && sols[0].solutionid) solIds.push(sols[0].solutionid);}+ } catch (err) {+ solutionError = err;+ }+ }++ try {+ if (solutionError) throw solutionError;+ // Solution component type 29 is Workflow — which is EVERY process kind, not just business+ // rules: classic workflows, actions, business process flows and modern flows all land here.+ // See component type values: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent+ //+ // So the rows must be narrowed after the fetch. A business rule is `category 2`, and `type 1`+ // is the DEFINITION — activating one makes Dataverse create a second `type 2` copy of it, so+ // without the type filter every active rule would appear twice in the inventory.+ //+ // Filtered client-side rather than in the query because `rowsByIds` batches on the id column;+ // both fields are requested in the select so the decision is made on real values, and a row+ // that reports NEITHER field is dropped rather than assumed to be a rule — fail closed, since+ // mislabelling somebody's classic workflow as a business rule is the failure mode here.+ const ids = [];+ for (const solId of solIds) {+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid', 'componenttype'], filter: `_solutionid_value eq ${solId} and componenttype eq 29`, top: 1000 });+ ids.push(...(comps || []).map((r) => r && r.objectid).filter(Boolean));+ }+ // rowsByIds de-duplicates, so a rule in two of the candidate solutions is listed once.+ const processes = await rowsByIds(sdk, 'workflow', 'workflowid', ids, ['workflowid', 'name', 'primaryentity', 'description', 'category', 'type'], (r) => r);+ for (const r of processes) {+ if (Number(r && r.category) !== 2 || Number(r && r.type) !== 1) continue;+ inventory.businessRules.push(withDescription({ id: r.workflowid, name: r.name, entity: r.primaryentity }, r.description));}} catch (err) {// FAIL CLOSED, not silent. This used to swallow the error as "an inspection aid, not a rebuild@@ -708,14 +765,40 @@ async function readDescriptionInventory(sdk, appId, solutionUniqueName) {// An ABSENT `IsManaged` keeps the row. This inventory's whole purpose is to avoid asserting an// absence it cannot substantiate, so an unreadable flag degrades to "report it" rather than to a// silent drop.- const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged');- if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);- if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');- inventory.globalChoices.push(- ...res.body.value- .filter((r) => r && r.IsManaged !== true)- .map((r) => withDescription({ name: r.Name }, r.Description))- );+ //+ // And the inventory is SCOPED TO THE APP (#586 item 5): a set is listed only when the app's+ // SOLUTION owns it, or when a column this download emits REFERENCES it (so its description is+ // kept). The metadata collection is org-wide, so listing every unmanaged row told the author to+ // recreate metadata the app has nothing to do with — measured live, an isolated app whose spec+ // declared no global choices was reported as leaving two behind while its solution held zero+ // option-set components. Ownership is solution component type 9 (OptionSet), whose `objectid` is+ // the set's MetadataId — hence MetadataId in the $select, and the join is on normalized GUIDs.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent+ if (solutionError) throw solutionError;+ const owned = new Set();+ let truncated = null;+ for (const solId of solIds) {+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid'], filter: `_solutionid_value eq ${solId} and componenttype eq 9`, top: COMPONENT_PAGE_CAP });+ // A full page is indistinguishable from a truncated one — same rule as the app components above.+ if ((comps || []).length >= COMPONENT_PAGE_CAP) truncated = new Error(`more than ${COMPONENT_PAGE_CAP} option sets in one of the app's solutions; the list was truncated, so this class is incomplete`);+ for (const r of comps || []) if (r && r.objectid) owned.add(odataGuid(r.objectid).toLowerCase());+ }+ const referenced = new Set([...(referencedGlobalChoices || [])].map((n) => String(n).toLowerCase()));+ // Nothing in scope — no solution that could own a set, and no emitted column binding one — means+ // there is nothing of THIS app's to find, so the org-wide read is skipped rather than filtered to+ // an empty list. That is not an unknown: the sets the app binds are all declared in the spec.+ if (owned.size || referenced.size) {+ const res = await sdk.dataverse.get('/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged,MetadataId');+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);+ if (!res.body || !Array.isArray(res.body.value)) throw new Error('the response carried no value[] array');+ inventory.globalChoices.push(+ ...res.body.value+ .filter((r) => r && r.IsManaged !== true)+ .filter((r) => owned.has(odataGuid(r.MetadataId).toLowerCase()) || referenced.has(String(r.Name || '').toLowerCase()))+ .map((r) => withDescription({ name: r.Name }, r.Description))+ );+ }+ if (truncated) fail('globalChoices', truncated);} catch (err) {fail('globalChoices', err);}@@ -996,13 +1079,16 @@ async function readOptionSets(sdk, logical) {// Options are FLATTENED to a single string here, unlike the inline case: `validateAppSpec` rejects a// localized `globalChoices[]` option outright, because Dataverse accepts the multi-language payload// for a shared set and stores only the base language without reporting the loss.+//+// Declared `existing: true` (#587 item 6): a global option set is org-wide and can be shared with other+// apps, and nothing here proves this app created it — so teardown retains it, as it does the tables.function collectGlobalChoices(meta, into) {for (const a of (meta && meta.attributes) || []) {const os = a && a.optionSet;if (!os || !os.isGlobal || !os.name) continue;const key = String(os.name).toLowerCase();if (into.has(key)) continue;- into.set(key, { name: os.name, options: os.options.map((l) => descriptionFromDataverse(l)) });+ into.set(key, { name: os.name, options: os.options.map((l) => descriptionFromDataverse(l)), existing: true });}return into;}@@ -1146,8 +1232,10 @@ function notRoundTrippedSummary(inventory) {// Drop from the not-round-tripped inventory the global choices this download DOES now reconstruct// (#564). The report's whole value is that its claims are true: a shared set emitted into// `spec.globalChoices[]` IS carried forward, so listing it as "not round-tripped" would be the same-// class of false statement the report exists to prevent. Every other global choice in the-// environment stays listed — the app does not bind it, so a rebuild genuinely will not recreate it.+// class of false statement the report exists to prevent. Every other set in the inventory — which+// holds only sets the app's solution owns or its columns bind (#586 item 5) — stays listed: the spec+// does not declare it, so a rebuild genuinely will not recreate it. `declared` is any collection with+// `has(lowerCasedName)` and `size`.function roundTrippedAware(inventory, globalChoiceDecls) {if (!inventory || !Array.isArray(inventory.globalChoices) || !globalChoiceDecls || !globalChoiceDecls.size) return inventory;const declared = globalChoiceDecls;@@ -1709,52 +1797,80 @@ function droppedSubareaCount(app, spec) {// Recover the REAL unmanaged solution an app module belongs to. An app is a `solutioncomponent` of// EVERY solution it lives in — always the built-in system solutions (Active/Default/Basic) AND the-// real unmanaged solution it was created in. The naive `top:1` query returns an arbitrary row (often-// 'Default', which is itself ismanaged=false, so an ismanaged filter does not exclude it), so the-// real solution was never recovered and a downloaded spec defaulted its solution to the restricted-// 'Default' — which teardown then 400s on, orphaning the real solution. So enumerate ALL memberships-// and pick the single unmanaged, non-system solution. Best-effort: returns null (caller keeps its own-// default) on no match or any query error — never throws.+// real unmanaged solution(s) it was added to. The naive `top:1` query returned an arbitrary row (often+// 'Default', which is itself ismanaged=false, so an ismanaged filter does not exclude it), so the real+// solution was never recovered and a downloaded spec defaulted to the restricted 'Default' — which+// teardown then 400s on, orphaning the real solution. So every membership is read (`paginate`, which+// the SDK refuses to combine with `top`: `$top` is a hard cap that suppresses `@odata.nextLink`).+// Never throws. Returns one of:+// null — no real (unmanaged, non-system) solution+// { uniqueName, description?, publisherPrefix?, publisherUnreadable? } — exactly one: the app's solution+// { ambiguous: [uniqueName, ...], publisherPrefix?, publisherUnreadable? } — several (#587 item 9)+// { unreadable: reason } — the membership could not be read//-// Returns `{ uniqueName, publisherPrefix? }`. The publisher prefix is read from the recovered-// solution's OWNING PUBLISHER via the SDK's `getSolution`, because it is the only authoritative-// source: the prefix was previously guessed from the app's uniquename, which breaks whenever the app-// name doesn't encode the solution's publisher — an app named `new_customermanagement` inside-// publisher `contoso`, an app with no prefix at all, or a publisher prefix longer than the guess's-// length bound all collapsed to the literal `'new'` (ADO 6603390). `getSolution` is best-effort on top-// of best-effort: if it fails or the publisher defines no prefix, we return the uniqueName alone and-// the caller falls back to the app-derived guess.+// SEVERAL is never resolved to one. Dataverse has no "owning" solution — a component is simply a+// member of each — and the pick is not cosmetic: a rebuild adds components to the spec's solution and+// teardown deletes that container. The rule this replaced took the first qualifying row of a capped+// first page, so two downloads of one app could name different solutions on row order alone; a+// heuristic such as "the one whose publisher matches the app name's prefix" rests on the app-name+// guess ADO 6603390 showed is unreliable. The caller keeps 'Default' — which teardown never deletes —+// and names the candidates. UNREADABLE stays apart from null for the reason it does everywhere else in+// this file: "the app is in no solution" and "we could not look" must not look alike.+//+// `publisherPrefix` is read from the solution's OWNING PUBLISHER via the SDK's `getSolution`, the only+// authoritative source: the prefix used to be guessed from the app's uniquename, which breaks whenever+// the app name doesn't encode the publisher — an app named `new_customermanagement` inside publisher+// `contoso`, an app with no prefix, or a prefix longer than the guess's length bound all collapsed to+// the literal `'new'` (ADO 6603390). With several candidates it is reported only when EVERY+// candidate's prefix was read and they agree: the prefix shapes the relationship schema names the+// download emits, so a wrong one makes a same-environment rebuild create duplicates — a failed read+// never counts as agreement. A publisher read that FAILS, for the one solution or any of several, is+// reported as `publisherUnreadable` (the reason), and the caller then treats the prefix as unknown rather+// than guess it: a failed read says nothing about the publisher. Only when there is simply no usable+// prefix — a bundle without getSolution, or a publisher without a customization prefix — does the caller+// fall back to the app-derived guess.async function recoverAppSolution(sdk, appId) {+ let real;try {- // objectid == the appmoduleid. `top:500` is a safe over-provision (an app is realistically a- // component of only a handful of solutions) that keeps us on the same proven query path as every- // other queryRecords call in the skill (all pass an explicit top) — it just must not be the old- // `top:1`, which returned an arbitrary single membership (often 'Default').- const comps = await sdk.queryRecords('solutioncomponent', { select: ['_solutionid_value'], filter: `objectid eq ${appId}`, top: 500 });+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['_solutionid_value'], filter: `objectid eq ${appId}`, paginate: true });const solIds = [...new Set((comps || []).map((c) => c && c._solutionid_value).filter(Boolean))];if (!solIds.length) return null;- // One OR-batched lookup for all candidate solutions (solutionid is a Guid, so it is unquoted in- // the OData filter — mirrors the existing `solutionid eq ${id}` usage elsewhere in this file).- const filter = solIds.map((id) => `solutionid eq ${id}`).join(' or ');- const sols = await sdk.queryRecords('solution', { select: ['solutionid', 'uniquename', 'ismanaged', 'description'], filter, top: 500 });- const real = (sols || []).find((s) => s && s.ismanaged === false && !isRestrictedSolution(s.uniquename));- if (!real) return null;- const out = withDescription({ uniqueName: real.uniquename }, real.description);- // Authoritative publisher prefix for anything authored into THIS solution. Guarded on the method- // existing so an older vendored bundle (pre-getSolution) degrades to the caller's fallback instead- // of throwing away the solution we just recovered.- if (typeof sdk.getSolution === 'function') {- try {- const info = await sdk.getSolution(real.uniquename);- // An empty-string prefix is legitimate for some first-party publishers, but it is not usable as- // a customization prefix, so treat it as "not recovered" and let the caller fall back.- if (info && info.publisherPrefix) out.publisherPrefix = String(info.publisherPrefix).toLowerCase();- } catch { /* best-effort — keep the recovered uniqueName */ }+ const sols = await rowsByIds(sdk, 'solution', 'solutionid', solIds, ['solutionid', 'uniquename', 'ismanaged', 'description'], (r) => r);+ // Sorted so the candidates — and everything derived from them — are order-independent.+ real = sols+ .filter((s) => s && s.ismanaged === false && !isRestrictedSolution(s.uniquename))+ .sort((a, b) => String(a.uniquename).localeCompare(String(b.uniquename)));+ } catch (e) {+ return { unreadable: (e && e.message) ? String(e.message).slice(0, 200) : 'read failed' };+ }+ if (!real.length) return null;+ // Resolves to the prefix, to null when there is none to use, or to { failed: reason } when the read+ // itself failed. Guarded on the method existing so an older vendored bundle (pre-getSolution) degrades+ // to the caller's fallback. An empty-string prefix is legitimate for some first-party publishers, but it+ // is not usable as a customization prefix, so it reads as "none".+ const prefixOf = async (s) => {+ if (typeof sdk.getSolution !== 'function') return null;+ try {+ const info = await sdk.getSolution(s.uniquename);+ return info && info.publisherPrefix ? String(info.publisherPrefix).toLowerCase() : null;+ } catch (e) {+ return { failed: (e && e.message) ? String(e.message).slice(0, 200) : 'read failed' };}+ };+ if (real.length === 1) {+ const out = withDescription({ uniqueName: real[0].uniquename }, real[0].description);+ const prefix = await prefixOf(real[0]);+ if (typeof prefix === 'string') out.publisherPrefix = prefix;+ else if (prefix) out.publisherUnreadable = prefix.failed;return out;- } catch {- return null; // best-effort — a recovery failure must not break the download}+ const prefixes = [];+ for (const s of real) prefixes.push(await prefixOf(s));+ const out = { ambiguous: real.map((s) => String(s.uniquename)) };+ if (prefixes.every((p) => typeof p === 'string') && new Set(prefixes).size === 1) out.publisherPrefix = prefixes[0];+ const failed = prefixes.find((p) => p && typeof p === 'object');+ if (failed) out.publisherUnreadable = failed.failed;+ return out;}// Injectable download helper: all live-Dataverse work happens here so tests can inject mock deps.@@ -2021,13 +2137,41 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// when recovery finds nothing — that fallback cannot be torn down, but teardown skips it safely (see// system-solutions.js) rather than erroring.const recovered = await recoverAppSolution(sdk, appId);+ // Several real solutions (#587 item 9), or a membership that could not be read: the spec keeps+ // 'Default' rather than a guess — the one solution a teardown never deletes — and says so. The+ // candidates are returned as well as printed, so the JSON result carries them.+ const solutionCandidates = recovered && Array.isArray(recovered.ambiguous) ? recovered.ambiguous : null;+ const solutionUnreadable = recovered && recovered.unreadable ? recovered.unreadable : null;+ if (solutionCandidates) {+ process.stderr.write(`WARNING: this app belongs to ${solutionCandidates.length} unmanaged solutions (${solutionCandidates.join(', ')}) and a download cannot tell which one you manage it in, so the spec's solution is left as 'Default', which a teardown never deletes. Set solution.uniqueName in app-spec.json to that solution before a rebuild or teardown.\n`);+ }+ if (solutionUnreadable) {+ process.stderr.write(`WARNING: the solutions this app belongs to could not be read (${solutionUnreadable}), so the spec's solution is left as 'Default', which a teardown never deletes, and its business rules and solution-owned global choices are reported as unknown. Set solution.uniqueName in app-spec.json before a rebuild or teardown.\n`);+ }// Prefix precedence: the SOLUTION's publisher (authoritative) → the app-uniquename guess (fallback).// `prefixResolved` means "this prefix is trustworthy", which gates the icon own-vs-foreign// classification below; it must be true for BOTH trusted sources, or a genuine own-publisher custom// nav icon stops round-tripping. It stays false only for the unverified 'new' default.const solutionPrefix = (recovered && recovered.publisherPrefix) || null;- const trustedPrefix = solutionPrefix || appDerivedPrefix;+ const publisherUnreadable = (recovered && recovered.publisherUnreadable) || null;+ // Several candidate solutions whose publishers do not share one prefix, none that could be read, or a+ // publisher whose read FAILED — the one solution's included: the prefix is UNKNOWN. The app-name guess is+ // exactly the heuristic that ambiguity refuses to use (see recoverAppSolution), and a wrong prefix renames+ // every relationship not carrying it, so a same-environment rebuild creates each a second time. So it is+ // not used: the prefix stays the unverified default, and relationships keep their deployed names. (A failed+ // read of the one solution's publisher used to read as "no prefix", which fell back to the guess.)+ const prefixUnknown = !solutionPrefix && !!(solutionCandidates || solutionUnreadable || publisherUnreadable);+ if (prefixUnknown) {+ let why = solutionCandidates ? 'the publishers of those solutions do not share one customization prefix' : 'with the solutions unread, the publisher is unknown';+ if (publisherUnreadable) {+ why = solutionCandidates+ ? `the publishers of those solutions could not all be read (${publisherUnreadable})`+ : `the publisher of solution '${recovered.uniqueName}' could not be read (${publisherUnreadable})`;+ }+ process.stderr.write(`WARNING: ${why}, so solution.publisherPrefix is left as the unverified 'new' and every relationship keeps its deployed name. Set solution.publisherPrefix in app-spec.json to your solution publisher's prefix before a rebuild.\n`);+ }+ const trustedPrefix = solutionPrefix || (prefixUnknown ? null : appDerivedPrefix);const solution = { uniqueName: 'Default', publisherPrefix: trustedPrefix || 'new', prefixResolved: !!trustedPrefix };if (recovered && recovered.uniqueName) solution.uniqueName = recovered.uniqueName;// `recoverAppSolution` already unwraps the solution's description; carry it across. This object is@@ -2078,7 +2222,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLostry {const rel = await readRelationships(sdk, allLogicals, solution.publisherPrefix, (m) => {process.stderr.write(`WARNING: ${m}\n`);- });+ }, { prefixUnknown });relationships = rel.relationships;relationshipsSkipped = rel.skipped;} catch (e) {@@ -2113,8 +2257,19 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLosglobalChoices: async () => finalizeGlobalChoices(entities, globalChoiceDecls),// Captured on the way past so the role-restriction warning below can read it. The accessor stays// a function (hydrateSpec's contract) and is still called exactly once, so this adds no query.+ // The global-choice inventory is scoped to the sets the app's solution owns plus the ones an+ // emitted column binds (#586 item 5); the second half is read off `entities` here rather than off+ // the `globalChoices` accessor so it does not depend on the order hydrateSpec calls them in.descriptionInventory: async () => {- capturedInventory = await readDescriptionInventory(sdk, appId, solution.uniqueName);+ const referenced = new Set();+ for (const e of entities || []) for (const c of (e && e.columns) || []) if (c && c.globalChoice) referenced.add(String(c.globalChoice).toLowerCase());+ // Scoped the way the solution was resolved: the one solution; EVERY candidate when there are+ // several — each contains the app, and scoping by none would report their business rules as+ // "none", the silent absence this report exists to prevent; unknown when unreadable.+ const scope = solutionUnreadable+ ? new Error(`the solutions this app belongs to could not be read (${solutionUnreadable})`)+ : (solutionCandidates || solution.uniqueName);+ capturedInventory = await readDescriptionInventory(sdk, appId, scope, referenced);return capturedInventory;},};@@ -2132,12 +2287,18 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos// reported failure was not that they are omitted — that is a documented limitation — but that// NOTHING said so, so a second session reading the spec could not tell "this app has no views"// from "this download does not carry views".- const notRoundTripped = notRoundTrippedSummary(roundTrippedAware(capturedInventory, globalChoiceDecls));+ //+ // Round-tripped means DECLARED in the emitted spec, so subtract `spec.globalChoices` — not the raw+ // `globalChoiceDecls` candidates, which also hold sets bound only by a filtered attribute or a+ // dropped table. Subtracting those hid a set the spec never re-declares: a silent loss in the one+ // report whose job is naming them.+ const declaredGlobalChoices = new Set((spec.globalChoices || []).map((g) => String(g && g.name).toLowerCase()));+ const notRoundTripped = notRoundTrippedSummary(roundTrippedAware(capturedInventory, declaredGlobalChoices));if (notRoundTripped) process.stderr.write(notRoundTrippedWarning(notRoundTripped));if (relationshipsSkipped.length) process.stderr.write(relationshipsSkippedWarning(relationshipsSkipped));const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];- return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped };+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, ...(solutionCandidates ? { solutionCandidates } : {}) };}async function main() {@@ -2194,7 +2355,7 @@ async function main() {const result = await runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy: allowLossyDownload });if (!result.ok) { emitResult(false, result); return; }- const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped } = result;+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates } = result;if (droppedSubareas > 0 || dashboardReconstructionError) {const droppedList = (droppedSubareaDetails || []).map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)@@ -2236,7 +2397,7 @@ async function main() {const specPath = path.join(outDir, 'app-spec.json');preserveAuthoredLanguageCode(spec, specPath);fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));- emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}) });+ emitResult(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) });}// Carry an AUTHOR-PINNED `languageCode` across a download, and only from the spec already on disk.diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.jsindex 559274f0e..4da9ed7ce 100644--- a/plugins/model-apps/scripts/lib/app-spec-doc.js+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js@@ -42,6 +42,9 @@ function overview(spec) {const app = spec.app || {};const out = [`# ${text(app.name, 'Model-driven app')} — design`, ''];if (app.description) out.push(text(app.description), '');+ // #583: the routing description is reviewed beside the tile text, since the two now say different+ // things — the tile stays short, and the routing text says who the app is for and what it leaves out.+ if (app.aiDescription) out.push(`**Routing description:** ${text(app.aiDescription)}`, '');out.push('Generated from `app-spec.json` by `scripts/write-app-spec-doc.js`. **Regenerate rather than','hand-edit** — `app-spec.json` is the source of truth, so a manual edit here is lost on the next',diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 52ddf40f9..08c8cebd5 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -170,7 +170,9 @@ function choiceValueMap(entity, spec) {}const map = Object.create(null);for (const c of entity.columns || []) {- if (c.type !== 'Choice' && c.type !== 'MultiChoice') continue;+ // A column with no string schemaName cannot be keyed; validateAppSpec reports it by name+ // ("a column is missing schemaName") — this helper must not crash that report instead.+ if (!c || (c.type !== 'Choice' && c.type !== 'MultiChoice') || typeof c.schemaName !== 'string') continue;let byLabel = null;if (Array.isArray(c.options) && c.options.length) {byLabel = indexOptions(c.options);@@ -387,7 +389,7 @@ function manyToManySchemaName(rel, publisherPrefix) {// booleans, ISO dates, and unknown tokens all still work).function resolveSampleRecords(entity, records, spec) {const choices = choiceValueMap(entity, spec);- const multi = new Set((entity.columns || []).filter((c) => c.type === 'MultiChoice').map((c) => c.schemaName.toLowerCase()));+ const multi = new Set((entity.columns || []).filter((c) => c && c.type === 'MultiChoice' && typeof c.schemaName === 'string').map((c) => c.schemaName.toLowerCase()));return (records || []).map((rec) => {const out = {};for (const [k, v] of Object.entries(rec)) {@@ -1018,6 +1020,27 @@ function validateDescription(value, label, errors, opts = {}) {}}+// `app.aiDescription` (#583) — the app's ROUTING description: what an agent or router reads to choose+// between sibling apps over the same tables ("prefer My Work when the request is about the signed-in+// contributor's own assigned work"). It is distinct from `app.description`, which is the text on the+// app tile. It maps to the platform's `appmodule.aiappdescription`, a Memo of up to 1,048,576 characters:+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule#BKMK_aiappdescription+//+// ABSENT means "leave the deployed value alone": the platform can write this text itself, so the build+// never writes the field unless the spec sets it. That makes an empty string the one value that could+// blank a description nobody asked to remove, so it is refused rather than written.+const AI_DESCRIPTION_MAX = 1048576;+function validateAiDescription(value, errors) {+ if (value === undefined || value === null) return;+ if (typeof value !== 'string') {+ errors.push('app.aiDescription must be a string');+ } else if (!value.trim()) {+ errors.push('app.aiDescription must not be blank — omit it to leave the deployed value alone');+ } else if (value.length > AI_DESCRIPTION_MAX) {+ errors.push(`app.aiDescription is ${value.length} characters (max ${AI_DESCRIPTION_MAX})`);+ }+}+// Per-control form-field options: `readOnly`, `hidden`, `after`.//// Reachable two ways — inline on an EXPLICIT layout's `sections[].fields[]` entry, or via the@@ -1145,6 +1168,52 @@ function sampleKeyIdentity(v) {return JSON.stringify([typeof v, v]);}+// Identity of a dashboard NAME, shared by the author-time gate in `validateAppSpec` and the download's+// withholding in `readDashboards` (download-model-app.js). The two MUST agree, or a download could+// hand back a spec that its own gate then rejects.+//+// A dashboard has no identity but its name: a sitemap subarea names it, and the build reuses an+// existing one that a server-side `name eq '…'` filter finds (resolveArtifact, sdk-build.js). That+// comparison follows the environment's SQL collation — case-insensitive in every language, accent-+// insensitive in most — so two names can differ on the page and still be ONE dashboard to the lookup.+// See: https://learn.microsoft.com/en-us/power-platform/admin/language-collations+//+// What this folds is MEASURED, not assumed: pairs were written to a live English environment and read+// back with `eq`. The server treated as EQUAL: case (Latin, Greek, Cyrillic); Latin, Greek and+// Vietnamese accents, whether precomposed or decomposed; Hebrew points; the Devanagari nukta; kana+// voicing marks; katakana vs hiragana; full- vs half-width; the ligatures and expansions ß/ss, Æ/AE,+// Œ/OE, fi/fi; the stroke letters Ø Ł Đ; final vs medial sigma; Arabic tatweel; and TRAILING spaces.+// It kept as DIFFERENT: a LEADING space; a trailing tab or no-break space; Devanagari and Thai vowel+// signs and Arabic harakat (letters, not accents); and Cyrillic й vs и — though ё vs е is equal, so+// on Cyrillic only the breve counts. An earlier version stripped every combining mark and trimmed+// both ends, which rejected distinct names such as 'कार' / 'कर' (a vowel sign is a letter).+//+// Where it cannot mirror the server exactly it folds MORE — accents in the accent-sensitive+// languages, and a decomposed Hangul syllable, which the server keeps distinct from its precomposed+// form. The costs are lopsided: a false rejection is loud and fixed by a rename, while a missed+// collision silently drops a dashboard from the app.+const DASHBOARD_FOLDED_MARK = /[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u093c\u09bc\u0a3c\u0abc\u0b3c\u0cbc\u3099\u309a\u0640]/u;+const DASHBOARD_LETTER_FOLDS = { 'ß': 'ss', 'æ': 'ae', 'œ': 'oe', 'ø': 'o', 'ł': 'l', 'đ': 'd', 'ς': 'σ' };+function dashboardNameKey(name) {+ // Trailing U+0020 is stripped BEFORE the compatibility decomposition: NFKD turns a no-break space+ // into a plain one, and the server keeps a trailing no-break space significant.+ const raw = String(name == null ? '' : name).replace(/ +$/, '');+ let out = '';+ let cyrillicBase = false;+ for (const ch of raw.normalize('NFKD')) {+ if (DASHBOARD_FOLDED_MARK.test(ch)) {+ if (ch === '\u0306' && cyrillicBase) out += ch; // й / ў are letters of their own, not accented и / у+ continue;+ }+ cyrillicBase = /\p{Script=Cyrillic}/u.test(ch);+ out += ch;+ }+ return out.toLowerCase()+ .replace(/[ßæœøłđς]/g, (c) => DASHBOARD_LETTER_FOLDS[c])+ // Katakana → hiragana: the same kana, one code-point block apart (0x60).+ .replace(/[\u30a1-\u30f6\u30fd\u30fe]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0x60));+}+// The names the form compiler generates for an UNNAMED tab/section, shared with artifact-intent.js// so the spec gate and the compiler cannot disagree about what a container will actually be called.//@@ -1175,6 +1244,23 @@ function formColumnsOf(tab) {return [{ width: '100%', sections: Array.isArray(tab.sections) ? tab.sections : [] }];}+// Every section name an explicit layout DECLARES, under the name the compiler gives it, lower-cased.+// The build and verify both take it from here, so their label and position passes skip exactly the+// same containers (form-container-match.js `claimedByAuthoredName`). Engine-owned sections — the+// notes section, sub-grid hosts — are never in it: the compiler appends those, the author does not.+// `{ named: true }` keeps only the names the author GAVE, leaving out the ones generated from a+// section's position.+function authoredSectionNames(formSpec, { named = false } = {}) {+ const names = new Set();+ const tabs = formSpec && Array.isArray(formSpec.tabs) ? formSpec.tabs : [];+ tabs.forEach((t, ti) => formColumnsOf(t).forEach((col, ci) => {+ ((col && Array.isArray(col.sections)) ? col.sections : []).forEach((sec, si) => {+ if (sec && typeof sec === 'object' && (!named || sec.name)) names.add(String(sec.name || generatedSectionName(ti, ci, si)).toLowerCase());+ });+ }));+ return names;+}+// The plugin's own version, read from its manifest, for the `minimumPluginVersion` capability gate.//// Cached, and NULL when the manifest cannot be read. The caller decides what that means, and it is@@ -1723,6 +1809,7 @@ function validateAppSpec(spec, opts = {}) {if (spec.app && spec.app.headerNavigationRefresh !== undefined && typeof spec.app.headerNavigationRefresh !== 'boolean') {errors.push('app.headerNavigationRefresh must be a boolean');}+ validateAiDescription(spec.app && spec.app.aiDescription, errors);if (spec.languageCode !== undefined && normalizeLanguageCode(spec.languageCode) === null) {// Keep the leading clause stable — the CLI flag and two test suites match on it. The appended// guidance exists because the bare message named the mistake without naming the fix, and a@@ -2417,8 +2504,52 @@ function validateAppSpec(spec, opts = {}) {const DASH_TILE_TYPES = new Set(['chart', 'list', 'iframe', 'webresource']);const viewNamesSet = new Set((spec.views || []).map((v) => v.name));const chartNamesSet = new Set((spec.charts || []).map((c) => c.name));+ // Name → the tables that declare it. A tile names its view and chart, but both are unique only PER+ // TABLE, and the build resolves them on the tile's table: when names repeat across tables, a tile+ // that does not pin its table — or whose chart lives on a different one — deploys one table's view+ // under another table's chart, which the platform accepts and publishes (live-measured).+ const entitiesByName = (items) => {+ const m = new Map();+ for (const x of items || []) {+ if (!x || !x.name || !x.entity) continue;+ if (!m.has(x.name)) m.set(x.name, new Set());+ m.get(x.name).add(String(x.entity).toLowerCase());+ }+ return m;+ };+ const viewTables = entitiesByName(spec.views);+ const chartTables = entitiesByName(spec.charts);+ const seenDashboardNames = new Map(); // dashboardNameKey → the first dashboard's name as written+ // The table a name-based chart/list tile shows, or null when it cannot be determined (reported).+ const tileTable = (d, t) => {+ const tables = viewTables.get(t.view);+ if (!tables) return null; // unknown view — reported by the caller+ if (t.entity) {+ const want = String(t.entity).toLowerCase();+ if (!tables.has(want)) {+ errors.push(`dashboard '${d.name}': ${t.type} tile names view '${t.view}' on ${t.entity}, but that view is declared on ${[...tables].join(', ')}`);+ return null;+ }+ return want;+ }+ if (tables.size > 1) {+ errors.push(`dashboard '${d.name}': ${t.type} tile's view '${t.view}' is declared on more than one table (${[...tables].join(', ')}) — set the tile's entity to say which`);+ return null;+ }+ return [...tables][0];+ };for (const d of spec.dashboards || []) {if (!d || !d.name) { errors.push('a dashboard is missing a name'); continue; }+ // A sitemap subarea and the build both find a dashboard BY NAME, the build through a server-side+ // filter that ignores case (and usually accents), so two names that compare equal there cannot be+ // told apart: both subareas resolve to one dashboard and the other silently leaves the nav+ // (#586 item 4). See dashboardNameKey for exactly what is folded.+ const dashKey = dashboardNameKey(d.name);+ if (seenDashboardNames.has(dashKey)) {+ errors.push(`dashboard '${d.name}': has the same name as dashboard '${seenDashboardNames.get(dashKey)}' — Dataverse compares names ignoring case (and, in most languages, accents), and a sitemap subarea and the build find a dashboard by name, so each name must be unique`);+ } else {+ seenDashboardNames.set(dashKey, d.name);+ }validateDescription(d.description, `dashboard '${d.name}'`, errors);if (!Array.isArray(d.tiles) || !d.tiles.length) { errors.push(`dashboard '${d.name}': needs tiles[]`); continue; }for (const t of d.tiles) {@@ -2440,6 +2571,13 @@ function validateAppSpec(spec, opts = {}) {} else {if (!t.chart || !chartNamesSet.has(t.chart)) errors.push(`dashboard '${d.name}': chart tile references unknown chart '${t.chart}'`);if (!t.view || !viewNamesSet.has(t.view)) errors.push(`dashboard '${d.name}': chart tile needs a declared view for its data — '${t.view}' not found`);+ else {+ const table = tileTable(d, t);+ const chartOn = chartTables.get(t.chart);+ if (table && chartOn && !chartOn.has(table)) {+ errors.push(`dashboard '${d.name}': chart tile shows ${table} (view '${t.view}'), but chart '${t.chart}' is declared on ${[...chartOn].join(', ')} — a tile's chart and view must be on the same table`);+ }+ }}} else if (t.type === 'list') {if (byId) {@@ -2447,6 +2585,8 @@ function validateAppSpec(spec, opts = {}) {else badEntityRef(t.entity, `dashboard '${d.name}': list tile`);} else if (!t.view || !viewNamesSet.has(t.view)) {errors.push(`dashboard '${d.name}': list tile references unknown view '${t.view}'`);+ } else {+ tileTable(d, t);}} else if (t.type === 'iframe') {if (!t.url) errors.push(`dashboard '${d.name}': iframe tile needs a url`);@@ -2827,7 +2967,14 @@ function validateAppSpec(spec, opts = {}) {for (const key of Object.keys(rec)) if (key.toLowerCase() === want) return rec[key];return undefined;};- const filled = (col) => v.length > 0 && v.every((r) => {+ // The loader decides on RESOLVED values: buildSeedGroup runs resolveSampleRecords before+ // chooseMatchOn, so a Choice label, its other-language alias and the raw option integer+ // ('Open', 'Ouvert', 100000000) are ONE key there. Comparing the values as authored passed+ // exactly those specs, and the seed then refused them mid-build (#586 item 2). Resolved one+ // row at a time so a malformed row — already reported above — cannot throw out of the gate.+ const isRow = (r) => r && typeof r === 'object' && !Array.isArray(r);+ const resolved = v.map((r) => (isRow(r) ? resolveSampleRecords(ent, [r], spec)[0] : r));+ const filled = (col) => resolved.length > 0 && resolved.every((r) => {const x = valueOf(r, col);return x !== undefined && x !== null && x !== '';});@@ -2843,19 +2990,23 @@ function validateAppSpec(spec, opts = {}) {.find((c) => c && filled(c));const matchOnCol = altKeyCol || (!hasSafeKey && filled(ent.primaryAttribute.schemaName) ? ent.primaryAttribute.schemaName : null);if (matchOnCol) {- const seen = new Set();- for (const r of v) {- const raw = valueOf(r, matchOnCol);+ const seen = new Map(); // resolved key → the value as the author wrote it+ for (let i = 0; i < v.length; i++) {+ const raw = valueOf(v[i], matchOnCol);// Keyed through the SHARED `sampleKeyIdentity` the loader uses, so this gate cannot// decide "duplicate" differently from the code that actually refuses the seed. A// plain `String(...)` key made `1` and `'1'` collide here while the loader treats them// as distinct — rejecting, at author time, a spec that builds.- const key = sampleKeyIdentity(raw);+ const key = sampleKeyIdentity(valueOf(resolved[i], matchOnCol));if (seen.has(key)) {- errors.push(`sampleData['${k}']: duplicate ${String(matchOnCol).toLowerCase()} value '${String(raw)}'. ${altKeyCol ? `${String(matchOnCol).toLowerCase()} is the single-column alternate key used as matchOn` : `With no single-column alternate key, ${String(matchOnCol).toLowerCase()} is used as matchOn`}, so Dataverse could resolve or deduplicate the wrong row. Make ${String(matchOnCol).toLowerCase()} unique across the sample rows.`);+ // Two DIFFERENT spellings of one option read as a false alarm unless the message+ // says why they are the same.+ const prev = seen.get(key);+ const alias = sampleKeyIdentity(prev) === sampleKeyIdentity(raw) ? '' : ` (the same option as '${String(prev)}')`;+ errors.push(`sampleData['${k}']: duplicate ${String(matchOnCol).toLowerCase()} value '${String(raw)}'${alias}. ${altKeyCol ? `${String(matchOnCol).toLowerCase()} is the single-column alternate key used as matchOn` : `With no single-column alternate key, ${String(matchOnCol).toLowerCase()} is used as matchOn`}, so Dataverse could resolve or deduplicate the wrong row. Make ${String(matchOnCol).toLowerCase()} unique across the sample rows.`);break;}- seen.add(key);+ seen.set(key, raw);}}}@@ -3413,9 +3564,11 @@ function migrateAppSpec(spec) {module.exports = {rejectLocalizedGlobalChoice,sampleKeyIdentity,+ dashboardNameKey,generatedTabName,generatedSectionName,formColumnsOf,+ authoredSectionNames,validateAppSpec,validateSampleDataRows,normalizePageSource,diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-index.js b/plugins/model-apps/scripts/lib/apply-snapshot-index.jsindex bd046b1e9..5bc7b9bef 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-index.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-index.js@@ -87,7 +87,9 @@ function indexArtifacts(spec, created, opts = {}) {}for (const ch of Array.isArray(s.charts) ? s.charts : []) {if (!ch || typeof ch !== 'object') continue;- const id = c.charts && c.charts[ch.name];+ // `created.charts` is keyed `entity|name` — the same identity as `identityOf.chart` — because two+ // tables may each own a chart with the same name.+ const id = c.charts && c.charts[identityOf.chart(ch)];if (id) out.charts[identityOf.chart(ch)] = { id };}for (const cm of Array.isArray(s.commands) ? s.commands : []) {diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.jsindex 9468a3f7f..f0e0aa36e 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js@@ -2,20 +2,24 @@// Impure persistence for the apply-snapshot envelope (changed-only deliverable #3, part 2).//// The DECISION logic lives in apply-snapshot.js (pure); this module is the I/O boundary: an atomic-// snapshot write, a build-wide WORKSPACE lease, a generation-CAS write, and the invalidate / tombstone /-// delete primitives the build and teardown flows will call. Correctness rests on TWO mechanisms:+// snapshot write, a build-wide WORKSPACE lease, a generation-CAS write, and the invalidate / claim /+// tombstone / delete primitives the build and teardown flows call. Correctness rests on TWO mechanisms:// · Atomic write (temp→fsync→rename) so a crash never leaves a truncated, half-trusted snapshot.// · Generation CAS so a concurrent build that re-wrote the snapshot between our read and our write is// detected and the loser's write is REFUSED (never a lost update).// The lease is an OPTIMIZATION that reduces contention around the read-modify-write; unlike the pages// lease (sdk-build.js acquireAppPagesLease, which must NOT steal because duplicate CREATE isn't CAS--// guarded), this lease MAY reclaim a stale holder because the generation CAS is the actual guard — a-// reclaimed-but-still-alive original holder simply loses the CAS on its own write.+// guarded), this lease MAY reclaim a stale holder. That is only as safe as the lease is exclusive in+// practice, because every write here — the CAS write included — compares and then writes as two steps+// under it: a holder paused past LEASE_STALE_MS between them can still overwrite. So reclaim is limited+// to a holder that is dead or past LEASE_STALE_MS (minutes, against writes of milliseconds), a token+// caught mid-write is aged by its file rather than presumed abandoned, and a lock released meanwhile is+// re-taken exclusively (acquireLease).const fs = require('node:fs');const path = require('node:path');const {- parseEnvelope, serializeEnvelope, markIneligible, tombstone, generationMatches, newGeneration, bumpGeneration,+ parseEnvelope, serializeEnvelope, makeEnvelope, markIneligible, tombstone, generationMatches, newGeneration, bumpGeneration,} = require('./apply-snapshot.js');const SNAPSHOT_FILE = 'apply-snapshot.json';@@ -34,6 +38,16 @@ function readSnapshot(workspaceDir) {catch { return null; }}+// Is there provably NO snapshot file? readSnapshot answers null for an absent file and for one it could not read or+// parse alike, and a caller that must not trust a snapshot it cannot see (distrustWorkspace) needs the difference: only+// ENOENT (or ENOTDIR, a workspace path that is not a folder) proves absence; any other outcome, the file present+// included, does not.+function snapshotAbsent(workspaceDir) {+ try { fs.lstatSync(snapshotPath(workspaceDir)); return false; } catch (e) {+ return !!(e && (e.code === 'ENOENT' || e.code === 'ENOTDIR'));+ }+}+// Atomic write. The temp file MUST be in the same directory as the target — rename() is only atomic// within a single filesystem, and a workspace-local temp guarantees that. fsync the fd before rename so// the bytes are durable, not just in the page cache. A crash leaves EITHER the prior snapshot or the new@@ -58,10 +72,34 @@ function writeSnapshotAtomic(workspaceDir, envelope) {}}+// Create a CLAIM `file` holding `text` exclusively ('wx' — one writer wins), and remove it again when the write+// itself fails. writeFileSync with 'wx' creates the file BEFORE it writes, so a write that failed (ENOSPC) left an+// empty claim behind — and a claim is removed only by its creator (acquireLease), so every later attempt refused.+// Rolling back is safe for a claim precisely because nobody else ever removes or reclaims one. It is NOT used for+// the lease lock: an empty lock ages into a reclaimable one, and deleting it after another writer had reclaimed it+// let a third take the path fresh — two holders. writeFileSync on the descriptor writes the whole text (a single+// writeSync may write only part of it). The final close is part of the write: one that reports an error (EIO) threw+// past the rollback, and the claim stayed behind with every later attempt refused. Throws what open, write or close+// threw; EEXIST means another writer holds it.+function createExclusive(file, text) {+ const fd = fs.openSync(file, 'wx');+ let open = true;+ try {+ fs.writeFileSync(fd, text);+ // Counted as closed BEFORE the call: a close that throws has still released the descriptor (Linux, Windows),+ // and closing it again could close another file that has reused the number meanwhile.+ open = false;+ fs.closeSync(fd);+ } catch (e) {+ if (open) { try { fs.closeSync(fd); } catch { /* best-effort */ } }+ try { fs.rmSync(file, { force: true }); } catch { /* best-effort: it is empty, and names itself (acquireLease) */ }+ throw e;+ }+}+// Is `pid` a live process? Best-effort: process.kill(pid, 0) throws ESRCH when the pid is gone, EPERM when-// it exists but we lack permission (still alive). pid reuse can FALSELY report alive, but that only makes-// us KEEP a young lease held (→ caller falls back to full build, safe). Age is the primary staleness-// signal; aliveness only protects a YOUNG lease from premature takeover.+// it exists but we lack permission (still alive). pid reuse can FALSELY report a dead holder alive, which+// keeps its lease held (see acquireLease): every write then fails closed, never unsafely.function processAlive(pid) {if (!pid || typeof pid !== 'number') return false;try { process.kill(pid, 0); return true; }@@ -69,8 +107,8 @@ function processAlive(pid) {}// Acquire the workspace snapshot lease. Exclusive create ('wx') picks one winner atomically. If the lease-// is already held, reclaim it ONLY when stale (token older than staleMs OR the holder pid is dead); a live,-// young holder blocks (returns { ok:false }). Returns a handle whose token is written into the lock so+// is already held, reclaim it ONLY when stale — its holder's pid is dead, or, for a lock with no readable+// token, the lock file is older than staleMs; a live holder blocks (returns { ok:false }), however old. Returns a handle whose token is written into the lock so// release is OWNER-CHECKED (never remove a lock a different build now holds). `deps` seams now()/pid/alive// for tests.function acquireLease(workspaceDir, deps = {}) {@@ -82,22 +120,103 @@ function acquireLease(workspaceDir, deps = {}) {const lp = leasePath(workspaceDir);const token = JSON.stringify({ pid, at: now(), rnd: Math.random().toString(36).slice(2) });const tryCreate = () => {+ // Not createExclusive: a write that fails after the create leaves a tokenless lock, which ages into a+ // reclaimable one (below) — removing it instead could delete a lock another writer has since reclaimed.try { fs.writeFileSync(lp, token, { flag: 'wx' }); return { ok: true, path: lp, token }; }catch (e) { return { ok: false, code: e && e.code, error: e }; }};let r = tryCreate();if (r.ok) return r;if (r.code !== 'EEXIST') return { ok: false, reason: `lease create failed: ${r.error && r.error.message}` };- // Held — decide staleness.- let held;- try { held = JSON.parse(fs.readFileSync(lp, 'utf8')); } catch { held = null; }- const age = held && typeof held.at === 'number' ? now() - held.at : Infinity;- const stale = age > staleMs || !(held && isAlive(held.pid));- if (!stale) return { ok: false, reason: `lease held by pid ${held && held.pid} (age ${age}ms)`, heldBy: held };- // Reclaim: overwrite the stale token. The generation CAS — not this reclaim — is what actually prevents a- // lost update if the reclaimed holder is still alive.- try { fs.writeFileSync(lp, token); return { ok: true, path: lp, token, reclaimed: true }; }- catch (e) { return { ok: false, reason: `stale lease reclaim failed: ${e.message}` }; }+ // Held — decide staleness. The raw content is kept: a reclaim replaces the lock only while it still holds+ // exactly what was judged stale here.+ let held = null;+ let heldRaw = null;+ let gone = false;+ try { heldRaw = fs.readFileSync(lp, 'utf8'); } catch (e) { gone = !!e && e.code === 'ENOENT'; }+ if (heldRaw !== null) { try { held = JSON.parse(heldRaw); } catch { held = null; } }+ const heldToken = held && typeof held.at === 'number' ? held : null;+ let age = 0;+ if (heldToken) {+ age = now() - heldToken.at;+ } else if (!gone) {+ // No complete token. The 'wx' create makes the file BEFORE it writes the token, so an empty file is+ // usually a holder caught mid-write — and presuming it abandoned let two writers hold the lease at+ // once. Age it by the file itself; with no pid to test, only that age can make it stale. Any other+ // stat failure leaves it held (age 0): fail-closed.+ try { age = Date.now() - fs.statSync(lp).mtimeMs; } catch (e) { gone = !!e && e.code === 'ENOENT'; }+ }+ if (gone) {+ // Released between our create and our look. Free — but free for everyone, so it is taken the same+ // exclusive way as a fresh lock. Overwriting it let a writer that created it meanwhile hold it too.+ r = tryCreate();+ if (r.ok) return r;+ return { ok: false, reason: r.code === 'EEXIST' ? 'lease taken by another writer just now' : `lease create failed: ${r.error && r.error.message}` };+ }+ // A lease that names its holder is stale only when that holder is DEAD, however old it is. A live holder+ // may be paused mid-write — a machine asleep, a debugger — and reclaiming from under it let it resume and+ // commit its stale view straight over the generation fence, a tombstone included; a release by that+ // holder could also land inside the reclaim and let a fresh writer hold the lease beside this one. Age+ // alone is kept for a lock with no readable token (a holder caught between creating the file and writing+ // it, or one that crashed there): with no pid to test, only age can say it was abandoned. The cost is a+ // holder that crashed and whose pid a live process now has: its lock is never reclaimed and every write+ // fails closed, so an old one says which file to delete.+ const stale = heldToken !== null ? !isAlive(heldToken.pid) : age > staleMs;+ if (!stale) {+ const old = age > staleMs ? ` — held for ${Math.round(age / 60000)} min; if no build or teardown of this workspace is running, delete ${lp} and re-run` : '';+ return { ok: false, reason: `lease held by pid ${held && held.pid} (age ${age}ms)${old}`, heldBy: held };+ }+ // Reclaim EXCLUSIVELY. Only the writer that creates the claim file — the same exclusive create as the+ // lock itself — may replace the stale lock, and only while the lock still holds exactly what it judged+ // stale. Overwriting and reading back alone let two reclaimers each read their own token back before the+ // other's write landed, and both held the lease.+ const claim = `${lp}.reclaim`;+ try { createExclusive(claim, token); } catch (e) {+ if (!(e && e.code === 'EEXIST')) return { ok: false, reason: `stale lease reclaim failed: ${e && e.message}` };+ // Another writer is reclaiming right now — or crashed doing so. A claim is abandoned by the rule the lock+ // itself follows (above): once its claimer's pid is dead, or, for one with no readable token, once it is+ // older than the staleness window. Age alone let a claimer paused mid-reclaim lose its claim to a second+ // reclaimer, and both then held the lease.+ //+ // An abandoned claim is NOT removed: it says which file to delete, as an old lease does (above). Removing+ // it is a read and then a delete, and nothing in the filesystem makes "delete it only while it is still+ // that one" a single step — so two writers could both judge it abandoned, the second delete it, claim and+ // pause mid-reclaim, and the first's delete then took the SECOND writer's live claim; the first claimed+ // again, and both held the lease. Only the writer that created a claim ever removes it (below), which+ // keeps it exclusive. A claimer crashing inside the few file operations a reclaim takes is rare; two+ // holders of one lease are no price for sparing that.+ let hint = '';+ try {+ const claimRaw = fs.readFileSync(claim, 'utf8');+ let owner = null;+ try { owner = JSON.parse(claimRaw); } catch { owner = null; }+ const claimAge = Date.now() - fs.statSync(claim).mtimeMs;+ const named = !!owner && typeof owner.pid === 'number' && typeof owner.at === 'number';+ const abandoned = named ? !isAlive(owner.pid) : claimAge > staleMs;+ const remedy = `if no build or teardown of this workspace is running, delete ${claim} and re-run`;+ if (abandoned) hint = ` — the reclaim was abandoned (${named ? `its claimer, pid ${owner.pid}, is gone` : 'its claim is older than the staleness window'}); ${remedy}`;+ else if (claimAge > staleMs) hint = ` — claimed for ${Math.round(claimAge / 60000)} min; ${remedy}`;+ } catch { /* best-effort: a claim that vanished meanwhile needs no hint */ }+ return { ok: false, reason: `lease being reclaimed by another writer${hint}` };+ }+ try {+ let nowRaw = null;+ try { nowRaw = fs.readFileSync(lp, 'utf8'); } catch (e) { if (!(e && e.code === 'ENOENT')) throw e; }+ if (nowRaw !== heldRaw) return { ok: false, reason: 'lease changed while it was being reclaimed' };+ fs.writeFileSync(lp, token);+ // Read back as well: a writer that ignored the claim protocol still cannot make two holders silently.+ if (fs.readFileSync(lp, 'utf8') !== token) return { ok: false, reason: 'lease reclaimed by another writer just now' };+ return { ok: true, path: lp, token, reclaimed: true };+ } catch (e) {+ // The write may have landed before what failed (the read-back, say). A lock left holding OUR token is one+ // no other writer would reclaim — its pid is alive: ours — so it is released here, owner-checked; if even+ // that fails, it frees once this process exits.+ try { if (fs.readFileSync(lp, 'utf8') === token) fs.rmSync(lp, { force: true }); } catch { /* best-effort */ }+ return { ok: false, reason: `stale lease reclaim failed: ${e.message}` };+ } finally {+ // Ours: only the writer that created a claim removes it. One left behind names itself as the file to delete (above).+ try { fs.rmSync(claim, { force: true }); } catch { /* best-effort */ }+ }}// Owner-checked release: remove the lock ONLY if it still holds OUR exact token (a build that reclaimed our@@ -108,20 +227,32 @@ function releaseLease(handle) {catch { /* gone/unreadable — best-effort */ }}-// CAS write (call while holding the lease). Refuse to overwrite when the on-disk generation no longer-// matches what the caller last read — a concurrent build won the race. expectedGeneration === null means-// "I expected NO prior snapshot" (first write); if one appeared meanwhile, refuse. Returns { ok, reason }.-function casWriteSnapshot(workspaceDir, envelope, expectedGeneration) {- const disk = readSnapshot(workspaceDir);- if (expectedGeneration == null) {- if (disk) return { ok: false, reason: 'expected no prior snapshot but one exists (concurrent create)' };- } else if (!disk) {- return { ok: false, reason: 'expected snapshot vanished (concurrent delete/teardown)' };- } else if (!generationMatches(disk, expectedGeneration)) {- return { ok: false, reason: 'generation CAS failed (concurrent snapshot write)' };+// CAS write. Refuse to overwrite when the on-disk generation no longer matches what the caller last read —+// a concurrent build won the race. expectedGeneration === null means "I expected NO prior snapshot" (first+// write); if one appeared meanwhile, refuse. Returns { ok, reason }.+//+// Takes the workspace lease ITSELF. The compare and the write are two steps, and the lease is what+// serializes a teardown tombstone against every other snapshot write: without it, a tombstone written+// between this read and this write was silently overwritten by a pre-teardown view (#587 item 1). No+// caller held the lease across this call, whatever this comment used to ask of them. A held lease means+// another writer is mid-update, so the write is refused (fail-closed: the next run full-builds).+function casWriteSnapshot(workspaceDir, envelope, expectedGeneration, deps = {}) {+ const lease = acquireLease(workspaceDir, deps);+ if (!lease.ok) return { ok: false, reason: `snapshot lease unavailable (${lease.reason})` };+ try {+ const disk = readSnapshot(workspaceDir);+ if (expectedGeneration == null) {+ if (disk) return { ok: false, reason: 'expected no prior snapshot but one exists (concurrent create)' };+ } else if (!disk) {+ return { ok: false, reason: 'expected snapshot vanished (concurrent delete/teardown)' };+ } else if (!generationMatches(disk, expectedGeneration)) {+ return { ok: false, reason: 'generation CAS failed (concurrent snapshot write)' };+ }+ writeSnapshotAtomic(workspaceDir, envelope);+ return { ok: true };+ } finally {+ releaseLease(lease);}- writeSnapshotAtomic(workspaceDir, envelope);- return { ok: true };}// Unconditional persist under the lease (no CAS) — used to seed the very first snapshot or to write a@@ -138,11 +269,25 @@ function persistSnapshot(workspaceDir, envelope) {// `generation` is the new post-invalidate token the caller must pass as the CAS `expected` on its re-bless.// Fail-closed callers (the fast-path apply) MUST abort if this returns { ok:false }. A missing snapshot is// already-safe (nothing can fast-path) ⇒ ok:true with generation:null.-function invalidateSnapshot(workspaceDir, deps = {}) {- const lease = acquireLease(workspaceDir, deps);+//+// `options.expectedGeneration` FENCES the invalidate to the snapshot the caller's decision was based on+// (#587 item 1). Rotating the generation only protects a reader who is later compared against it, and+// without this the invalidate itself was never compared: a run that read an eligible snapshot, then lost+// the race to a teardown tombstone, invalidated the TOMBSTONED copy, got a fresh generation back, and+// re-blessed its stale view over the tombstone. With the key present the invalidate refuses unless the+// disk still holds that very generation — so a snapshot that was tombstoned, rewritten, or deleted since+// it was read stops the run before it mutates. Absent the key (a plain `--apply`, which decided nothing+// from a read), behavior is unchanged. The remaining keys are the lease test seams (see acquireLease).+function invalidateSnapshot(workspaceDir, options = {}) {+ const lease = acquireLease(workspaceDir, options);if (!lease.ok) return { ok: false, reason: lease.reason };try {const disk = readSnapshot(workspaceDir);+ const fenced = Object.prototype.hasOwnProperty.call(options, 'expectedGeneration');+ if (fenced && !disk) return { ok: false, reason: 'the snapshot this run read has since been deleted (a concurrent teardown?) — re-run' };+ if (fenced && (disk.generation || null) !== (options.expectedGeneration || null)) {+ return { ok: false, reason: 'the snapshot changed since this run read it (a concurrent teardown or build) — re-run' };+ }if (!disk) return { ok: true, reason: 'no snapshot to invalidate', generation: null };markIneligible(disk);const gen = newGeneration();@@ -158,16 +303,130 @@ function invalidateSnapshot(workspaceDir, deps = {}) {// TOMBSTONE-before-delete: mark a teardown-in-progress (eligible:false + teardown debt) and persist, BEFORE// any live delete. A partial/crashed teardown then leaves the tombstone so a surviving artifact can never be-// rebaselined. No snapshot ⇒ nothing to tombstone (ok). Under the lease.+// rebaselined. Under the lease.+//+// It also ROTATES the generation, which is what makes it a fence rather than a label (#587 item 1): every+// in-flight changed-only run holds the generation it read, and its invalidate and re-bless both compare+// against it, so a tombstone that kept the old token let such a run erase it. The teardown caller refuses+// to delete anything when this returns { ok:false } (#587 item 2).+//+// NO snapshot is fenced as well, with a fresh tombstone. A first changed-only build has no snapshot until+// it finishes, and this used to answer "nothing to fence" there — so that build went on to write an+// eligible baseline for the app this teardown had just deleted. The fresh tombstone refuses such a build's+// claim (claimBaselineSnapshot) if it has not claimed yet; a placeholder it already claimed is tombstoned+// like any snapshot, which rotates the generation its baseline write expects. An unreadable file is+// replaced the same way: parseEnvelope answers null for it, and a build would overwrite it just the same.+//+// That needs the workspace folder, so a missing one is created and reported as `createdDir` (the first+// folder mkdir made), for the caller to remove after a clean teardown (removeCreatedDir). A folder that+// CANNOT be created is one no build can use either — it keeps its SDK state there, and a claim or a+// baseline write needs the same mkdir — so that one case still answers ok without writing.+const CANNOT_CREATE = new Set(['EACCES', 'EPERM', 'EROFS', 'ENOTDIR', 'EEXIST', 'ENOENT', 'EINVAL', 'ENAMETOOLONG']);+const MKDIR_ATTEMPTS = 5;++// The teardowns in flight, as a tombstone lists them (see releaseTombstone). A running teardown refreshes its+// entry's `beat` every TEARDOWN_BEAT_MS (beatTeardown), and an entry counts only while its process is alive+// AND it was seen within TEARDOWN_STALE_MS. A pid alone was not enough: a teardown that was KILLED never+// drops its entry, its pid can be reused — or come from another machine sharing the workspace — and the+// entry then kept every --changed-only build refused, and every later clean teardown "left", for a day.+const TEARDOWN_BEAT_MS = 60 * 1000;+const TEARDOWN_STALE_MS = 5 * 60 * 1000;+const lastSeen = (t) => (typeof t.beat === 'number' ? t.beat : t.at);+function liveTeardowns(disk, deps = {}) {+ const now = typeof deps.now === 'function' ? deps.now : Date.now;+ const isAlive = typeof deps.processAlive === 'function' ? deps.processAlive : processAlive;+ const list = disk && Array.isArray(disk.teardowns) ? disk.teardowns : [];+ return list.filter((t) => t && typeof t.id === 'string' && typeof t.at === 'number' && now() - lastSeen(t) < TEARDOWN_STALE_MS && isAlive(t.pid));+}+// The teardowns a snapshot says are still running — what a changed-only build waits for (changed-only-flow.js).+function teardownsInFlight(envelope) { return liveTeardowns(envelope); }++// Refresh a running teardown's entry (see liveTeardowns). Best-effort and quiet: one attempt at the lease, and+// a busy lease or a vanished entry just skips this beat — the next one tries again. It never rotates the+// generation: a beat moves no fence.+function beatTeardown(workspaceDir, teardownId, deps = {}) {+ const now = typeof deps.now === 'function' ? deps.now : Date.now;+ let lease = null;+ try {+ if (!fs.existsSync(snapshotPath(workspaceDir))) return { ok: false, reason: 'no snapshot' };+ lease = acquireLease(workspaceDir, deps);+ if (!lease.ok) return { ok: false, reason: lease.reason };+ const disk = readSnapshot(workspaceDir);+ const mine = disk && Array.isArray(disk.teardowns) ? disk.teardowns.find((t) => t && t.id === teardownId) : null;+ if (!mine) return { ok: false, reason: 'no entry for this teardown' };+ mine.beat = now();+ writeSnapshotAtomic(workspaceDir, disk);+ return { ok: true };+ } catch (e) {+ return { ok: false, reason: `beat failed: ${e.message}` };+ } finally {+ if (lease && lease.ok) releaseLease(lease);+ }+}++// A Windows NAMESPACED path in its plain form: `\\?\C:\x` → `C:\x`, `\\?\UNC\server\share\x` →+// `\\server\share\x`; anything else unchanged. Node 22 on Windows returns the folder a recursive mkdirSync+// created in the namespaced form (Node 20 returns it plain), and every path it is compared with is plain —+// so the teardown never recognised the folder it had created, and left it behind.+function plainPath(p) {+ if (typeof p !== 'string') return p;+ if (/^\\\\\?\\UNC\\/i.test(p)) return `\\\\${p.slice(8)}`;+ if (p.startsWith('\\\\?\\')) return p.slice(4);+ return p;+}+function tombstoneSnapshot(workspaceDir, deps = {}) {- const lease = acquireLease(workspaceDir, deps);+ const mkdir = typeof deps.mkdirSync === 'function' ? deps.mkdirSync : fs.mkdirSync;+ let createdDir;+ try {+ // Returns the first folder it created, or undefined when the whole path already existed — namespaced+ // on Node 22 for Windows (see plainPath).+ //+ // An ENOENT is retried. A folder moved away between mkdir's own steps — a --clear-workspace renaming it+ // aside (clearWorkspace) — surfaces as ENOENT from a folder that existed a moment before, and read as "no+ // workspace can exist here": the teardown then ran with no fence while a build could recreate the folder+ // and bless a baseline. A race resolves on the next attempt, which makes a fresh folder; a path that truly+ // cannot exist, on a drive that is not there, fails the same way every time.+ for (let attempt = 1; ; attempt += 1) {+ try {+ createdDir = plainPath(mkdir(workspaceDir, { recursive: true })) || null;+ break;+ } catch (e) {+ if (!(e && e.code === 'ENOENT')) throw e;+ // Retries only buy time: a folder that kept vanishing is no proof that none can exist, so running out of+ // them fails closed — a teardown with no fence while a build recreates the folder is what they exist to stop.+ if (attempt >= MKDIR_ATTEMPTS) return { ok: false, reason: `tombstone failed: the workspace at ${workspaceDir} kept vanishing while it was being prepared (ENOENT) — another teardown may be clearing it, or the path cannot exist; re-run, or pass another --workspace` };+ }+ }+ } catch (e) {+ // Any other code (EBUSY, EMFILE, ENOSPC, EIO, …) is transient: a build could still get the folder, so+ // the teardown fails closed rather than proceed unfenced.+ // …but only when the workspace really is not there. mkdir over an EXISTING folder succeeds, so these codes+ // mean the folder is absent — unless a platform refuses it anyway (a folder it cannot write, say): then+ // a snapshot may sit there unfenced, and that fails closed like any other failure.+ if (e && CANNOT_CREATE.has(e.code)) {+ let absent;+ try { absent = !fs.statSync(workspaceDir).isDirectory(); } catch (se) { absent = !!se && (se.code === 'ENOENT' || se.code === 'ENOTDIR'); }+ if (absent) return { ok: true, reason: `no workspace can exist at ${workspaceDir} (${e.code}), so there is no snapshot to fence` };+ return { ok: false, reason: `tombstone failed: the workspace at ${workspaceDir} is there but could not be prepared (${e.code}), so its snapshot cannot be fenced` };+ }+ return { ok: false, reason: `tombstone failed: ${e && e.message}` };+ }+ let lease;+ try { lease = acquireLease(workspaceDir, deps); } catch (e) { return { ok: false, reason: `tombstone failed: ${e.message}` }; }if (!lease.ok) return { ok: false, reason: lease.reason };try {- const disk = readSnapshot(workspaceDir);- if (!disk) return { ok: true, reason: 'no snapshot to tombstone' };+ const disk = readSnapshot(workspaceDir) || makeEnvelope({});tombstone(disk);+ // Every teardown in flight is listed, so one that finishes first leaves the fence standing for the+ // others (releaseTombstone). The id names this one — the generation cannot, since any later write+ // rotates it.+ const teardownId = newGeneration();+ const now = typeof deps.now === 'function' ? deps.now : Date.now;+ disk.teardowns = [...liveTeardowns(disk, deps), { id: teardownId, pid: deps.pid != null ? deps.pid : process.pid, at: now() }];+ bumpGeneration(disk, newGeneration());writeSnapshotAtomic(workspaceDir, disk);- return { ok: true };+ return { ok: true, createdDir, generation: disk.generation, teardownId };} catch (e) {return { ok: false, reason: `tombstone failed: ${e.message}` };} finally {@@ -175,6 +434,74 @@ function tombstoneSnapshot(workspaceDir, deps = {}) {}}+// CLAIM the workspace for a FIRST changed-only baseline — the no-snapshot twin of the fenced invalidate.+//+// A run that read no snapshot had nothing to be fenced by: its baseline write expects "no snapshot"+// (casWriteSnapshot with expected null), and a concurrent teardown that found none either never changed+// that. The claim gives the run a generation of its own. Under the lease, and only while there is still no+// snapshot, it writes a placeholder whose generation the run passes as its baseline CAS `expected`: a+// teardown that lands after the claim tombstones the placeholder (rotating that generation), so the write+// is refused; one that landed since the run's read left a tombstone, so the claim is refused and the run+// stops before it builds anything.+//+// The placeholder is ineligible with no priorSpec — exactly "no baseline yet" — and carries NO debt on+// purpose: a later run that reads it (this one crashed) passes it as the `prior` of its own baseline, which+// inherits prior debt, and a debt here would keep that app ineligible for good. `identity` is the live+// identity the run resolved, so a later read reports "not eligible" rather than an identity mismatch.+// Returns { ok, generation } or { ok:false, reason }.+function claimBaselineSnapshot(workspaceDir, identity, deps = {}) {+ let lease;+ try { lease = acquireLease(workspaceDir, deps); } catch (e) { return { ok: false, reason: `claim failed: ${e.message}` }; }+ if (!lease.ok) return { ok: false, reason: `snapshot lease unavailable (${lease.reason})` };+ try {+ if (readSnapshot(workspaceDir)) return { ok: false, reason: 'a snapshot appeared since this run found none (a concurrent teardown or build) — re-run' };+ const env = makeEnvelope(identity || {});+ writeSnapshotAtomic(workspaceDir, env);+ return { ok: true, generation: env.generation };+ } catch (e) {+ return { ok: false, reason: `claim failed: ${e.message}` };+ } finally {+ releaseLease(lease);+ }+}++// Undo claimBaselineSnapshot for a run that writes no baseline over its placeholder (the changed-only+// no-identity fallback, which claims one only to have a generation to compare after its build). Deletes the+// placeholder under the lease, and only while it is still the one this run claimed: anything else there now —+// a teardown's tombstone, another build's baseline — belongs to someone else and stays. Best-effort: a+// placeholder left behind is ineligible and debt-free, exactly "no baseline yet". Returns { ok, reason? }.+function dropBaselineClaim(workspaceDir, generation, deps = {}) {+ let lease;+ try { lease = acquireLease(workspaceDir, deps); } catch (e) { return { ok: false, reason: `drop failed: ${e.message}` }; }+ if (!lease.ok) return { ok: false, reason: `snapshot lease unavailable (${lease.reason})` };+ try {+ const disk = readSnapshot(workspaceDir);+ if (!disk || disk.generation !== generation) return { ok: false, reason: 'the snapshot is no longer the placeholder this run claimed' };+ fs.rmSync(snapshotPath(workspaceDir), { force: true });+ return { ok: true };+ } catch (e) {+ return { ok: false, reason: `drop failed: ${e.message}` };+ } finally {+ releaseLease(lease);+ }+}++// Undo tombstoneSnapshot's folder creation after a clean teardown: remove the folders it created, deepest+// first, up to and including `createdDir`. rmdir — never a recursive rm — so a folder that is no longer+// empty (a build started meanwhile and wrote into it) is left alone, and so is every folder above it. A+// teardown from a folder that never had a workspace then leaves none behind. Best-effort.+function removeCreatedDir(workspaceDir, createdDir) {+ if (!createdDir) return;+ const top = path.resolve(plainPath(createdDir));+ // Deepest first. The walk ends when it steps above `top` — or at once, for a caller passing an unrelated+ // pair — so nothing outside what mkdir created is ever touched.+ for (let dir = path.resolve(workspaceDir); ; dir = path.dirname(dir)) {+ const rel = path.relative(top, dir);+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) return;+ try { fs.rmdirSync(dir); } catch { return; }+ }+}+// Delete the snapshot file — ONLY after a teardown has verified live absence (the caller's responsibility).// Best-effort; a missing file is success.function deleteSnapshot(workspaceDir) {@@ -182,20 +509,213 @@ function deleteSnapshot(workspaceDir) {catch (e) { return { ok: false, reason: `delete failed: ${e.message}` }; }}+// A run that found the workspace changed under it and could not invalidate the snapshot there (every attempt refused,+// the lease held by a live writer: distrustWorkspace, changed-only-flow.js) records that HERE, beside the snapshot and+// outside the lease. The lease is exactly what it could not get, and whatever that writer puts in the snapshot next,+// an eligible baseline say, certifies a state this run may since have changed. The next --changed-only run finds a+// marker and builds in full, however eligible the snapshot reads (decideChangedOnly); a full build that lands its own+// baseline deletes the markers it found when it started (clearDistrust), and the last teardown deletes them all with+// the snapshot (releaseTombstone).+//+// One file per refusal, `apply-snapshot.distrust.<id>.json`, never a shared one: a marker is then only ever created or+// deleted, never moved, rewritten or put back. A single shared marker had to be moved aside to be cleared safely, and+// while it was aside a concurrent run saw no marker at all (and saw none for good if putting it back failed); putting+// back an older marker over a newer one also let an earlier run clear the newer refusal. Written temp then rename, so a+// reader sees a whole marker or none: the temp name ends `.tmp`, and a reader lists `.json` names only.+const DISTRUST_PREFIX = 'apply-snapshot.distrust.';+const DISTRUST_SUFFIX = '.json';+const isDistrustMarker = (name) => typeof name === 'string' && name.startsWith(DISTRUST_PREFIX) && name.endsWith(DISTRUST_SUFFIX)+ && !/[\\/]/.test(name);+// Returns { ok, reason? }.+function markDistrusted(workspaceDir, { reason } = {}) {+ const id = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;+ const target = path.join(workspaceDir, `${DISTRUST_PREFIX}${id}${DISTRUST_SUFFIX}`);+ const tmp = `${target}.tmp`;+ try {+ fs.mkdirSync(workspaceDir, { recursive: true });+ fs.writeFileSync(tmp, JSON.stringify({ id, reason: reason || null, pid: process.pid, at: new Date().toISOString() }));+ fs.renameSync(tmp, target);+ return { ok: true };+ } catch (e) {+ try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup of the temp */ }+ return { ok: false, reason: e.message };+ }+}++// The workspace's distrust markers as { names, reason }, or null when there are none. `names` is what this run will+// clear, and only that (clearDistrust). A marker that cannot be read or parsed still counts (fail closed): a marker+// nobody can read has not said the workspace is trusted again. A folder that cannot be listed counts too, with no+// names, so nothing is cleared.+function readDistrust(workspaceDir) {+ let names;+ try { names = fs.readdirSync(workspaceDir).filter(isDistrustMarker).sort(); } catch (e) {+ if (e && e.code === 'ENOENT') return null;+ return { names: [], reason: `the workspace could not be listed for distrust markers (${(e && e.code) || e})` };+ }+ if (!names.length) return null;+ let reason = null;+ for (const name of names) {+ try {+ const m = JSON.parse(fs.readFileSync(path.join(workspaceDir, name), 'utf8'));+ if (m && typeof m.reason === 'string' && m.reason) { reason = m.reason; break; }+ } catch { /* unreadable: it still counts */ }+ }+ return { names, reason: reason || 'no readable reason recorded' };+}++// Delete the markers a run found when it started (`names`, from readDistrust), and only those: a marker written since+// is another run's, which found the workspace changed under IT, and this run's baseline cannot vouch for what that run+// did. Each is deleted by its own name, so no other marker is ever out of place. Returns { ok, cleared, reason? }; a+// marker that cannot be deleted stays, and the next run builds in full again.+function clearDistrust(workspaceDir, names) {+ let cleared = 0;+ const failed = [];+ for (const name of Array.isArray(names) ? names : []) {+ if (!isDistrustMarker(name)) continue;+ try { fs.rmSync(path.join(workspaceDir, name), { force: true }); cleared += 1; } catch (e) { failed.push(`${name} (${(e && e.code) || e})`); }+ }+ return failed.length ? { ok: false, cleared, reason: `could not delete ${failed.join(', ')}` } : { ok: true, cleared };+}++// End a teardown's hold on the snapshot. tombstoneSnapshot lists every teardown in flight, and every+// teardown that has FINISHED drops its entry here, under the lease — a finished teardown is no longer in+// flight, and an entry left behind read as one still running whenever its pid was alive (reused, slow to+// exit, or the very process a caller runs teardowns in), so a later clean teardown kept the fence for up to+// a day. Then:+// · `deps.keep` (the teardown failed or threw) → the tombstone stays whatever else is running — a+// surviving artifact must not be rebaselined — with its generation rotated. → { kept: true, left }+// · other teardowns of this workspace are still running → the tombstone stays, with the generation+// rotated, and goes on fencing their deletes. Deleting it when the first of two overlapping teardowns+// finished — in either order — let a first changed-only build claim and bless a baseline for an app+// the other was still deleting. → { left: true }+// · this was the last → the snapshot is deleted, WHATEVER it now is: this tombstone, or anything a+// writer put in its place — a snapshot is never left behind once the app is gone. → { deleted: true }+// · there is no snapshot (or no workspace at all) → nothing to release, and the folder is not recreated+// for it. → { gone: true }+// A lease another writer holds for a moment (a build persisting its snapshot) is retried briefly, for the+// same reason: giving up at once left the entry behind.+const RELEASE_ATTEMPTS = 5;+const RELEASE_WAIT_MS = 200;+// A synchronous pause: the store is synchronous throughout, and a teardown waiting 200 ms blocks nothing+// else in its own process.+function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }+function releaseTombstone(workspaceDir, teardownId, deps = {}) {+ if (!fs.existsSync(snapshotPath(workspaceDir))) return { ok: true, deleted: false, gone: true };+ const attempts = deps.attempts != null ? deps.attempts : RELEASE_ATTEMPTS;+ const sleep = typeof deps.sleep === 'function' ? deps.sleep : sleepSync;+ let lease;+ for (let attempt = 1; ; attempt += 1) {+ try { lease = acquireLease(workspaceDir, deps); } catch (e) { return { ok: false, deleted: false, reason: `release failed: ${e.message}` }; }+ if (lease.ok || attempt >= attempts) break;+ sleep(RELEASE_WAIT_MS);+ }+ if (!lease.ok) return { ok: false, deleted: false, reason: `snapshot lease unavailable (${lease.reason})` };+ try {+ if (!fs.existsSync(snapshotPath(workspaceDir))) return { ok: true, deleted: false, gone: true };+ // An unreadable file is replaced like tombstoneSnapshot replaces it; a clean last release deletes it.+ const disk = readSnapshot(workspaceDir) || makeEnvelope({});+ const others = liveTeardowns(disk, deps).filter((t) => t.id !== teardownId);+ if (others.length || deps.keep) {+ disk.teardowns = others;+ tombstone(disk);+ bumpGeneration(disk, newGeneration());+ writeSnapshotAtomic(workspaceDir, disk);+ if (deps.keep) return { ok: true, deleted: false, kept: true, left: others.length > 0 };+ return { ok: true, deleted: false, left: true, reason: `${others.length} other teardown(s) of this workspace are still running` };+ }+ fs.rmSync(snapshotPath(workspaceDir), { force: true });+ // Distrust markers go with it: they say a snapshot here cannot be trusted, and the app it described is gone.+ for (const name of fs.readdirSync(workspaceDir).filter(isDistrustMarker)) fs.rmSync(path.join(workspaceDir, name), { force: true });+ return { ok: true, deleted: true };+ } catch (e) {+ return { ok: false, deleted: false, reason: `release failed: ${e.message}` };+ } finally {+ releaseLease(lease);+ }+}++// --clear-workspace, after a clean teardown: remove the workspace folder — only while holding its lease, and+// only when no snapshot is in it. This teardown's release already deleted its own, so one there now was+// written since: another teardown's tombstone or a build's first baseline, and deleting the folder deleted+// that fence. The folder is RENAMED aside under the lease and only then deleted. A recursive delete is many+// steps, and removing the folder in place, after the release — as the CLI used to — left a window in which a+// second teardown's fresh tombstone went with it; a rename is one step, and afterwards the path is simply+// absent, for whoever comes next to start afresh (the lock went with the folder). A rename refused — a file+// held open on Windows, say — clears nothing. `target` is the folder checkWorkspaceClearable approved;+// `deps.beforeRename` is a test seam, called under the lease just before the rename. Returns+// { ok, reason?, leftover? }.+function clearWorkspace(target, deps = {}) {+ let lease;+ try { lease = acquireLease(target, deps); } catch (e) { return { ok: false, reason: `the workspace lease could not be taken (${e.message})` }; }+ if (!lease.ok) return { ok: false, reason: `the workspace is in use (${lease.reason})` };+ let aside = null;+ let reserved = false;+ const claim = `${leasePath(target)}.reclaim`;+ try {+ if (fs.existsSync(snapshotPath(target))) {+ return { ok: false, reason: 'a changed-only snapshot was written to it after this teardown finished — another teardown or build of it is running' };+ }+ // The reclaim claim is reserved too, the way a reclaimer takes it (acquireLease): a reclaim in progress+ // refuses the clear, and none can start while the folder is moved. A claim that moved WITH the folder was+ // later deleted by its reclaimer by path — in a folder recreated there, another writer's live claim. Ours+ // moves with the folder and goes with it.+ try { createExclusive(claim, lease.token); } catch (e) {+ return { ok: false, reason: e && e.code === 'EEXIST' ? `a reclaim of its lease is in progress — if no build or teardown of this workspace is running, delete ${claim} and re-run` : `its lease could not be reserved (${(e && e.code) || e})` };+ }+ reserved = true;+ if (typeof deps.beforeRename === 'function') deps.beforeRename();+ const candidate = `${target}.cleared-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;+ fs.renameSync(target, candidate);+ aside = candidate;+ } catch (e) {+ return { ok: false, reason: `it could not be moved aside (${(e && e.code) || (e && e.message) || e})` };+ } finally {+ // Once moved, the lock and the claim went with the folder: nothing is left here to release.+ if (!aside) {+ if (reserved) { try { fs.rmSync(claim, { force: true }); } catch { /* best-effort: it names itself (acquireLease) */ } }+ releaseLease(lease);+ }+ }+ try {+ fs.rmSync(aside, { recursive: true, force: true });+ } catch (e) {+ return { ok: true, leftover: aside, reason: `its contents were moved to ${aside}, which could not be deleted (${(e && e.code) || e}); delete it by hand` };+ }+ return { ok: true };+}+module.exports = {SNAPSHOT_FILE,LEASE_FILE,+ DISTRUST_PREFIX,+ DISTRUST_SUFFIX,LEASE_STALE_MS,snapshotPath,leasePath,readSnapshot,+ snapshotAbsent,writeSnapshotAtomic,processAlive,+ createExclusive,acquireLease,releaseLease,casWriteSnapshot,persistSnapshot,invalidateSnapshot,tombstoneSnapshot,+ claimBaselineSnapshot,+ dropBaselineClaim,+ removeCreatedDir,+ plainPath,deleteSnapshot,+ markDistrusted,+ readDistrust,+ clearDistrust,+ releaseTombstone,+ clearWorkspace,+ teardownsInFlight,+ beatTeardown,+ TEARDOWN_BEAT_MS,+ TEARDOWN_STALE_MS,+ RELEASE_ATTEMPTS,};diff --git a/plugins/model-apps/scripts/lib/apply-snapshot.js b/plugins/model-apps/scripts/lib/apply-snapshot.jsindex e5eaaa300..9c9cf89f3 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot.js@@ -194,13 +194,18 @@ function generationMatches(diskEnvelope, expectedGeneration) {}// THE gate: may we take the `--changed-only` fast path against `live`? Fail-closed — returns-// { eligible:false, reason } unless EVERY condition holds: valid schema-3 envelope, identity matches live,-// not tombstoned, eligible flag true, empty debt, and a generation present (needed for the write-CAS).+// { eligible:false, reason } unless EVERY condition holds: valid schema-3 envelope, not tombstoned, identity+// matches live, eligible flag true, empty debt, and a generation present (needed for the write-CAS).+//+// The tombstone is checked BEFORE identity so it is the reason reported. A teardown that found no snapshot+// writes a fresh tombstone that carries no identity (it never asks WhoAmI), and an identity-first gate+// called that "orgId mismatch (different Dataverse org)" — fail-closed either way, but it sent the reader+// looking for the wrong problem.function isFastPathEligible(envelope, live) {if (!isEnvelope(envelope)) return { eligible: false, reason: 'no valid snapshot (full build)' };+ if (isTombstoned(envelope)) return { eligible: false, reason: 'snapshot tombstoned by a teardown' };const idm = identityMatches(envelope, live);if (!idm.ok) return { eligible: false, reason: idm.reason };- if (isTombstoned(envelope)) return { eligible: false, reason: 'snapshot tombstoned by a teardown' };if (envelope.eligible !== true) return { eligible: false, reason: 'snapshot not eligible (last apply was full/unsupported or invalidated)' };if (envelope.debt.length > 0) return { eligible: false, reason: `snapshot carries ${envelope.debt.length} open debt entr${envelope.debt.length === 1 ? 'y' : 'ies'}` };if (!envelope.generation) return { eligible: false, reason: 'snapshot missing generation token (cannot CAS)' };diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.jsindex 16cf3118e..5bd6f77b8 100644--- a/plugins/model-apps/scripts/lib/artifact-intent.js+++ b/plugins/model-apps/scripts/lib/artifact-intent.js@@ -11,7 +11,7 @@// the SDK's generic mutation surface without hardcoding form-model logic everywhere.const { entityByLogical } = require('./_graph.js');-const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf } = require('./app-spec.js');+const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames } = require('./app-spec.js');const { SDK_COLUMN_TYPE } = require('./entity-provision.js');// Arrange field cells into `columns` cells-per-row.@@ -691,6 +691,11 @@ function compileFormIntent(spec, formSpec, opts) {// combination, but `compileFormIntent` is called directly too, so the flag states what actually// happened rather than what was asked for.__explicitLayout: Array.isArray(formSpec.tabs),+ // The section names the author declared (see `authoredSectionNames`), so the engine's reconcile+ // skips the same containers verify skips. An array, because the compiled def is plain data.+ __authoredSectionNames: [...authoredSectionNames(formSpec)],+ // …and the subset the author NAMED, which the engine's sweep reads to word its report.+ __namedSectionNames: [...authoredSectionNames(formSpec, { named: true })],// Ordering anchors: { <logical>: <anchorLogical> }. Consumed by the engine's reconcile, which// MOVES an existing control to sit immediately after its anchor. Kept off the cells because a// cell is pushed verbatim to the SDK and `after` is not part of its model (see `positions`).@@ -844,7 +849,9 @@ function findFieldCellLocation(formJson, logical) {// The search is form-wide rather than scoped to the expected tab on purpose: section names are// unique per form in Dataverse, and a section a maker dragged to another tab is still THAT section.// Scoping the lookup to the tab the spec now names would miss it and create a duplicate beside it.-function findSectionLocation(formJson, sectionName) {+// `accept`, when given, filters the candidates: an authored section must never resolve to an+// engine-owned host that happens to share its name (sdk-build.js, the form topology pass).+function findSectionLocation(formJson, sectionName, accept) {const want = String(sectionName || '').toLowerCase();if (!want) return null;const tabs = formJson.tabs || [];@@ -854,6 +861,7 @@ function findSectionLocation(formJson, sectionName) {const sections = cols[ci].sections || [];for (let si = 0; si < sections.length; si++) {if (String(sections[si].name || '').toLowerCase() !== want) continue;+ if (accept && !accept(sections[si])) continue;const pointer = '/tabs/' + ti + '/columns/' + ci + '/sections/' + si;return { pointer, rowsPointer: pointer + '/rows', tabIndex: ti, columnIndex: ci, sectionIndex: si, section: sections[si] };}diff --git a/plugins/model-apps/scripts/lib/changed-only-flow.js b/plugins/model-apps/scripts/lib/changed-only-flow.jsindex b06eb2716..8d44caed6 100644--- a/plugins/model-apps/scripts/lib/changed-only-flow.js+++ b/plugins/model-apps/scripts/lib/changed-only-flow.js@@ -30,9 +30,10 @@ const { odataLit } = require('./odata.js');// ---- PURE decision -------------------------------------------------------------------------------------// Decide fast vs full vs noop from the annotated spec, the persisted snapshot, and the live identity.+// Decide fast vs full vs noop from the annotated spec, the persisted snapshot, and the live identity. `distrust` is the+// workspace's distrust markers (store.readDistrust), or null.// Returns { decision:'fast'|'full'|'noop', reason, classify, pageKeys?, gateReason }.-function decideChangedOnly({ annotatedSpec, snapshot, live }) {+function decideChangedOnly({ annotatedSpec, snapshot, live, distrust = null }) {const prior = snapshot ? snapshot.priorSpec : null;const classify = classifyChanges(annotatedSpec, prior);const gate = snap.isFastPathEligible(snapshot, live);@@ -41,6 +42,11 @@ function decideChangedOnly({ annotatedSpec, snapshot, live }) {if (!snapshot) {return { decision: 'full', reason: 'no snapshot — establishing the changed-only baseline via a full build', classify, gateReason: 'no snapshot' };}+ // An earlier run found the workspace changed under it and could not invalidate the snapshot it found (distrustWorkspace+ // below): that snapshot may certify a state the run since changed, so however eligible it reads, it is not trusted.+ if (distrust) {+ return { decision: 'full', reason: `full build — an earlier run found the workspace changed under it and could not invalidate the snapshot (${distrust.reason})`, classify, gateReason: 'distrusted' };+ }// Snapshot exists but is not fast-eligible (identity mismatch / tombstoned / invalidated / carries// debt) → full build (fail-closed). The full build then re-persists the snapshot (with sticky debt).if (!gate.eligible) {@@ -187,13 +193,95 @@ async function runChangedOnlyApply({ spec, opts, deps }) {const annotate = (s) => annotateContentHashes(s, deps.readContent);const annotatedSpec = annotate(spec);const snapshot = store.readSnapshot(ws);+ const distrust = store.readDistrust(ws);+ // A teardown still running lists itself on the tombstone it wrote (apply-snapshot-store.js+ // tombstoneSnapshot), and a build now would recreate what it is deleting — the fenced invalidate below+ // would let it, the tombstone's generation being the very one this run read. So the run waits for it,+ // whichever build it would have run (the no-identity fallback included). A tombstone no teardown still+ // holds (one that failed, or was killed and stopped being seen) does not block: it only makes the+ // baseline ineligible, through its debt. A teardown starting after this read is caught by a generation fence+ // below: the invalidate's, or, in the no-identity fallback, the re-read before it builds and the check made+ // when the build returns.+ const running = store.teardownsInFlight(snapshot);+ if (running.length) {+ const who = running.map((t) => `pid ${t.pid}, last seen ${Math.max(0, Math.round((Date.now() - (typeof t.beat === 'number' ? t.beat : t.at)) / 1000))}s ago`).join('; ');+ const msg = `changed-only: ${running.length} teardown(s) of this workspace are still running (${who}) — re-run the build once they have finished. A teardown that died stops counting ${Math.round(store.TEARDOWN_STALE_MS / 60000)} minutes after it was last seen.`;+ log(`✗ ${msg}`);+ return { ok: false, errors: [msg], changedOnly: { decision: 'full', reason: 'a teardown is running' } };+ }const live = await deps.resolveLiveIdentity();// No trustworthy live identity → we cannot safely gate a fast apply. Degrade to a normal full build and// do NOT touch the snapshot (writing one we can't identity-bind would be worse than none).+ //+ // Identity discovery takes seconds, and a teardown that began meanwhile is not in the read above. The+ // branches below catch it through their fenced invalidate; this one writes no snapshot, so nothing would —+ // and the build would recreate what the teardown is deleting. So the workspace is read again, and the build+ // refused when the snapshot's generation moved: a teardown's tombstone rotates it (on a workspace with no+ // snapshot too, where it creates one), and so does another build's invalidate.+ //+ // A teardown that begins AFTER that re-read, while the build is reading or writing, is not fenced by it. The+ // other branches notice one at the end, when their baseline CAS is refused; this one has no CAS to refuse. So+ // the workspace is read once more when the build returns: a generation that moved means a teardown or another+ // build ran alongside this one, so what this build made may already be partly deleted, and the run fails+ // rather than report a success nothing can vouch for.+ //+ // The generation compared afterwards must be THIS run's own, one no other run can hold. The one it read is not:+ // with no snapshot, a teardown that begins AND finishes during the build writes its tombstone and deletes it on+ // release, so "none" before and "none" after hid it; and a second no-identity build that read the same+ // generation, built and finished inside this one, left it unchanged, so neither saw the other. So, like the+ // fenced branches, the run takes a generation of its own before it builds. On a workspace with no snapshot it+ // claims a placeholder (claimBaselineSnapshot: ineligible, debt-free, "no baseline yet") and drops it again+ // afterwards if it is still that placeholder, so this path leaves no snapshot behind. On one with a snapshot it+ // invalidates it, fenced to the generation it read, as a full build does: a baseline the build is about to+ // outdate is never left eligible.if (!live) {+ const genOf = (s) => (s && s.generation) || null;+ const seen = genOf(store.readSnapshot(ws));+ if (seen !== genOf(snapshot)) {+ const msg = 'changed-only: the workspace changed while the live identity was being resolved (a teardown or another build started) — re-run the build once it has finished';+ log(`✗ ${msg}`);+ return { ok: false, errors: [msg], changedOnly: { decision: 'full', reason: 'the workspace changed during identity discovery' } };+ }+ let claimed = null;+ let before;+ if (seen === null) {+ const claim = store.claimBaselineSnapshot(ws, {});+ if (!claim.ok) {+ const msg = `changed-only: could not claim the workspace before the build (${claim.reason}) — aborting before any change`;+ log(`✗ ${msg}`);+ return { ok: false, errors: [msg], changedOnly: { decision: 'full', reason: 'the workspace could not be claimed' } };+ }+ claimed = claim.generation;+ before = claimed;+ } else {+ const inv = store.invalidateSnapshot(ws, { expectedGeneration: seen });+ if (!inv.ok) {+ const msg = `changed-only: could not invalidate the snapshot before the build (${inv.reason}) — aborting before any change`;+ log(`✗ ${msg}`);+ return { ok: false, errors: [msg], changedOnly: { decision: 'full', reason: 'the workspace could not be claimed' } };+ }+ before = inv.generation;+ }log('▸ changed-only: could not resolve live identity (WhoAmI/app discovery) — running a normal full build');- const r = await deps.buildModelApp(spec, fullApplyOpts(opts), deps.buildDeps);+ let held;+ try {+ held = await buildHolding(ws, before, log, () => deps.buildModelApp(spec, fullApplyOpts(opts), deps.buildDeps));+ } catch (e) {+ // Only while it is still ours: a placeholder another writer has replaced is theirs.+ if (claimed) store.dropBaselineClaim(ws, claimed);+ throw e;+ }+ const { r, moved } = held;+ if (moved) {+ const msg = 'changed-only: the workspace changed while this build ran (a teardown or another build ran alongside it), so what it built may already be partly deleted — re-run the build once that has finished';+ log(`✗ ${msg}`);+ return { ...r, ok: false, errors: [...((r && r.errors) || []), msg], changedOnly: { decision: 'full', reason: 'the workspace changed during the build' } };+ }+ if (claimed) {+ const dropped = store.dropBaselineClaim(ws, claimed);+ if (!dropped.ok) log(`▸ changed-only: the placeholder this build claimed was left in place (${dropped.reason}); it is ineligible, so the next run still builds in full`);+ }return { ...r, changedOnly: { decision: 'full', reason: 'no live identity' } };}@@ -207,7 +295,7 @@ async function runChangedOnlyApply({ spec, opts, deps }) {// recoverable direction.const appPreExisted = live.appIdKnown === false ? true : !!live.appId;- let decision = decideChangedOnly({ annotatedSpec, snapshot, live });+ let decision = decideChangedOnly({ annotatedSpec, snapshot, live, distrust });// Sample-data guard (Sol #11): the baseline records whether --sample-data was applied. If THIS run asks// for sample data but the eligible baseline did not seed it, a fast/noop would never seed the rows —// force a full build so the sample-data phase runs.@@ -226,7 +314,9 @@ async function runChangedOnlyApply({ spec, opts, deps }) {// apply writes anything, so a crash mid-upload can never leave a stale "eligible" snapshot and a// concurrent reader that captured the old generation can no longer win the re-bless CAS. A failed// invalidate means lease contention (another build) → ABORT rather than risk two concurrent builds.- const inv = store.invalidateSnapshot(ws);+ // FENCED to the generation this decision was read at (#587 item 1): a teardown that tombstoned the+ // snapshot while identity was being resolved must stop this run here, before it uploads anything.+ const inv = store.invalidateSnapshot(ws, { expectedGeneration: snapshot.generation || null });if (!inv.ok) {const msg = `changed-only: could not invalidate the snapshot before the fast apply (${inv.reason}) — aborting to avoid an unsafe partial write`;log(`✗ ${msg}`);@@ -234,16 +324,25 @@ async function runChangedOnlyApply({ spec, opts, deps }) {}// selectedKeys: upload ONLY the changed pages (never clobber an unchanged one — Sol #1).const fastOpts = { ...fullApplyOpts(opts), phases: ['pages'], changedOnly: { fastApply: true, resolvedAppId: live.appId, skipSitemapFinalize: true, selectedKeys: decision.pageKeys } };- const r = await deps.buildModelApp(spec, fastOpts, deps.buildDeps);+ const { r, moved } = await buildHolding(ws, inv.generation, log, () => deps.buildModelApp(spec, fastOpts, deps.buildDeps));// Re-bless ONLY on a fully successful apply whose mandatory page verify PASSED (a fast apply always// applies the pages phase, so verify is mandatory and r.verify is always set — a missing/failed verify// leaves the snapshot invalidated, fail-closed; Sol #2/#3, Opus H4). CAS `expected` = the post-invalidate// generation (inv.generation), which the invalidate wrote; a concurrent writer that bumped it again is// detected and this re-bless is refused.- if (r && r.ok && !r.dryRun && r.verify && r.verify.ok) {+ if (r && r.ok && !r.dryRun && r.verify && r.verify.ok && moved) {+ return conflictResult(r, decision, 'fast apply', log);+ } else if (r && r.ok && !r.dryRun && r.verify && r.verify.ok) {const refreshed = assembleFastSnapshot({ snapshot, annotatedSpec, created: r.created, pageKeys: decision.pageKeys, generation: snap.newGeneration() });const cas = store.casWriteSnapshot(ws, refreshed, inv.generation);- if (!cas.ok) log(`▸ changed-only: fast apply succeeded but the snapshot was not re-blessed (${cas.reason}) — the next run will do a full build`);+ if (!cas.ok) {+ // Read before distrust rotates it: a generation that is no longer ours means another writer landed. A lease+ // held for a moment (its own write) leaves ours in place, and the run's result stands.+ const conflicted = generationOnDisk(ws) !== inv.generation;+ log(`▸ changed-only: fast apply succeeded but the snapshot was not re-blessed (${cas.reason}) — the next run will do a full build`);+ const seen = distrustWorkspace(ws, log, inv.generation);+ if (conflicted || seen.foreign || !seen.resolved) return conflictResult(r, decision, 'fast apply', log);+ }else log('✓ changed-only: fast apply verified; snapshot re-blessed eligible');} else if (r && r.ok && !r.dryRun) {log('▸ changed-only: fast apply completed but page verify did not pass — snapshot left invalidated (next run will full-build)');@@ -254,28 +353,138 @@ async function runChangedOnlyApply({ spec, opts, deps }) {// FULL build (baseline, ineligible-snapshot fallback, or an unsupported/unwired change).let expectedGen = null;if (snapshot) {- const inv = store.invalidateSnapshot(ws);+ // Fenced exactly like the fast path: the baseline this build writes is assembled from the snapshot+ // read above, so a tombstone that landed since must stop the build rather than be overwritten by it.+ const inv = store.invalidateSnapshot(ws, { expectedGeneration: snapshot.generation || null });if (!inv.ok) {const msg = `changed-only: could not invalidate the snapshot before the full apply (${inv.reason}) — aborting to avoid a concurrent build`;log(`✗ ${msg}`);return { ok: false, errors: [msg], changedOnly: decision };}expectedGen = inv.generation;+ } else {+ // No snapshot to fence against, so CLAIM one. The baseline write below would otherwise expect "none",+ // and a teardown running alongside that found none either never changes that — this build then+ // blessed an app the teardown had just deleted. The claim's generation is what the baseline CAS+ // compares: a teardown landing during the build tombstones the placeholder, so the write is refused;+ // one that landed since the read above left its tombstone, so the claim is refused and nothing runs.+ // `snapshot` stays null, so the baseline is assembled with no prior exactly as before.+ const claim = store.claimBaselineSnapshot(ws, {+ orgId: live.orgId,+ envUrl: live.envUrl,+ appUniqueName: live.appUniqueName,+ appId: live.appId,+ solutionUniqueName: annotatedSpec.solution && annotatedSpec.solution.uniqueName,+ });+ if (!claim.ok) {+ const msg = `changed-only: could not claim the workspace for the first baseline (${claim.reason}) — aborting before any change`;+ log(`✗ ${msg}`);+ return { ok: false, errors: [msg], changedOnly: decision };+ }+ expectedGen = claim.generation;}- const r = await deps.buildModelApp(spec, fullApplyOpts(opts), deps.buildDeps);- if (r && r.ok && !r.dryRun && (!r.verify || r.verify.ok)) {+ const { r, moved } = await buildHolding(ws, expectedGen, log, () => deps.buildModelApp(spec, fullApplyOpts(opts), deps.buildDeps));+ if (r && r.ok && !r.dryRun && (!r.verify || r.verify.ok) && moved) {+ return conflictResult(r, decision, 'build', log);+ } else if (r && r.ok && !r.dryRun && (!r.verify || r.verify.ok)) {// Re-resolve identity so a fresh baseline records the now-created appId (the app did not exist before// this build). created.app already carries it, so this is belt-and-suspenders.let liveForWrite = live;if (!live.appId) { const relive = await deps.resolveLiveIdentity(); if (relive) liveForWrite = relive; }const env = assembleBaselineSnapshot({ annotatedSpec, created: r.created, live: liveForWrite, prior: snapshot, appPreExisted, sampleDataApplied: !!opts.sampleData });const wrote = store.casWriteSnapshot(ws, env, expectedGen);- if (!wrote.ok) log(`▸ changed-only: full apply succeeded but the snapshot was not persisted (${wrote.reason})`);- else log(`✓ changed-only: baseline snapshot ${env.eligible ? 'ELIGIBLE' : 'recorded INELIGIBLE (open debt — a future edit needs a full build)'}`);+ if (!wrote.ok) {+ const conflicted = generationOnDisk(ws) !== expectedGen;+ log(`▸ changed-only: full apply succeeded but the snapshot was not persisted (${wrote.reason})`);+ const seen = distrustWorkspace(ws, log, expectedGen);+ if (conflicted || seen.foreign || !seen.resolved) return conflictResult(r, decision, 'build', log);+ }+ else {+ log(`✓ changed-only: baseline snapshot ${env.eligible ? 'ELIGIBLE' : 'recorded INELIGIBLE (open debt — a future edit needs a full build)'}`);+ // This full build ran over whatever the markers distrusted, and its baseline landed on the generation it held, so+ // the markers it found have done their job. One another run wrote since is left in place (clearDistrust).+ if (distrust) {+ const cleared = store.clearDistrust(ws, distrust.names);+ if (!cleared.ok) log(`▸ changed-only: a distrust marker could not be cleared (${cleared.reason}); the next run builds in full again`);+ }+ }}return { ...r, changedOnly: decision };}+const generationOnDisk = (ws) => ((store.readSnapshot(ws) || {}).generation) || null;++// A run that another writer overlapped reports FAILURE, whatever its own build returned: a teardown may have deleted+// part of what it built, another build may have overwritten it, and no baseline records it. The caller re-runs once+// the other writer has finished, as the no-identity branch already said.+function conflictResult(r, decision, what, log) {+ const msg = `changed-only: the workspace changed while this ${what} ran (a teardown or another build ran alongside it), so no baseline records it and what it wrote may already be partly deleted or overwritten — re-run the build once that has finished`;+ log(`✗ ${msg}`);+ return { ...r, ok: false, errors: [...((r && r.errors) || []), msg], changedOnly: decision };+}++// Run one build while holding generation `held`, the one this run's claim or invalidate wrote. On EVERY way out —+// a result, a failed verify, a thrown halt — a generation that has moved means another writer ran alongside this+// build, and the workspace is distrusted (below) before the result or the error goes on. A failed or halted build+// has still changed the environment, so its way out needs the check as much as a clean one. Returns { r, moved }.+async function buildHolding(ws, held, log, build) {+ const movedOn = () => (((store.readSnapshot(ws) || {}).generation) || null) !== held;+ let r;+ try {+ r = await build();+ } catch (e) {+ if (movedOn()) distrustWorkspace(ws, log);+ throw e;+ }+ const moved = movedOn();+ if (moved) distrustWorkspace(ws, log);+ return { r, moved };+}++// A run that finds the workspace changed under it (its generation moved while it built, or its baseline write was+// refused) cannot tell what the other writer recorded from what this run changed after it. A baseline another build+// blessed meanwhile would certify a state this run may since have overwritten, and a later run would noop on it; and+// a build still between its verify and its baseline write holds the generation it will CAS against, so an ineligible+// snapshot is no safer to leave as it is. So whatever is there is invalidated — made ineligible, and its generation+// rotated so that no pending writer's CAS can land — and the next run builds in full. Each invalidate is fenced to+// the generation just read and keeps the snapshot's contents: tombstone, debt and teardown list (teardowns release+// by id, not by generation). A writer landing between the read and the invalidate is read again and invalidated in+// turn.+//+// Returns what it saw, for a caller still deciding whether it was overlapped at all (a baseline write refused by a+// busy lease): `foreign` when any generation it read was not `held`, the one the caller's run holds. That lease may+// have been an older build's, about to rotate the generation, and the flag read before this call cannot see that.+// `resolved` is false when the invalidate never landed; the caller fails closed on that too. And since the snapshot+// then stays as the lease's holder leaves it, possibly eligible, the refusal is recorded beside it, outside the lease+// (store.markDistrusted): the next --changed-only run builds in full whatever it reads, on every way out of this run,+// a thrown build included.+const DISTRUST_ATTEMPTS = 4;+function distrustWorkspace(ws, log, held) {+ let reason = '';+ let foreign = false;+ for (let attempt = 1; attempt <= DISTRUST_ATTEMPTS; attempt += 1) {+ const now = store.readSnapshot(ws);+ const generation = (now && now.generation) || null;+ if (held !== undefined && generation !== held) foreign = true;+ if (!now) {+ // Only a snapshot that is provably absent leaves nothing to distrust. One that exists but reads as nothing (a+ // transient read error, a file mid-replace) may be the other writer's eligible baseline, readable again by the+ // next run, so it is a refusal like any other: read again, and recorded if it never reads.+ if (store.snapshotAbsent(ws)) return { foreign, resolved: true };+ reason = 'the snapshot exists but could not be read';+ } else {+ const inv = store.invalidateSnapshot(ws, { expectedGeneration: generation });+ if (inv.ok) return { foreign, resolved: true };+ reason = inv.reason;+ }+ // A lease another writer holds for a moment (its own snapshot write) is waited out briefly.+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);+ }+ const marked = store.markDistrusted(ws, { reason });+ log(`▸ changed-only: could not invalidate the snapshot another run left (${reason}) — ${marked.ok ? 'recorded beside it, so the next --changed-only build runs in full' : `and could not record that either (${marked.reason}): run the next build without --changed-only`}`);+ return { foreign, resolved: false };+}+// Force a FULL-phase apply: changed-only decides its own phases, so it must ignore any --stage/--only/etc.// selection carried on opts (main() also rejects combining them). phases:undefined → sdk-build uses PHASES.function fullApplyOpts(opts) {@@ -292,4 +501,5 @@ module.exports = {assembleFastSnapshot,runChangedOnlyApply,fullApplyOpts,+ distrustWorkspace,};diff --git a/plugins/model-apps/scripts/lib/classify-changes.js b/plugins/model-apps/scripts/lib/classify-changes.jsindex 957f4427c..3045770d7 100644--- a/plugins/model-apps/scripts/lib/classify-changes.js+++ b/plugins/model-apps/scripts/lib/classify-changes.js@@ -17,7 +17,7 @@// layout:'auto' forms don't even carry placement), so form edits are conservatively// full-build + debt-candidate; the build-time verifier clears the debt iff it converged.// #3 view — pure APPEND of columns (prior columns are a prefix of current; nothing else changed).-// #4 app-shell— structural sitemap change only (app.name/description/icon unchanged).+// #4 app-shell— structural sitemap change only (the whole app object unchanged).//// PURE + I/O-free. Consumes the ANNOTATED specs (caller runs annotateContentHashes first).@@ -137,16 +137,17 @@ function classifyViews(cur, prior) {return out;}-// #4 app-shell: fast ONLY when the SITEMAP structure (appShell) changed but the app object (name /-// description / icon) is byte-identical. An app-icon/description/name change is not a sitemap-only edit.+// #4 app-shell: fast ONLY when the SITEMAP structure (appShell) changed but the app object is+// byte-identical. The object is compared WHOLE, so a change to any app field — name, description,+// routing description, icon — is not a sitemap-only edit.function classifyAppShell(cur, prior) {const out = { fast: [], full: [], debt: [] };const appSame = stableStringify(cur.app || null) === stableStringify(prior.app || null);const shellSame = stableStringify(cur.appShell || null) === stableStringify(prior.appShell || null);if (appSame && !shellSame) {- out.fast.push({ shape: 'app-shell', phase: 'app-shell', identity: 'sitemap', detail: 'sitemap structure changed (app icon/description unchanged)' });+ out.fast.push({ shape: 'app-shell', phase: 'app-shell', identity: 'sitemap', detail: 'sitemap structure changed (app object unchanged)' });} else if (!appSame) {- out.full.push('app-shell: the app object (name/description/icon) changed — not a sitemap-only edit');+ out.full.push('app-shell: the app object changed — not a sitemap-only edit');}return out;}diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex a1ed26aab..a29e07e99 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -553,6 +553,15 @@ function makeRunner({ emit, total }) {return { run, mapLimit, skip, emit, total };}+// Whether a push RESULT is a failure. The SDK reports some failures by value instead of throwing (see+// requireSuccessfulPush below for which, and why both spellings of the commit flag are read). Shared so+// every caller that reacts to a failed push decides "failed" exactly as the halt does.+function pushFailed(result) {+ if (!result) return false;+ const committed = result.saved !== undefined ? result.saved : result.success;+ return committed === false || (committed === undefined && Boolean(result.error));+}+// Route every artifact push (form/view/chart/app/command/dashboard) through this. The SDK's// pushArtifact RESOLVES (it does NOT throw) with a failed PushResult on a 412 — the artifact changed// in Maker since our last fetch — and on an ARTIFACT_ALREADY_EXISTS collision. The engine previously@@ -570,8 +579,7 @@ function makeRunner({ emit, total }) {// the check is written to fail CLOSED against both bundle generations rather than assume one.function requireSuccessfulPush(result, what, warn) {if (!result) return result;- const committed = result.saved !== undefined ? result.saved : result.success;- if (committed === false || (committed === undefined && result.error)) {+ if (pushFailed(result)) {// SEVERAL different by-value failures reach here and they need different remedies, so the// diagnosis is SELECTED from the SDK's own error code rather than assumed.//@@ -1344,4 +1352,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, requireSuccessfulPush, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };+module.exports = { makeRunner, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };diff --git a/plugins/model-apps/scripts/lib/form-container-match.js b/plugins/model-apps/scripts/lib/form-container-match.jsindex 7c11c792a..02c6afdf7 100644--- a/plugins/model-apps/scripts/lib/form-container-match.js+++ b/plugins/model-apps/scripts/lib/form-container-match.js@@ -12,14 +12,17 @@// Find the deployed container matching `want`, preferring an exact name, then a label, then the// positional slot. `claimed` (a Set of already-taken indices) keeps two authored containers from// resolving to the same deployed one; `skip` hides containers the LABEL and POSITION passes must-// not claim. Returns `{ index, item }` or null.+// not claim; `nameSkip` hides containers from the NAME pass as well — an authored section passes+// `isEngineOwnedSection` there, since it may legally share a name with the engine's own host.+// Returns `{ index, item }` or null.function matchContainer(list, want, wantIndex, opts) {const items = list || [];const claimed = (opts && opts.claimed) || null;const skip = (opts && opts.skip) || (() => false);+ const nameSkip = (opts && opts.nameSkip) || (() => false);const eq = (a, b) => a !== undefined && a !== null && String(a).toLowerCase() === String(b || '').toLowerCase();const free = (i) => !claimed || !claimed.has(i);- let idx = items.findIndex((x, i) => free(i) && want.name && eq(x.name, want.name));+ let idx = items.findIndex((x, i) => free(i) && want.name && eq(x.name, want.name) && !nameSkip(x));if (idx < 0) idx = items.findIndex((x, i) => free(i) && !skip(x) && want.label && eq(x.label, want.label));if (idx < 0 && wantIndex < items.length && free(wantIndex) && !skip(items[wantIndex])) idx = wantIndex;return idx < 0 ? null : { index: idx, item: items[idx] };@@ -44,4 +47,66 @@ function isEngineOwnedSection(s) {return cells.length > 0 && cells.every((c) => c && c.control && !c.control.fieldName);}-module.exports = { matchContainer, isEngineOwnedSection };+// A control class id as compared: the SDK projects `classid` without its braces and in its original case,+// FormXML carries it in braces, and the compiler writes the constant in upper case.+const classIdOf = (c) => String((c && c.control && c.control.classId) || '').replace(/[{}]/g, '').trim().toLowerCase();+const cellsOf = (s) => ((s && s.rows) || []).flatMap((r) => (r && r.cells) || []);++// The names the COMPILER gives the sections it adds itself — `section_notes` (notesSectionIntent) and+// `section_grid_<relationship>` (subgridSectionIntent), both in artifact-intent.js — each with the control+// that host exists to hold: the notes timeline and a sub-grid. These are the stable platform class ids+// sdk-build.js pins as NOTES_CLASS_ID and SUBGRID_CLASS_ID (the SDK's ControlClassIds).+const ENGINE_HOSTS = [+ { name: /^section_notes$/i, classId: '06375649-c143-495e-a496-c962e5b4488e' },+ { name: /^section_grid_.*$/i, classId: 'e7a81278-8635-4d9e-8d4d-59480b391c5b' },+];++// An engine HOST: a section that still carries the name the compiler gave it, and is either engine-owned+// or holds the control that name's host exists for — never a bound field: a bound control's class id comes+// from its attribute's type. This — not isEngineOwnedSection alone — is what an AUTHORED want never takes,+// by name, label or position.+//+// The structure alone is not enough, in either direction. It says a section holds only unbound controls;+// it cannot say who laid the section out. An authored section declared with no fields that a maker then+// filled with a web resource, an iframe or a sub-grid is structurally the same, and its name is the one+// positive evidence that it is the author's: skipping it created an empty duplicate beside it, and when+// the spec moved it, left the maker's control behind in the old tab. And a host a maker added a bound+// field to is no longer engine-owned, yet still the host — it holds the timeline or the sub-grid the+// engine put it there for. Taking it, an authored `section_notes` moved the timeline into the author's+// tab and poured the author's fields into it.+//+// Limit: an authored section that takes an engine name cannot be told from the host when it holds no+// bound field, or holds that host's own control, so it is treated as one. An authored section with fields+// and no such control never is.+function isEngineHostSection(s) {+ const host = ENGINE_HOSTS.find((h) => h.name.test(String((s && s.name) || '')));+ if (!host) return false;+ return isEngineOwnedSection(s) || cellsOf(s).some((c) => classIdOf(c) === host.classId);+}++// The host an ENGINE want is recognised by: a section holding, unbound, the want's OWN control — the notes+// timeline's class id. The compiler's notes want shares its name with any authored `section_notes`, and+// taking one of those for its host — any unbound control once qualified, a maker's web resource beside the+// author's field included — meant the form never got its timeline, and the want re-patched the author's+// section on every build. A timeline host a maker added a field to still holds the control, so it is still+// found. A want whose cells name no class id falls back to any unbound control.+function holdsControlOf(want) {+ const ids = new Set(cellsOf(want).map(classIdOf).filter(Boolean));+ return (s) => cellsOf(s).some((c) => c && c.control && !c.control.fieldName && (!ids.size || ids.has(classIdOf(c))));+}++// A deployed section an authored section claims BY NAME: the LABEL and POSITION passes must not hand+// it to a different want. Its own want finds it through the name pass, which `skip` does not apply to+// — and the build MOVES a named section to the tab and form-column the spec places it in — so a label+// or position claim by another want would be followed by that move and route two authored sections'+// fields into one. `authoredNames` is every authored section name on the form, lower-cased+// (validation keeps them unique). Build and verify both pass it, so they keep matching the same+// containers.+function claimedByAuthoredName(authoredNames) {+ return (s) => {+ const name = String((s && s.name) || '').toLowerCase();+ return !!name && authoredNames.has(name);+ };+}++module.exports = { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName };diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.jsindex a20746415..457a95692 100644--- a/plugins/model-apps/scripts/lib/hydrate-spec.js+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js@@ -211,6 +211,12 @@ async function hydrateSpec(read) {app: {name: app.name,description: app.description || '',+ // #583: the routing description round-trips when the app has one. The SDK sets `aiDescription` on+ // a fetched app whenever `appmodule.aiappdescription` is non-empty — including whitespace-only — so+ // a blank one is dropped here: validation refuses a blank value, and one the platform left blank+ // would otherwise fail the whole download. Absent stays absent, and the build never writes an absent+ // field, so a rebuild cannot blank one the platform wrote.+ ...(typeof app.aiDescription === 'string' && app.aiDescription.trim() ? { aiDescription: app.aiDescription } : {}),...(app.uniquename ? { uniqueName: app.uniquename } : {}),...(typeof app.newLook === 'boolean' ? { newLook: app.newLook } : {}),...(typeof app.headerNavigationRefresh === 'boolean' ? { headerNavigationRefresh: app.headerNavigationRefresh } : {}),diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 03c78ef82..5f28a39cb 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -44,6 +44,7 @@ const { topoOrderEntities, entityByLogical } = require('./_graph.js');const {makeRunner,requireSuccessfulPush,+ pushFailed,reportPartialPush,errorCodeChain,makeEntitySetResolver,@@ -76,7 +77,7 @@ const {rowsFromCells,} = require('./artifact-intent.js');const { makeGenpageCli, suppliedButBlank } = require('./genpage-cli.js');-const { matchContainer, isEngineOwnedSection } = require('./form-container-match.js');+const { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName } = require('./form-container-match.js');const { manifestResourceName, buildManifest, serializeManifest, parseManifestBase64, reconcilePageIds } = require('./page-manifest.js');// MEMBERSHIP authority (the app's live sitemap) + the cross-app shared-page scan. fetchSitemap is// fail-closed & discriminated (C4); fetchAppsForPages is the only way to prove a generative page is not@@ -89,6 +90,7 @@ const { selectSummaryTables } = require('./ai-candidates.js');const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { buildPromptSpec } = require('./ai-prompt.js');const { odataLit } = require('./odata.js');+const { isRestrictedSolution } = require('./system-solutions.js');// Re-export from entity-provision so the export surface stays unchangedconst BuildHalt = _BuildHalt;@@ -115,6 +117,59 @@ const TILE_CLASS_ID = {// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponentconst COMPONENT_TYPE = { view: 26, chart: 59, form: 60, dashboard: 60, webResource: 61, sitemap: 62, app: 80, role: 20, workflow: 29 };+// Which of `ids` (dashboard systemform ids) are components of the solution `solutionUniqueName`.+//+// A dashboard's only identity in an App Spec is its name, and Dataverse neither keeps names unique nor+// compares them exactly (it ignores case, most accents and trailing spaces), so a lookup by name can+// return other apps' dashboards too. Every dashboard the build creates is added to the app's solution+// (the dashboards phase below) — which makes membership the evidence of ownership that the name alone+// cannot give. Used by the build (which of several matches to reuse) and by teardown (which to delete).+//+// Returns a Set of bare lower-case ids, or null when there is no solution to ask: none named, a+// built-in container (it holds every unmanaged customization, so it proves nothing), or one that no+// longer exists. Throws when a read fails; each caller decides how to fail closed.+async function dashboardsInSolution(sdk, solutionUniqueName, ids) {+ if (!solutionUniqueName || isRestrictedSolution(solutionUniqueName)) return null;+ const bare = (g) => String(g == null ? '' : g).replace(/[{}]/g, '').toLowerCase();+ const sols = await sdk.queryRecords('solution', { select: ['solutionid'], filter: `uniquename eq '${odataLit(solutionUniqueName)}'`, top: 1 });+ const solId = sols && sols[0] && sols[0].solutionid;+ if (!solId) return null;+ const wanted = [...new Set((ids || []).map(bare).filter(Boolean))];+ const members = new Set();+ // In chunks, so the OR-list — and the URL — stays bounded however many name matches there are+ // (findDashboardsByName reads them all). A component appears once per solution, so a chunk of 25+ // ids answers at most 25 rows and `top: 50` never truncates.+ for (let i = 0; i < wanted.length; i += 25) {+ const chunk = wanted.slice(i, i + 25);+ const rows = await sdk.queryRecords('solutioncomponent', {+ select: ['objectid'],+ filter: `_solutionid_value eq ${bare(solId)} and componenttype eq ${COMPONENT_TYPE.dashboard} and (${chunk.map((id) => `objectid eq ${id}`).join(' or ')})`,+ top: 50,+ });+ for (const r of rows || []) {+ const id = bare(r && r.objectid);+ if (id) members.add(id);+ }+ }+ return members;+}++// Every dashboard whose name matches `name` (Dataverse's comparison: case, most accents and trailing+// spaces ignored), as `[{ id, name }]`. The vendored `resolveArtifact('dashboard', { name })` reads ONE+// page — `top: 10` with no `$orderby`, so the server picks which ten — and with more matches than that+// the app's own dashboard can sort beyond it, leaving every ownership decision (reuse, check, delete)+// made without it. So a full page is re-read in full. A reader without resolveArtifact (verify's)+// always reads in full. Shared by build, verify and teardown so all three see the same set.+const DASHBOARD_LOOKUP_PAGE = 10;+async function findDashboardsByName(sdk, name) {+ if (typeof sdk.resolveArtifact === 'function') {+ const page = (await sdk.resolveArtifact('dashboard', { name })) || [];+ if (page.length < DASHBOARD_LOOKUP_PAGE) return page;+ }+ const rows = (await sdk.queryRecords('systemform', { select: ['formid', 'name'], filter: `type eq 0 and name eq '${odataLit(name)}'`, paginate: true })) || [];+ return rows.map((r) => ({ id: String(r.formid), name: String(r.name) }));+}+// Web-resource kinds (App Spec `type`) -> SDK createWebResource `type` token. The SDK maps// the token to the Dataverse webresourcetype code (js=3, html=1, css=2, …).const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);@@ -144,6 +199,11 @@ const HEADER_NAV_SETTING = 'HeaderAndNavigationRefresh';// the underlying view (savedqueryid) — and the chart its visualization id — from what the build// already created; the target entity is derived from the referenced view. iframe/webresource tiles// carry a url / web-resource name.+//+// Views AND charts are keyed `entity|name`, and a tile resolves both on its OWN target entity. A chart+// keyed by name alone let two same-named charts on different tables collide, so a tile took whichever+// was built last — one table's view with another table's chart, which the platform accepts and+// publishes (live-measured). Validation guarantees the named chart exists on the tile's table.function dashboardTileOpts(spec, tile, result) {const viewEntity = (name) => { const v = (spec.views || []).find((x) => x.name === name); return v && v.entity.toLowerCase(); };const span = (o) => { if (tile.colspan) o.colspan = tile.colspan; if (tile.rowspan) o.rowspan = tile.rowspan; return o; };@@ -152,7 +212,7 @@ function dashboardTileOpts(spec, tile, result) {const targetEntity = tile.entity ? tile.entity.toLowerCase() : viewEntity(tile.view);if (tile.type === 'chart') {return span({ type: 'chart', name: tile.name || tile.chart, targetEntity,- viewId: tile.viewId || result.created.views[`${targetEntity}|${tile.view}`], visualizationId: tile.visualizationId || result.created.charts[tile.chart] });+ viewId: tile.viewId || result.created.views[`${targetEntity}|${tile.view}`], visualizationId: tile.visualizationId || result.created.charts[`${targetEntity}|${tile.chart}`] });}if (tile.type === 'list') {return span({ type: 'list', name: tile.name || tile.view, targetEntity, viewId: tile.viewId || result.created.views[`${targetEntity}|${tile.view}`] });@@ -921,10 +981,156 @@ function appDef(spec, result, opts = {}) {groups: (a.groups || []).map((g, gi) => ({ id: `group_${ai}_${gi}`, title: g.label,subAreas: (g.subAreas || []).map((s, si) => subAreaJson(s, `sub_${ai}_${gi}_${si}`)).filter(Boolean) })) }));return { name: spec.app.name, uniqueName, description: spec.app.description || '', siteMap: { areas },+ // #583: the routing description, only when the spec sets one (see applyAppAiDescription).+ ...(spec.app.aiDescription ? { aiDescription: spec.app.aiDescription } : {}),...(opts.iconWebResourceId ? { iconWebResourceId: opts.iconWebResourceId } : {}),components: { forms: Object.values(result.forms || {}).filter(Boolean), views: Object.values(result.views || {}).filter(Boolean), charts: Object.values(result.charts || {}).filter(Boolean) } };}+// #583: set the routing description (`app.aiDescription` → `appmodule.aiappdescription`) on the FETCHED+// artifact of an app that already exists. Returns true when the artifact changed and needs a push.+//+// * Only when the spec sets one. Absent means "leave the deployed value alone" — the platform can write+// this text itself — so an omitted field is never written, and never blanked.+// * Only when it differs from the FETCHED artifact, which is the draft layer+// (RetrieveUnpublishedMultiple) the SDK's own push compares the header against. So `true` here means+// exactly "the push will write the header", and a plain rebuild neither pushes nor publishes for+// nothing. Same rule as the chart description reconcile: read the layer the write targets.+// * A fetched app carries `aiDescription` only when the row has one, and `updateElement` refuses a+// path that is not there (PATH_NOT_FOUND). So the key is ADDED at the artifact root when absent and+// updated when present.+// LIVE-MEASURED: addElement at the root and a push write `aiappdescription` (read back before and after+// publish); a later updateElement and push change it; an unrelated edit and push leave it untouched.+async function applyAppAiDescription(provision, spec, appId) {+ const want = spec.app && spec.app.aiDescription;+ if (typeof want !== 'string' || !want.trim()) return false;+ const current = (await provision.getArtifact('app', appId)) || {};+ if (current.aiDescription === want) return false;+ if (current.aiDescription === undefined) await provision.addElement('app', appId, '', { aiDescription: want });+ else await provision.updateElement('app', appId, '/aiDescription', want);+ return true;+}++// #583: halt precisely when the push of an app whose routing description this run changed was refused+// because Dataverse will not take a header write until the app is PUBLISHED — rather than because of a+// concurrent edit. Called before requireSuccessfulPush, whose generic 412 remedy (re-download and+// rebuild) reads the same draft and fails the same way. The SDK reports that state two ways:+// * APP_DRAFT_HEADER_NOT_WRITABLE, THROWN (see pushAppHeader) for an app that was never published. The+// SDK's own message names the state, so no read is needed.+// * VERSION_CONFLICT, RESOLVED (saved:false) for a published app with an unpublished header change.+// LIVE-MEASURED: once a header change (name, description or routing description) is pushed but not+// published, the appmodule row has a second, unpublished layer with its own version number, and the+// SDK's next header PATCH fails with 412 although nothing changed since the fetch; a sitemap-only+// push over the same state still succeeds, and publishing clears it. The state arises from a header+// edit saved in Maker but not published, or from a build whose publish did not complete. A 412 is+// relabelled only when it was the APPMODULE row's and a draft read PROVES that state (componentstate+// 1 = Unpublished:+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodule#BKMK_ComponentState);+// any other outcome — a settled row, a read that fails — returns and leaves the generic halt in place.+//+// Whose 412 it was matters because the SDK writes an app in two PATCHes, the header then the sitemap,+// each conditional on its own version, and names the refused one in the error's `detail`:+// Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/appmodules(<id>)+// Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/sitemaps(<id>)+// A sitemap 412 is a concurrent sitemap edit — and by then this push's own header write has committed,+// leaving exactly the unpublished layer the draft read finds. Relabelling it reset the copy, and+// "publish, then re-run" then overwrote the other edit; the kept copy is what makes that re-run stop.+//+// Before halting it RESETS the workspace copy to the server's. The refused push left this run's edits in+// it; once the operator publishes, the server moves, and a plain fetch then refuses to discard unpushed+// edits (LOCAL_EDITS_WOULD_BE_LOST) — so "publish, then re-run" would halt again. Measured against the+// vendored bundle. The edits were projected from the spec and the re-run re-applies them, so nothing is+// lost; if the reset itself fails, the halt names the workspace to delete instead.+async function haltOnUnpublishedAppHeader(provision, appId, pushed, name) {+ // pushFailed reads `saved`, then the older SDK spelling `success`, then a bare error — the same reading+ // requireSuccessfulPush applies, so the precise halt fires for either result shape.+ const code = pushFailed(pushed) && pushed.error && pushed.error.code;+ const neverPublished = code === 'APP_DRAFT_HEADER_NOT_WRITABLE';+ if (!neverPublished) {+ if (code !== 'VERSION_CONFLICT' || !provision.dataverse || typeof provision.dataverse.get !== 'function') return;+ if (!/\/appmodules\(/i.test(`${pushed.error.detail || ''} ${pushed.error.message || ''}`)) return;+ let pending = false;+ try {+ // No `$top`: look for the unpublished layer among EVERY row the draft read returns. Measured, it+ // returns only the unpublished row while one exists, but that is not a documented guarantee, and a+ // published row read first would silently fall through to the generic halt this exists to replace.+ const res = await provision.dataverse.get(`/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=componentstate&$filter=appmoduleid eq ${appId}`);+ // `dataverse.get` RESOLVES on a non-2xx, so the status is checked explicitly.+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {+ pending = res.body.value.some((r) => r && r.componentstate === 1);+ }+ } catch {+ return;+ }+ if (!pending) return;+ }+ let reset = true;+ try {+ await provision.fetchArtifact('app', appId, { overwrite: true });+ } catch {+ reset = false;+ }+ const workspace = reset ? ''+ : ' First delete the .maker-workspace directory (or the --workspace one): it still holds this run\'s unpushed copy of the app, which a re-run would refuse to overwrite.';+ const why = neverPublished+ ? 'the app has never been published, and Dataverse refuses a write to its name, description or routing description until it is'+ : 'the app has an unpublished change to its name, description or routing description (saved in Maker, or by a build whose publish did not complete), and Dataverse refuses another write to those fields until it is published';+ const fix = neverPublished ? 'publish the app in Power Apps' : 'publish the app in Power Apps (or discard the change)';+ throw new BuildHalt(`push app ${name} failed: ${why}. Re-downloading reads the same draft and fails the same way: ${fix}, then re-run the build.${workspace}`, { phase: 'push', code: 'app-header-unpublished', recoverable: true, cause: pushed.error });+}++// #583: push an app artifact whose header this run may have changed (the routing description). A refusal+// that means "publish first" — thrown or returned — goes through haltOnUnpublishedAppHeader; everything+// else is exactly the plain push (the result is still for requireSuccessfulPush to judge) — except that a+// FAILED push first resets the workspace copy (discardUnrecordedEdits).+async function pushAppHeader(provision, appId, name, headerChanged) {+ let pushed;+ try {+ pushed = await provision.pushArtifact('app', appId);+ } catch (e) {+ if (headerChanged) await haltOnUnpublishedAppHeader(provision, appId, { saved: false, error: e }, name);+ await discardUnrecordedEdits(provision, appId, e, true);+ throw e;+ }+ if (headerChanged) await haltOnUnpublishedAppHeader(provision, appId, pushed, name);+ if (pushFailed(pushed)) await discardUnrecordedEdits(provision, appId, pushed.error, false);+ return pushed;+}++// #583: after a push of the app FAILED, reset the workspace copy to the server's. Its edits were never+// recorded, and a copy still holding them hurts the re-run: its plain fetch refuses to discard them+// (LOCAL_EDITS_WOULD_BE_LOST) once the server has moved; the next run that pushes the app refuses such a+// copy outright (refuseUnpushedAppCopy); and applyAppAiDescription would compare against it, so a pending+// routing description read as "already set". The edits are projected from the spec, so the re-run+// re-applies them and nothing is lost. (Only a push that carried a header change used to reset; a failed+// sitemap-only push left the copy holding its edits.)+//+// A concurrent edit is the one failure that KEEPS the copy: a VERSION_CONFLICT, or a returned failure+// with no code at all (the bare 412 requireSuccessfulPush reads the same way). There the remedy is a+// fresh download, and the unrecorded copy is what makes a blind re-run stop instead of overwriting the+// other edit. Best-effort: a reset that fails leaves the copy exactly as it was before this existed.+async function discardUnrecordedEdits(provision, appId, error, thrown) {+ const code = error && error.code;+ if (code === 'VERSION_CONFLICT' || (!thrown && !code)) return;+ try {+ await provision.fetchArtifact('app', appId, { overwrite: true });+ } catch { /* see above */ }+}++// #583 review: an app copy an earlier run left holding unpushed edits — a build interrupted between its edit+// and its push, say — goes out with the next push of the app, whatever that run asked for. A plain fetch+// keeps such a copy while the server has not moved, and the SDK serializes every field that differs from+// its stored server copy: a routing description the spec leaves out ("leave the deployed one alone") was+// overwritten with the earlier run's, a wanted one read as already set (so its push skipped the+// unpublished-header halt), and a stale sitemap rewrite was replayed, detaching live pages with no gate. So+// a run that will push the app refuses such a copy before it applies anything.+async function refuseUnpushedAppCopy(provision, appId, name) {+ const listed = (await provision.listArtifacts('app')).find((a) => a && a.id === appId);+ if (listed && listed.isDirty) {+ throw new BuildHalt(`app ${name}: the workspace copy holds edits an earlier run did not push (an interrupted build, say), and this run's push of the app would send them too. Delete the .maker-workspace directory (or the --workspace one) and re-run.`, { phase: 'app-shell', code: 'app-copy-unpushed-edits', recoverable: true });+ }+}+// A business-rule row filter that selects only the DEFINITION, never the platform's activated copy.//// LIVE-MEASURED. Activating a business rule makes Dataverse create a SECOND `workflows` row:@@ -1821,20 +2027,6 @@ async function runSdkBuild(spec, opts = {}) {}};- // After a whole tab or form-column is appended, record where each of its sections landed, so the- // field pass places into them through the same locator the converge path produces. A freshly- // added container's sections occupy indices 0..n-1 in declaration order.- const recordColumnSectionTargets = (out, wantColumn, tabIndex, columnIndex, liveColumns) => {- const live = ((liveColumns || [])[columnIndex] || {}).sections || [];- (wantColumn.sections || []).forEach((s, si) => {- out[s.name] = { pointer: '/tabs/' + tabIndex + '/columns/' + columnIndex + '/sections/' + si, name: (live[si] || {}).name };- });- };-- const recordSectionTargets = (out, wantTab, tabIndex, liveTab) => {- (wantTab.columns || []).forEach((c, ci) => recordColumnSectionTargets(out, c, tabIndex, ci, (liveTab || {}).columns));- };-// Identity of a deployed tab/section across rebuilds, in descending order of confidence:// 1. NAME — what the compiler emits, so a form this plugin created matches itself exactly.// 2. LABEL — what the author sees and types; survives a name this plugin did not choose@@ -1889,8 +2081,37 @@ async function runSdkBuild(spec, opts = {}) {// object a section legitimately named `__proto__` would mutate the prototype instead of becoming// an own enumerable property, so it would be invisible to `Object.values` — and the// vacated-section sweep would then treat a section the layout explicitly claimed as unclaimed.+ //+ // Only AUTHORED wants are recorded: the map routes the author's fields. The compiler's notes section+ // is also named `section_notes`, and an authored section may be too — recording the engine's want+ // after the author's replaced the author's target, and the field pass then poured the author's fields+ // into the timeline and the sweep removed the emptied authored section. An engine section routes no+ // field, and the sweep never removes a section that still holds its control.const sectionTargets = Object.create(null);const wantTabs = def.tabs || [];+ // The section names the AUTHOR declared, computed by the compiler from the spec with the same+ // function verify uses, so the label and position passes cannot hand one want's named section to+ // another (see claimedByAuthoredName) — and build and verify skip the same containers.+ const authoredSectionNames = new Set(def.__authoredSectionNames || []);+ // …and the subset the author NAMED. Only those are looked for across the form (see the form-wide+ // lookup below): a generated name encodes the section's place.+ const namedSectionNames = new Set(def.__namedSectionNames || []);+ // A section MOVE shifts its siblings: the ones after it in the source column slide up one. Every+ // recorded target pointer there is corrected, not only the name-less ones resolveSectionPointer+ // falls back to — the vacated-section sweep also treats recorded pointers as claims, and a stale+ // one would spare a section it should reclaim. Nothing recorded can sit at or after the INSERTION+ // point: the target column's own matches all precede it, and every other column's matches live in+ // that column (an authored name hit in another column is moved, never recorded in place; an engine+ // want, which is never moved, is never recorded at all).+ const shiftRecordedSectionPointers = (fromPointer) => {+ const split = (p) => { const m = /^(.*\/sections)\/(\d+)$/.exec(p || ''); return m ? { list: m[1], index: Number(m[2]) } : null; };+ const from = split(fromPointer);+ if (!from) return;+ for (const t of Object.values(sectionTargets)) {+ const at = t && split(t.pointer);+ if (at && at.list === from.list && at.index > from.index) t.pointer = at.list + '/' + (at.index - 1);+ }+ };// Indices already taken by an earlier want, so two wants can never converge on one container.const claimedTabs = new Set();const claimedSections = new Map(); // column pointer -> Set(index)@@ -1900,15 +2121,19 @@ async function runSdkBuild(spec, opts = {}) {// Re-read before every mutation: addElement appends and shifts sibling indices, so a pointer// computed against an earlier snapshot can address the wrong container.let form = await provision.getArtifact('form', formId) || {};- const tabMatch = matchContainer(form.tabs, wantTab, ti, { claimed: claimedTabs });+ let tabMatch = matchContainer(form.tabs, wantTab, ti, { claimed: claimedTabs });if (!tabMatch) {+ // A new tab is added with EMPTY form-columns, and its sections then go through the same+ // per-section pass as an existing tab's: a section the deployed form already carries elsewhere+ // is MOVED in, and only a genuinely new one is created. Adding the tab with its sections created+ // a same-named DUPLICATE of any section it relocated — the field pass then emptied the original,+ // which the vacated-section sweep spared for its claimed name.await provision.addElement('form', formId, '/tabs', Object.assign({}, wantTab, {- columns: (wantTab.columns || []).map((c) => Object.assign({}, c, { sections: (c.sections || []).map(stripRows) })),+ columns: (wantTab.columns || []).map((c) => Object.assign({}, c, { sections: [] })),}));form = await provision.getArtifact('form', formId) || {};- const added = matchContainer(form.tabs, wantTab, (form.tabs || []).length - 1, { claimed: claimedTabs });- if (added) { claimedTabs.add(added.index); recordSectionTargets(sectionTargets, wantTab, added.index, added.item); }- continue;+ tabMatch = matchContainer(form.tabs, wantTab, (form.tabs || []).length - 1, { claimed: claimedTabs });+ if (!tabMatch) continue; // defensive: the added tab could not be found again}claimedTabs.add(tabMatch.index);const tabPointer = '/tabs/' + tabMatch.index;@@ -1918,18 +2143,17 @@ async function runSdkBuild(spec, opts = {}) {const wantColumns = wantTab.columns || [];for (let ci = 0; ci < wantColumns.length; ci++) {form = await provision.getArtifact('form', formId) || {};- const liveTab = (form.tabs || [])[tabMatch.index];+ let liveTab = (form.tabs || [])[tabMatch.index];if (!liveTab) break; // defensive: the tab vanished mid-reconcile- const liveColumns = liveTab.columns || [];- if (ci >= liveColumns.length) {- // A tab that gained a form-column — e.g. a single-column form widened into two.- await provision.addElement('form', formId, tabPointer + '/columns', Object.assign({}, wantColumns[ci], {- sections: (wantColumns[ci].sections || []).map(stripRows),- }));+ if (ci >= (liveTab.columns || []).length) {+ // A tab that gained a form-column — e.g. a single-column form widened into two. Added EMPTY,+ // for the same reason as a new tab: its sections go through the per-section pass below.+ await provision.addElement('form', formId, tabPointer + '/columns', Object.assign({}, wantColumns[ci], { sections: [] }));form = await provision.getArtifact('form', formId) || {};- recordColumnSectionTargets(sectionTargets, wantColumns[ci], tabMatch.index, ci, ((form.tabs || [])[tabMatch.index] || {}).columns);- continue;+ liveTab = (form.tabs || [])[tabMatch.index];+ if (!liveTab || ci >= (liveTab.columns || []).length) break; // defensive: the add did not land}+ const liveColumns = liveTab.columns || [];if (wantColumns[ci].width && liveColumns[ci].width !== wantColumns[ci].width) {await provision.updateElement('form', formId, tabPointer + '/columns/' + ci, { width: wantColumns[ci].width });}@@ -1939,18 +2163,89 @@ async function runSdkBuild(spec, opts = {}) {form = await provision.getArtifact('form', formId) || {};const columnPointer = tabPointer + '/columns/' + ci;const liveSections = (((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci];- // A section may have been dragged to a different tab in Maker; it is still THAT section,- // so a form-wide name hit outranks a positional one inside this column.- const global = wantSection.name ? findSectionLocation(form, wantSection.name) : null;const claimedHere = claimedIn(columnPointer);- const local = global ? null : matchContainer((liveSections || {}).sections, wantSection, si, { claimed: claimedHere, skip: isEngineOwnedSection });+ // A section may have been dragged to a different tab in Maker, or the spec may now place it+ // somewhere else; either way it is still THAT section, so a form-wide name hit outranks a+ // positional one inside this column. A name hit INSIDE this column is preferred, so a pair of+ // same-named sections left by an older build resolves to the one already in place.+ const liveList = ((liveSections || {}).sections) || [];+ // An AUTHORED want never takes an engine HOST (the notes timeline, a sub-grid host, still under+ // the name the compiler gave it) by name, here or anywhere below. An authored section may legally+ // carry the name the engine gives its host — `section_notes` is a natural name for a section+ // holding a notes field — and taking the host MOVED it into the author's column and poured+ // authored fields into it. Such a host is simply not a candidate: the want is matched or created+ // like any other authored section — and a host a maker added a field to is still one, since it+ // still holds its control. A section a maker filled with a control but that carries an AUTHORED+ // name stays a candidate: the name is the evidence it is the author's (see isEngineHostSection). An ENGINE want, in turn, takes only a section holding its own control+ // (the notes timeline's class id): its name is shared with any authored `section_notes`, and taking+ // the author's section for its host meant an existing form never got its timeline (see+ // holdsControlOf).+ const authoredWant = !isEngineOwnedSection(wantSection);+ const engineHost = authoredWant ? null : holdsControlOf(wantSection);+ const candidate = (s) => (authoredWant ? !isEngineHostSection(s) : engineHost(s));+ const sameName = (s) => !!(s && s.name) && String(s.name).toLowerCase() === String(wantSection.name).toLowerCase() && candidate(s);+ const inColumn = wantSection.name ? liveList.findIndex((s, i) => !claimedHere.has(i) && sameName(s)) : -1;+ // The form-wide lookup is for a section the author NAMED — and for an engine want, whose host a+ // maker may have moved. A GENERATED name (`section_<tab>[_<column>]_<index>`) encodes the+ // section's place, so a section of that name elsewhere — dragged there in Maker, or another one+ // that carries it after a reorder — is not taken from there: as documented for a generated+ // section (app-spec-schema.md, "Moving a section"), it is created where the layout places it,+ // its fields follow, and the emptied original is removed. The in-column hit above still finds it+ // where it belongs, so an unchanged layout converges.+ const lookFormWide = !!wantSection.name && (!authoredWant || namedSectionNames.has(String(wantSection.name).toLowerCase()));+ let global = inColumn >= 0 ? { pointer: columnPointer + '/sections/' + inColumn, section: liveList[inColumn] }+ : (lookFormWide ? findSectionLocation(form, wantSection.name, candidate) : null);+ // A named section the spec places in THIS column but that lives elsewhere is MOVED here: the+ // same node, so its id, name, rows and any maker-set properties travel with it. It used to be+ // reused in place — its attributes patched, its location left alone — so the build reported+ // success, the section stayed in the wrong tab, and verify, which checks placement, failed.+ // It lands right after the furthest section this column has already matched — exactly the+ // sections the layout places before it here — so it follows all of them (or goes first when+ // there are none) and stays ahead of any sub-grid host appended after them.+ //+ // An ENGINE-owned want (the notes section, a sub-grid host) is never moved: the author did+ // not place it — the compiler appends it to the first tab — so a maker who moved the+ // timeline elsewhere keeps it there, and nothing verifies its placement either.+ if (global && !isEngineOwnedSection(wantSection) && !global.pointer.startsWith(columnPointer + '/sections/')) {+ const liveCount = liveList.length;+ const index = Math.min(liveCount, claimedHere.size ? Math.max(...claimedHere) + 1 : 0);+ // Named for the report before the move: after it, `global` addresses the new place.+ const fromTab = ((form.tabs || [])[global.tabIndex] || {}).name || `#${global.tabIndex + 1}`;+ const fromColumn = global.columnIndex + 1;+ // Source and target are different arrays here, so moveElement's remove-then-splice needs no+ // index compensation (it is only off by one within a single array).+ await provision.moveElement('form', formId, global.pointer, columnPointer + '/sections', { index });+ shiftRecordedSectionPointers(global.pointer);+ // Moving a section a maker may have dragged there on purpose is the spec winning, as it does+ // for a section's columns and label — so it is reported, never silent.+ if (typeof opts.warn === 'function') {+ opts.warn(`form ${def.name}: moved section '${wantSection.name}' from tab '${fromTab}' (form-column ${fromColumn}) `+ + `to tab '${liveTab.name || `#${tabMatch.index + 1}`}' (form-column ${ci + 1}), where the layout places it.`);+ }+ form = await provision.getArtifact('form', formId) || {};+ const moved = ((((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci] || {}).sections || [];+ global = { pointer: columnPointer + '/sections/' + index, section: moved[index] || global.section };+ }+ // An ENGINE want has no label or position to go on: its evidence is its name and its own control,+ // both weighed above. Running it through the label and position passes let the notes section, when+ // no host qualified, take whatever maker section sat at its index — relabelled "Notes", re-flowed+ // to one column, and still no timeline.+ const local = (global || !authoredWant) ? null : matchContainer((liveSections || {}).sections, wantSection, si,+ { claimed: claimedHere, skip: (s) => isEngineOwnedSection(s) || isEngineHostSection(s) || claimedByAuthoredName(authoredSectionNames)(s), nameSkip: (s) => !candidate(s) });if (!global && !local) {- await provision.addElement('form', formId, columnPointer + '/sections', stripRows(wantSection));+ // An authored section is created where the layout places it: right after the furthest section this+ // column has already matched, the index the move above uses. Appended, it landed after every+ // section still to come — a new one declared mid-column, or a generated one recreated after a+ // drag in Maker — and the build never reorders what exists, so the wrong order was permanent (and+ // verify does not check order). Nothing recorded sits at or after that index, so no recorded+ // pointer shifts. An ENGINE want is still appended: the compiler puts the notes section last.+ const at = authoredWant ? Math.min(liveList.length, claimedHere.size ? Math.max(...claimedHere) + 1 : 0) : null;+ await provision.addElement('form', formId, columnPointer + '/sections', stripRows(wantSection), ...(at === null ? [] : [{ position: { index: at } }]));form = await provision.getArtifact('form', formId) || {};const addedList = ((((form.tabs || [])[tabMatch.index] || {}).columns || [])[ci] || {}).sections || [];- const addedIdx = addedList.length - 1;+ const addedIdx = at === null ? addedList.length - 1 : at;claimedHere.add(addedIdx);- sectionTargets[wantSection.name] = { pointer: columnPointer + '/sections/' + addedIdx, name: (addedList[addedIdx] || {}).name };+ if (authoredWant) sectionTargets[wantSection.name] = { pointer: columnPointer + '/sections/' + addedIdx, name: (addedList[addedIdx] || {}).name };continue;}if (local) claimedHere.add(local.index);@@ -1963,7 +2258,7 @@ async function runSdkBuild(spec, opts = {}) {}const pointer = global ? global.pointer : columnPointer + '/sections/' + local.index;const live = global ? global.section : local.item;- sectionTargets[wantSection.name] = { pointer, name: live.name };+ if (authoredWant) sectionTargets[wantSection.name] = { pointer, name: live.name };// `columns` is the key that matters most: it is what makes a section render as two// columns rather than one, and it was previously unreachable on an existing form.const patch = diffPatch(live, wantSection, ['columns', 'label', 'showLabel', 'visible']);@@ -2005,6 +2300,15 @@ async function runSdkBuild(spec, opts = {}) {// back to the recorded pointer for a section that carries no name at all.const resolveSectionPointer = (form, target) => {if (!target) return null;+ // The recorded pointer, when the section there still carries the recorded name, is EXACT — and+ // only it can tell two same-named sections apart (a real one and an empty twin an older build left+ // in another tab), where a name search always returns the first in document order. Section indices+ // do not move under the field pass (it mutates rows and cells; the topology pass corrects them+ // across its own section moves), so a mismatch means the pointer went stale, and the name decides.+ if (target.name && target.pointer) {+ const at = sectionAt(form, target.pointer);+ if (at && String(at.name || '').toLowerCase() === String(target.name).toLowerCase()) return target.pointer;+ }if (target.name) {const loc = findSectionLocation(form, target.name);if (loc) return loc.pointer;@@ -2449,7 +2753,10 @@ async function runSdkBuild(spec, opts = {}) {// out of. Without this the sweep deleted a section a maker had created empty and may// show/hide from a form script — an unchanged layout would silently destroy it, and the// destructive preflight cannot see it because that compares fields, not containers.- // · the section is NOT one the authored layout claimed (by pointer or by deployed name).+ // · the section is NOT one the authored layout claimed — judged by the section each target+ // RESOLVES to on the live form, not by name: two same-named sections (a real one and a copy an+ // older build left in another tab) share a name, and a name test spared the emptied copy+ // forever while the field pass had moved everything into the real one.// · it holds NO cells at all — not merely no bound fields. A section can carry a spacer or a// control this reader does not model, and an empty-LOOKING section is not an empty one.//@@ -2459,24 +2766,21 @@ async function runSdkBuild(spec, opts = {}) {// and is spared above. Mutation testing proved it unkillable, and a guard that cannot fail// implies coverage that does not exist.if (def.__explicitLayout && def.__prune !== false) {- const claimedPointers = new Set();- const claimedNames = new Set();- for (const t of Object.values(sectionTargets || {})) {- if (!t) continue;- if (t.pointer) claimedPointers.add(t.pointer);- if (t.name) claimedNames.add(String(t.name).toLowerCase());- }// Collected from a single read and removed from the BACK, because removeElement shifts the// indices of later siblings — deleting front-first would silently target the wrong section.const orphans = [];const live = await provision.getArtifact('form', formId) || {};+ const claimedPointers = new Set();+ for (const t of Object.values(sectionTargets || {})) {+ const p = t && resolveSectionPointer(live, t);+ if (p) claimedPointers.add(p);+ }(live.tabs || []).forEach((tab, ti) => {(tab.columns || []).forEach((col, ci) => {(col.sections || []).forEach((sec, si) => {const pointer = `/tabs/${ti}/columns/${ci}/sections/${si}`;if (claimedPointers.has(pointer)) return;const secName = sec && sec.name ? String(sec.name).toLowerCase() : null;- if (secName && claimedNames.has(secName)) return;if (!secName || !vacatedSections.has(secName)) return;const cells = ((sec && sec.rows) || []).flatMap((r) => (r && r.cells) || []);if (cells.length) return;@@ -2487,7 +2791,12 @@ async function runSdkBuild(spec, opts = {}) {for (const o of orphans.slice().reverse()) {await provision.removeElement('form', formId, o.pointer);if (typeof opts.warn === 'function') {- opts.warn(`form ${def.name}: removed the now-empty section '${o.name}'${o.label ? ` ("${o.label}")` : ''} — the layout no longer places anything in it. Give a section an explicit \`name\` if you intend to move it between tabs or form-columns.`);+ // The naming hint helps only a GENERATED name (`section_<tab>[_<column>]_<index>`), which is+ // the one that loses its identity on a move; a named copy or a dropped section needs none. The+ // shape alone is not proof: an author may NAME a section `section_0_0`, and a copy of that+ // needs no advice to give it a name.+ const generated = /^section_\d+(?:_\d+)?_\d+$/.test(String(o.name)) && !(def.__namedSectionNames || []).includes(String(o.name).toLowerCase());+ opts.warn(`form ${def.name}: removed the now-empty section '${o.name}'${o.label ? ` ("${o.label}")` : ''} — the layout no longer places anything in it.${generated ? ' Give a section an explicit `name` if you intend to move it between tabs or form-columns.' : ''}`);}}}@@ -2758,7 +3067,7 @@ async function runSdkBuild(spec, opts = {}) {return pushed.id;});});- charts.forEach((c, i) => { result.created.charts[c.name] = ids[i]; });+ charts.forEach((c, i) => { result.created.charts[`${String(c.entity).toLowerCase()}|${c.name}`] = ids[i]; });}// 6. Forms (independent -> parallel; sub-grids reference the child view ids built above).@@ -3351,8 +3660,49 @@ async function runSdkBuild(spec, opts = {}) {// the dashboard kind (only view/chart/form/app), but the vendored bundle's resolveArtifact does (it// is what the teardown engine uses to find dashboards, sdk-teardown.js). Like charts, dashboard TILE// EDITS are not reapplied on a rebuild — recreate the dashboard to change it. Never removes tiles.- const existing = await provision.resolveArtifact('dashboard', { name: dash.name });- const existingId = existing && existing[0] && existing[0].id;+ const existing = await findDashboardsByName(provision, dash.name);+ let existingId = existing[0] && existing[0].id;+ // A name lookup can return several dashboards — names are not unique, and the lookup ignores+ // case, most accents and trailing spaces — and reusing the first one returned bound this app to+ // an arbitrary one, possibly another app's. The app's own is the one its solution holds; when+ // that does not single one out, halt with the names to fix rather than guess.+ if (existing.length > 1) {+ let ours = null;+ let unreadable = '';+ try {+ const members = await dashboardsInSolution(provision, sol.uniqueName, existing.map((e) => e.id));+ ours = members ? existing.filter((e) => members.has(String(e.id).replace(/[{}]/g, '').toLowerCase())) : null;+ } catch (err) {+ unreadable = ` (${(err && err.message) || err})`;+ }+ if (ours && ours.length === 1) {+ existingId = ours[0].id;+ } else {+ const reason = ours === null+ ? `and this app's solution cannot say which is its own${unreadable}`+ : `and ${ours.length ? `${ours.length} of them are` : 'none of them is'} in this app's solution '${sol.uniqueName}'`;+ await runner.run('dashboards', `dashboard "${dash.name}"`, async () => {+ throw new Error(`${existing.length} dashboards in this environment match the name '${dash.name}' (Dataverse compares names ignoring case, most accents and trailing spaces) ${reason}, so the build cannot tell which one to reuse. Rename or delete the extra ones in Maker, or give this dashboard a different name.`);+ });+ }+ } else if (existing.length === 1 && typeof opts.warn === 'function') {+ // A LONE match is reused without that proof. A downloaded app's dashboard may never have joined+ // the solution the download recovered — the one holding the APP; a dashboard made in Maker outside+ // it stays in Default — and refusing or duplicating it would break that rebuild. It is not ADDED to+ // the solution either (only a dashboard the build creates is), so teardown, which deletes solution+ // members only, keeps it. But a lone match outside the solution may be another app's namesake, and+ // this app is then bound to it with nothing to tell — so the build says so. A read that fails+ // proves nothing either way and is no reason to fail the step: the reuse is today's behaviour.+ let members = null;+ try {+ members = await dashboardsInSolution(provision, sol.uniqueName, [existing[0].id]);+ } catch {+ members = null;+ }+ if (members && !members.has(String(existing[0].id).replace(/[{}]/g, '').toLowerCase())) {+ opts.warn(`dashboard "${dash.name}": the one dashboard with this name is not in this app's solution '${sol.uniqueName}', so nothing proves it is this app's. It is reused; teardown will keep it, and a solution export will leave it out. If it is this app's, add it to the solution in Maker; if it is another app's, give this dashboard a different name.`);+ }+ }if (existingId) {runner.skip('dashboards', `dashboard "${dash.name}" (exists — reuse; tile edits aren't applied on rebuild, recreate to change)`);result.created.dashboards[dash.name] = existingId;@@ -3367,7 +3717,48 @@ async function runSdkBuild(spec, opts = {}) {await provision.addElement('dashboard', art.id, '/components', dashboardComponent(dashboardTileOpts(spec, tiles[ti], result), ti));}const pushed = requireSuccessfulPush(await provision.pushArtifact('dashboard', art.id), `dashboard ${dash.name}`, opts.warn);- await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.dashboard, solutionUniqueName: sol.uniqueName });+ try {+ await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.dashboard, solutionUniqueName: sol.uniqueName });+ } catch (err) {+ // The app's solution is the only proof, to a later rebuild or teardown, that this dashboard is+ // the app's (names are not unique — see dashboardsInSolution). Left outside it, a rebuild would+ // reuse it as a lone name match without ever adding it, and teardown would keep it as "not+ // created by this build" while its tiles blocked the chart and view deletes. So undo the push+ // — a re-run then simply creates it again — and when that fails too, say what is left behind.+ const why = (err && err.message) || String(err);+ let undoErr = null;+ try {+ await provision.deleteRemoteArtifact('dashboard', pushed.id);+ } catch (e) {+ undoErr = e;+ }+ // deleteRemoteArtifact removes the row and THEN the local workspace copy, so a failure can come+ // from either half. Only a row that is still there is left outside the solution; when that+ // cannot be read either, assume it is.+ let stranded = false;+ if (undoErr) {+ stranded = true;+ try {+ const still = await provision.queryRecords('systemform', { select: ['formid'], filter: `formid eq ${String(pushed.id).replace(/[{}]/g, '')}`, top: 1 });+ stranded = !!(still && still.length);+ } catch { /* cannot tell — keep assuming it is still there */ }+ }+ if (stranded) {+ const left = new Error(`dashboard "${dash.name}" was created (${pushed.id}) but could not be added to solution '${sol.uniqueName}' (${why}), and removing it again failed (${(undoErr && undoErr.message) || undoErr}) — add it to the solution or delete it in Maker before re-running, or teardown will not recognise it as this app's`);+ // Never auto-retried (isTransientHalt, build-model-app.js): a retry would reuse it as a lone+ // name match without adding it, whatever transient text the causes quoted above carry.+ left.transient = false;+ left.cause = err;+ throw left;+ }+ const removed = new Error(`dashboard "${dash.name}" could not be added to solution '${sol.uniqueName}' (${why}), so it was removed again — re-run to create it afresh`);+ // Nothing is left behind, so a retry is safe: keep the cause's HTTP status, so a 429/503 is+ // still auto-retried as it was before the undo existed.+ const status = err && (err.statusCode || err.status);+ if (status) removed.statusCode = status;+ removed.cause = err;+ throw removed;+ }result.created.dashboards[dash.name] = pushed.id;});}@@ -3398,6 +3789,22 @@ async function runSdkBuild(spec, opts = {}) {if (existingId) {appWasExisting = true;await provision.fetchArtifact('app', existingId);+ // Refused here, before anything is applied, whenever this run pushes the app: the finalizer (every+ // pages-phase run that rewrites the sitemap), or the app-shell pushes below (refuseUnpushedAppCopy).+ const routingSet = typeof (spec.app && spec.app.aiDescription) === 'string' && !!spec.app.aiDescription.trim();+ const pushesApp = has('pages')+ ? !(opts.changedOnly && opts.changedOnly.skipSitemapFinalize)+ : (!appHasPageSubareas(spec) || routingSet);+ if (pushesApp) await refuseUnpushedAppCopy(provision, existingId, def.name);+ // #583: the routing description rides an app push this run ALREADY makes — never a second push from+ // the same fetch (the push is If-Match). With the pages phase in the run — every CLI apply, since+ // --apply refuses a partial range that includes app-shell — the finalizer is the sole existing-app+ // sitemap writer, and applies it there, after its own re-fetch and after the removal gate. Pushing+ // the fetched app HERE would re-send the LIVE sitemap, which the SDK validates reference by+ // reference, so a subarea whose page or table was deleted in Maker would halt the run before the+ // pages phase could drop it. Without the pages phase it is applied below, right before the push+ // that carries it — after the live-page gate, so a gate that halts leaves no unrecorded edit in+ // the workspace copy for the re-run's plain fetch to refuse.// Update the nav tree via the generic surface. On push the adapter re-derives the app's// ENTITY + DashBoard components from the sitemap, so a sitemap edit's tables and dashboards// stay pinned. Explicit forms/views/charts component pins are applied at CREATE only (below):@@ -3429,8 +3836,21 @@ async function runSdkBuild(spec, opts = {}) {if (!liveSm.ok) throw new BuildHalt(`cannot verify the existing app's live generative pages before rewriting its sitemap (${liveSm.reason}) — refusing to proceed (would risk orphaning pages)`, { phase: 'app-shell', code: 'pages-sitemap-read-failed', recoverable: true });if (liveSm.ids.length && opts.allowDestructive !== true) throw new BuildHalt(`refusing to rewrite a page-less sitemap over an existing app that still has ${liveSm.ids.length} live generative page(s) (would orphan them: ${liveSm.ids.join(', ')}). Include the pages phase to reconcile them, or re-run with --allow-destructive to detach.`, { phase: 'app-shell', code: 'pages-removed', recoverable: false });await provision.updateElement('app', existingId, '/siteMap', def.siteMap);- requireSuccessfulPush(await provision.pushArtifact('app', existingId), `app ${def.name}`, opts.warn);+ const aiDescriptionChanged = await applyAppAiDescription(provision, spec, existingId);+ requireSuccessfulPush(await pushAppHeader(provision, existingId, def.name, aiDescriptionChanged), `app ${def.name}`, opts.warn);reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);+ } else if (!has('pages') && typeof (spec.app && spec.app.aiDescription) === 'string' && spec.app.aiDescription.trim()) {+ // Reached only WITHOUT the pages phase (a programmatic partial run — the CLI refuses one on+ // --apply): a page-backed app's sitemap is not written on this run, so the routing description+ // needs its own push. That push re-sends the workspace copy's sitemap, which the SDK validates —+ // and which is the live one only because a copy holding an earlier run's unpushed edits was+ // refused above (refuseUnpushedAppCopy): replaying a stale sitemap rewrite detached live pages+ // with no gate and no --allow-destructive, and the copy's routing description may be this very+ // edit, left unpushed, so "unchanged" against it would skip the push the server still needs.+ if (await applyAppAiDescription(provision, spec, existingId)) {+ requireSuccessfulPush(await pushAppHeader(provision, existingId, def.name, true), `app ${def.name} routing description`, opts.warn);+ reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);+ }}await ensureSitemapInSolution(provision, sol, def.uniqueName);return existingId;@@ -3698,8 +4118,12 @@ async function runSdkBuild(spec, opts = {}) {await provision.fetchArtifact('app', result.created.app);const full = appDef(spec, result.created);await provision.updateElement('app', result.created.app, '/siteMap', full.siteMap);- requireSuccessfulPush(await provision.pushArtifact('app', result.created.app), 'app sitemap finalize', opts.warn);- reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);+ // #583: the routing description rides THIS push whenever the pages phase runs (the app-shell+ // branch defers it here). A fresh app already carries it from its create, so this is a no-op there.+ const headerChanged = await applyAppAiDescription(provision, spec, result.created.app);+ const appName = (spec.app && spec.app.name) || result.created.app;+ requireSuccessfulPush(await pushAppHeader(provision, result.created.app, appName, headerChanged), 'app sitemap finalize', opts.warn);+ reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${appName}`, opts.warn);return result.created.app;});} else {@@ -4312,9 +4736,7 @@ async function runSdkBuild(spec, opts = {}) {// from `result.created.charts` would therefore hand publish an id it cannot resolve for an// existing chart with no description to reconcile, and the throw escapes publishArtifact and// halts the phase. `chartsToPublish` is populated at exactly the two points that put a chart in- // the workspace. It is also keyed by entity rather than by chart NAME, which sidesteps the- // `result.created.charts` name-only keying (two same-named charts on different entities- // collide there).+ // the workspace, and keyed by entity because publishing is per-entity.for (const [k, cid] of chartsToPublish) { if (cid && !seen.has(k)) { seen.add(k); perEntity.push(['chart', cid]); } }await runner.mapLimit(perEntity, concurrency, (async ([type, id]) => reportPartialPush(await provision.publishArtifact(type, id), `${type} ${id}`, opts.warn)));if (result.created.app) reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);@@ -4414,4 +4836,4 @@ async function runSdkBuild(spec, opts = {}) {return result;}-module.exports = { runSdkBuild, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };+module.exports = { runSdkBuild, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex e0ee76ecc..3b01b5039 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -53,7 +53,7 @@// the identical phase-grouped, status-marked log.const { topoOrderEntities } = require('./_graph.js');-const { appUniqueName, commandsByEntity, defaultViewColumns, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter } = require('./sdk-build.js');+const { appUniqueName, commandsByEntity, defaultViewColumns, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter } = require('./sdk-build.js');const { manifestResourceName, parseManifestBase64 } = require('./page-manifest.js');const { relationshipSchemaName, manyToManySchemaName, lookupColumnsFor, SDK_ROLE_MARKER, canonicalPersonaName, FORM_GUID_RE } = require('./app-spec.js');const { selectSummaryTables } = require('./ai-candidates.js');@@ -226,7 +226,24 @@ const KIND_HANDLERS = {// not-found failure means the row already cascaded away (not a leftover), so it is tolerated —// the same best-effort spirit as the step-level isNotFound handling in deleteStep.async del(sdk, item) {- const result = await sdk.deleteAppCascade(item.id, item.appModuleIdUnique);+ let result;+ try {+ result = await sdk.deleteAppCascade(item.id, item.appModuleIdUnique);+ } catch (err) {+ // A rejection does not mean the app survived. The SDK's deleteAppCascade runs the remote+ // cascade and THEN tidies its local workspace copy (`workspace.readArtifact`/`deleteArtifact`),+ // so a failure in that local step arrives after the app is already gone — and reading it as+ // "not deleted" abandoned every dependent step while reporting a deleted app as still there.+ // The PLATFORM decides, not the exception: if the app row is gone the delete happened, so the+ // dependents must go too (`appDeleted`, as for a cascade-cleanup failure below). It stays an+ // error, because what failed after the delete cannot be known from here. A 404 is left to+ // deleteStep, which asks the same question and treats a confirmed absence as a clean delete.+ if (isNotFound(err) || !(await KIND_HANDLERS.app.confirmAbsent(sdk, item))) throw err;+ const e = new Error(`app "${item.name}" was deleted, but the delete call then failed: ${errMsg(err)} — its dependents are torn down anyway`);+ e.cause = err;+ e.appDeleted = true;+ throw e;+ }const failures = (result && Array.isArray(result.failures) ? result.failures : []).filter((f) => !isNotFound(f && f.error));@@ -327,8 +344,60 @@ const KIND_HANDLERS = {},dashboard: {async resolve(sdk, target) {- const items = await sdk.resolveArtifact('dashboard', { name: target.name });- return (items || []).map((x) => ({ id: x.id, name: x.name }));+ // The name lookup fails closed like the membership read below. runTeardown reads an error that says+ // "not found" — a failed paginated read, a proxy's 404 — as an empty resolution, so the dashboard was+ // reported absent and the solution, the only thing a re-run can ask about ownership, then deleted.+ let items;+ try {+ items = await findDashboardsByName(sdk, target.name);+ } catch (err) {+ const e = new Error(`could not look up dashboards named '${target.name}' (${errMsg(err)}) — none is deleted; re-run the teardown`);+ e.failClosed = true;+ throw e;+ }+ if (!items.length) return [];+ // Found by NAME, and Dataverse neither keeps names unique nor compares them exactly (it ignores+ // case, most accents and trailing spaces), so a match may be another app's dashboard — deleting+ // every match took those with it. The app's own are the ones its solution holds (every dashboard+ // the build creates is added to it), so only those are deleted. With no real solution to ask —+ // the built-in container a download may leave, or a named solution already gone — nothing proves+ // a match is this app's, and none is deleted: an orphaned dashboard is recoverable; another app's+ // deleted one is not. (runTeardown keeps the solution while an earlier step failed, so a re-run+ // still has it to ask.)+ let members;+ try {+ members = await dashboardsInSolution(sdk, target.solutionUniqueName, items.map((x) => x.id));+ } catch (err) {+ // A FAILED step, not a skip. A skip leaves `result.errors` empty, so runTeardown went on to delete+ // the solution — the only thing a re-run can ask to tell this app's dashboards from same-named+ // ones — and every later run then kept them for good. As a failure, the solution is kept and a+ // re-run asks again. `failClosed` stops runTeardown's not-found shortcut from turning this back+ // into an empty resolution when the read error happens to say "not found" (a proxy's 404).+ const e = new Error(`could not read solution '${target.solutionUniqueName}' to tell whether a dashboard named '${target.name}' is this app's (${errMsg(err)}) — none is deleted; re-run the teardown`);+ e.failClosed = true;+ throw e;+ }+ const bare = (g) => String(g == null ? '' : g).replace(/[{}]/g, '').toLowerCase();+ if (members) {+ const ours = items.filter((x) => members.has(bare(x.id)));+ if (!ours.length) {+ return { items: [], skipReason: `${items.length} dashboard(s) match the name '${target.name}', but none is in this app's solution '${target.solutionUniqueName}' — not created by this build, so none is deleted` };+ }+ return ours.map((x) => ({ id: x.id, name: x.name }));+ }+ // The spec names a real solution that no longer exists — a re-run after a completed teardown, or+ // a build that never got that far. Every dashboard this build created was in it, so a name match+ // now can only be proven to be somebody else's, not this app's.+ if (target.solutionUniqueName && !isRestrictedSolution(target.solutionUniqueName)) {+ return { items: [], skipReason: `solution '${target.solutionUniqueName}' no longer exists, so nothing proves a dashboard named '${target.name}' is this app's — none is deleted` };+ }+ // No real solution at all: a built-in container (Default — what a download leaves when it cannot+ // tell which solution owns the app — Active or Basic) holds every unmanaged dashboard, so it+ // proves nothing. A lone match used to be deleted here, and a re-run after this app's own was+ // gone then deleted another app's namesake. Kept instead, as a download keeps a table whose+ // ownership it cannot prove (`existing: true`).+ const container = target.solutionUniqueName ? `this spec's solution '${target.solutionUniqueName}' is a built-in container that holds every dashboard` : 'this spec names no solution';+ return { items: [], skipReason: `${container}, so nothing proves a dashboard named '${target.name}' is this app's — none is deleted; remove it in Maker if it is` };},del: (sdk, item) => sdk.deleteRemoteArtifact('dashboard', item.id),},@@ -671,7 +740,12 @@ const KIND_HANDLERS = {},relationship: {// No pre-resolve: delete by schema name directly (like the table handler's synthetic item).+ // A relationship flagged `existing: true` is RETAINED, on the same terms as a table (#587 item 6):+ // this build cannot prove it created it — a download flags every relationship it recovers that way+ // — and deleting one removes its lookup column, with that column's data, from a table that may+ // itself be retained.async resolve(sdk, target) {+ if (target.existing) return { items: [], skipReason: 'reused relationship (existing: true) — not created by this build' };return [{ id: target.schemaName, schemaName: target.schemaName }];},async del(sdk, item) {@@ -775,7 +849,10 @@ const KIND_HANDLERS = {globalChoice: {// Deleted by name (the SDK has no id lister); a synthetic item drives deleteStep, mirroring// the table/relationship handlers. Runs AFTER tables so no column still binds the option set.+ // Retained when flagged `existing: true` (#587 item 6): a global option set is org-wide and may be+ // shared with other apps, and a download cannot prove this build created the ones it declares.async resolve(sdk, target) {+ if (target.existing) return { items: [], skipReason: 'reused global choice (existing: true) — not created by this build' };return [{ id: target.name, name: target.name }];},del: (sdk, item) => sdk.deleteGlobalOptionSet(item.name),@@ -841,7 +918,9 @@ function planTeardown(spec) {// original constraint that put roles early — a role holding a table's privileges can block that// table's delete — is still satisfied, because forms are themselves deleted well before tables.for (const d of spec.dashboards || []) {- steps.push({ kind: 'dashboard', phase: 'dashboards', label: `dashboard "${d.name}"`, target: { name: d.name } });+ // The solution travels with the step so the resolver can tell this app's dashboards from other+ // apps' that share the name (see KIND_HANDLERS.dashboard).+ steps.push({ kind: 'dashboard', phase: 'dashboards', label: `dashboard "${d.name}"`, target: { name: d.name, solutionUniqueName: spec.solution && spec.solution.uniqueName } });}// Command bars: FAIL-CLOSED (data-loss guard, PR #229 review). Only tear down the bar for a table// THIS spec CREATES (existing !== true) — a brand-new table has no pre-existing foreign buttons, and@@ -920,17 +999,27 @@ function planTeardown(spec) {}// Gap 6: before deleting relationships, reset each child entity's built-in default views to a// lookup-free column set — the build surfaces parent lookups there, and a lookup column on an- // un-deletable default view blocks the relationship's delete. Only entities that actually have a- // 1:N lookup need it. Pure: defaultViewColumns(...,{includeLookups:false}) computes the reset set.+ // un-deletable default view blocks the relationship's delete. Pure: defaultViewColumns(...,+ // {includeLookups:false}) computes the reset set.+ //+ // Only where there is something of THIS build's to undo (#587 item 6): the build enriched the+ // table's default views (`enrichesDefaultViews` — the build's own predicate, so the two cannot+ // disagree), AND a relationship teardown will actually delete puts its lookup on the table. The+ // reset REPLACES a view's column set, so running it anywhere else rewrites views nobody asked it+ // to touch — every retained table of a downloaded spec, whose relationships are retained too.for (const e of spec.entities || []) {const logical = e.schemaName.toLowerCase();if (!lookupColumnsFor(spec, logical).length) continue;+ if (!enrichesDefaultViews(spec, e)) continue;+ const deletesALookupHere = (spec.relationships || []).some((r) => r && r.type === 'OneToMany' && r.existing !== true+ && String(r.referencing || '').toLowerCase() === logical);+ if (!deletesALookupHere) continue;steps.push({ kind: 'resetDefaultViews', phase: 'views', label: `reset default views for ${logical} (drop parent lookups)`, target: { entityLogical: logical, cols: defaultViewColumns(spec, e, { includeLookups: false }) } });}const selfRefRelSteps = [];for (const r of spec.relationships || []) {const schema = r.type === 'ManyToMany' ? manyToManySchemaName(r, spec.solution && spec.solution.publisherPrefix) : relationshipSchemaName(r, spec.solution && spec.solution.publisherPrefix);- const step = { kind: 'relationship', phase: 'relationships', label: `relationship ${schema}`, target: { schemaName: schema } };+ const step = { kind: 'relationship', phase: 'relationships', label: `relationship ${schema}`, target: { schemaName: schema, existing: r.existing === true } };// A SELF-referencing 1:N (a hierarchy — `referenced === referencing`) is deleted AFTER its table// rather than before. Deleting it first fails:// ✗ relationship lph_org_lph_org — HTTP 400 … cannot be deleted because it is referenced by@@ -1063,7 +1152,7 @@ function planTeardown(spec) {// Global option sets last (before the solution container): every column that bound one lives// on a table deleted above, so the shared choice now has no dependents blocking its delete.for (const gc of spec.globalChoices || []) {- steps.push({ kind: 'globalChoice', phase: 'global-choices', label: `global choice ${gc.name}`, target: { name: gc.name } });+ steps.push({ kind: 'globalChoice', phase: 'global-choices', label: `global choice ${gc.name}`, target: { name: gc.name, existing: gc.existing === true } });}if (spec.solution) {steps.push({ kind: 'solution', phase: 'solution', label: `solution ${spec.solution.uniqueName}`, target: { uniqueName: spec.solution.uniqueName } });@@ -1156,6 +1245,19 @@ async function runTeardown(spec, opts = {}, deps = {}) {for (const step of plan) {const myN = (n += 1);emit({ phase: step.phase, status: 'start', label: step.label, n: myN, total });+ // The solution goes last, and only once every step before it succeeded. It is how a re-run tells+ // this app's dashboards from same-named ones elsewhere (the dashboard resolver): deleted after a+ // failed step, it left the retry nothing to prove them by, so the retry kept them — and their+ // tiles then blocked the chart and view deletes on every later run. Deleting it removes only the+ // container (its components stay in the org), so keeping it costs nothing a re-run cannot finish.+ // A built-in container (Default/Active/Basic) is exempt: it proves nothing and is never deleted —+ // its own handler skips it below.+ if (step.kind === 'solution' && result.errors.length && !isRestrictedSolution(step.target.uniqueName)) {+ const why = `${step.label} (kept — ${result.errors.length} earlier step(s) failed, and a re-run needs this solution to tell the app's dashboards from same-named ones; it is deleted once the rest succeeds)`;+ result.skipped.push(why);+ emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });+ continue;+ }const handler = KIND_HANDLERS[step.kind];try {let resolved;@@ -1164,8 +1266,10 @@ async function runTeardown(spec, opts = {}, deps = {}) {} catch (resolveErr) {// Resolving forms/charts/views filters by an entity's typecode; if that entity was never// created (partial build) or is already gone, Dataverse answers 400 "entity ... not found- // in the MetadataCache". There is nothing to delete — treat it as an empty resolution.- if (isNotFound(resolveErr)) { resolved = []; } else { throw resolveErr; }+ // in the MetadataCache". There is nothing to delete — treat it as an empty resolution. A resolver+ // marks an error `failClosed` when not being able to look is itself the failure (the dashboard+ // ownership read): its message may quote a "not found", but it must never read as nothing there.+ if (isNotFound(resolveErr) && !resolveErr.failClosed) { resolved = []; } else { throw resolveErr; }}// resolve returns either an array of items, or `{ items, skipReason }` when the step is// intentionally NOT torn down (e.g. a reused/system table the build did not create). The@@ -1174,7 +1278,9 @@ async function runTeardown(spec, opts = {}, deps = {}) {const skipReason = Array.isArray(resolved) ? null : resolved.skipReason;if (!items.length) {result.skipped.push(skipReason ? `${step.label} (${skipReason})` : step.label);- emit({ phase: step.phase, status: 'skip', label: `${step.label} (${skipReason || 'not found'})`, n: myN, total });+ // `skip` says WHICH kind of skip this is, for the summary: nothing there to delete, or a step+ // that found the artifact and deliberately left it (every `skipReason` is a keep-on-purpose).+ emit({ phase: step.phase, status: 'skip', skip: skipReason ? 'kept' : 'not-found', label: `${step.label} (${skipReason || 'not found'})`, n: myN, total });continue;}const { deletedIds, skipped } = await deleteStep(sdk, handler, items);@@ -1211,7 +1317,8 @@ async function runTeardown(spec, opts = {}, deps = {}) {const rest = plan[i];const why = `${rest.label} (not attempted — the app was not deleted)`;result.skipped.push(why);- emit({ phase: rest.phase, status: 'skip', label: why, n: i + 1, total });+ // Never queried, so the environment says nothing about it: counted apart from "not found".+ emit({ phase: rest.phase, status: 'skip', skip: 'not-attempted', label: why, n: i + 1, total });}break;}diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 59b73a7cc..288155e3f 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -5,10 +5,11 @@// { ok, checks:[{kind,name,present,detail}], missing:[…] }.const { odataLit } = require('./odata.js');-const { matchContainer, isEngineOwnedSection } = require('./form-container-match.js');+const { matchContainer, isEngineOwnedSection, isEngineHostSection, claimedByAuthoredName } = require('./form-container-match.js');+const { authoredSectionNames } = require('./app-spec.js');const { decodeXmlEntities } = require('./sitemap-pages.js');const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf } = require('./app-spec.js');-const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef } = require('./sdk-build.js');+const { resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, appUniqueName, businessRuleFilter, bpfFilter, viewDef, dashboardsInSolution, findDashboardsByName } = require('./sdk-build.js');const { extractNavTargets } = require('./pageref-resolver.js');const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');@@ -178,6 +179,89 @@ async function verifySpec(spec, read, opts = {}) {const rows = await read.queryRecords('savedqueryvisualization', { select: ['savedqueryvisualizationid'], filter: `primaryentitytypecode eq '${String(ch.entity).toLowerCase()}' and name eq '${odataLit(ch.name)}'`, top: 1 });add('chart', ch.name, rows && rows[0]);}+ // DASHBOARDS — existence, then that every deployed chart tile is internally consistent (#586 item 3).+ // A chart tile names a table (`TargetEntityType`), a view and a chart. The platform accepts and+ // publishes a tile whose chart belongs to ANOTHER table, and two same-named charts on different+ // tables made the build produce exactly that — live, with the dashboard present and verify passing.+ // So a dashboard is proven only when each chart tile's view and chart both belong to its table.+ //+ // Existence is checked for every dashboard. The tile check needs `dashboardComponents` on the+ // reader (additive and reader-gated, like the other content checks); the CLI's reader supplies it.+ // Every read failure is reported as unverified, never as correct.+ const ownerTable = async (table, idColumn, entityColumn, id) => {+ if (!id) return undefined;+ try {+ const rows = await read.queryRecords(table, { select: [entityColumn], filter: `${idColumn} eq ${id}`, top: 1 });+ return rows && rows[0] ? String(rows[0][entityColumn] || '').toLowerCase() : null; // null = no such row+ } catch { return undefined; } // undefined = could not look+ };+ // Tile parameters carry braced GUIDs (`{…}`); a filter needs the bare, unquoted form.+ const bareGuid = (g) => { const s = String(g || '').replace(/[{}]/g, '').trim().toLowerCase(); return /^[0-9a-f-]{36}$/.test(s) ? s : ''; };+ // The dashboard this spec builds, by name → `{ id }`, or `{ id: null, detail }` when it is absent or+ // cannot be told apart. A name can also match another app's dashboard (names are not unique, and+ // Dataverse compares them ignoring case, most accents and trailing spaces), so with several matches+ // it is the one the app's solution holds — the one the build reuses (dashboardsInSolution,+ // sdk-build.js). The dashboard check below and the sitemap subarea check both ask this, so the two+ // can never pick different dashboards: live, the subarea check took the first match, and a+ // same-named dashboard of another app sorted first and failed a correctly wired app. Memoized per+ // name, so each name is read once.+ const ownDashboards = new Map();+ const identifyDashboard = async (name) => {+ let rows = null;+ try {+ rows = await findDashboardsByName(read, name);+ } catch (e) {+ return { id: null, detail: `could not be read (${(e && e.message) || e}) — unverified, not proven correct` };+ }+ if (!rows || !rows.length) return { id: null, detail: '' };+ if (rows.length === 1) return { id: rows[0].id };+ let ours = null;+ let why = '';+ try {+ const members = await dashboardsInSolution(read, spec.solution && spec.solution.uniqueName, rows.map((r) => r.id));+ ours = members ? rows.filter((r) => members.has(String(r.id).replace(/[{}]/g, '').toLowerCase())) : null;+ } catch (e) {+ why = ` (${(e && e.message) || e})`;+ }+ if (ours && ours.length === 1) return { id: ours[0].id };+ const reason = ours === null+ ? `this app's solution cannot say which is its own${why}`+ : `${ours.length ? `${ours.length} of them are` : 'none of them is'} in this app's solution`;+ return { id: null, detail: `${rows.length} dashboards share this name and ${reason}, so the one this spec builds cannot be identified` };+ };+ const ownDashboard = (name) => {+ if (!ownDashboards.has(name)) ownDashboards.set(name, identifyDashboard(name));+ return ownDashboards.get(name);+ };+ for (const d of spec.dashboards || []) {+ if (!d || !d.name) continue;+ const own = await ownDashboard(d.name);+ if (!own.id) { add('dashboard', d.name, false, own.detail); continue; }+ const dashboardId = own.id;+ if (typeof read.dashboardComponents !== 'function') { add('dashboard', d.name, true); continue; }+ const problems = [];+ let components = null;+ try { components = await read.dashboardComponents(dashboardId); } catch (e) {+ problems.push(`its tiles could not be read (${(e && e.message) || e}) — unverified, not proven correct`);+ }+ for (const c of components || []) {+ if (!c || c.type !== 'chart') continue;+ const p = c.parameters || {};+ const table = String(p.TargetEntityType || '').toLowerCase();+ const label = `chart tile '${c.name || '(unnamed)'}'`;+ const chartTable = await ownerTable('savedqueryvisualization', 'savedqueryvisualizationid', 'primaryentitytypecode', bareGuid(p.VisualizationId));+ const viewTable = await ownerTable('savedquery', 'savedqueryid', 'returnedtypecode', bareGuid(p.ViewId));+ if (chartTable === undefined || viewTable === undefined) {+ problems.push(`${label}: its chart or view could not be resolved — unverified, not proven correct`);+ } else if (chartTable !== table || viewTable !== table) {+ const wrong = [];+ if (chartTable !== table) wrong.push(`its chart ${chartTable ? `belongs to ${chartTable}` : 'does not exist'}`);+ if (viewTable !== table) wrong.push(`its view ${viewTable ? `belongs to ${viewTable}` : 'does not exist'}`);+ problems.push(`${label} shows ${table || '(no table)'}, but ${wrong.join(' and ')}`);+ }+ }+ add('dashboard', d.name, problems.length === 0, problems.join('; '));+ }for (const f of spec.forms || []) {const name = f.name || `${f.entity} form`;// Resolve with the SAME identity the build reconcile uses — (entity, name, TYPE) or a validated pinned@@ -309,6 +393,9 @@ async function verifySpec(spec, read, opts = {}) {// AUTHORED name reported a perfectly good auto-to-explicit migration as "section absent" and// failed a build that had done exactly what was asked. Live-reproduced.const claimedTabs = new Set();+ // The section names the author declared — the same set the build's compiler records — so the+ // label and position passes skip a section another want owns by name, exactly as the build does.+ const authoredNames = authoredSectionNames(f);f.tabs.forEach((t, ti) => {if (!t || typeof t !== 'object') return;const tabName = String(t.name || generatedTabName(ti)).toLowerCase();@@ -331,8 +418,12 @@ async function verifySpec(spec, read, opts = {}) {sections.forEach((sec, si) => {if (!sec || typeof sec !== 'object') return;const secName = String(sec.name || generatedSectionName(ti, ci, si)).toLowerCase();+ // Every want here is authored (the spec's own sections), and an authored section never+ // matches an engine HOST by name, label or position — the same rule the build's topology pass+ // follows, a host a maker added a field to included. A section a maker filled with a control+ // but that carries the authored name is still found by it.const secHit = matchContainer(deployedSections, { name: secName, label: sec.label || 'Details' }, si,- { claimed: claimedSections, skip: isEngineOwnedSection });+ { claimed: claimedSections, skip: (s) => isEngineOwnedSection(s) || isEngineHostSection(s) || claimedByAuthoredName(authoredNames)(s), nameSkip: isEngineHostSection });if (!secHit) {problems.push(`section '${secName}' is absent from tab '${tabName}' form-column ${ci + 1}`);return;@@ -583,12 +674,11 @@ async function verifySpec(spec, read, opts = {}) {for (const sa of g.subAreas || []) {if (sa.entity) add('subarea', sa.title || sa.entity, hasElement(xml, 'SubArea', { Entity: sa.entity }));if (sa.dashboard) {- // Resolve the declared dashboard (a system dashboard = systemform type 0) by name, then- // confirm the sitemap points a SubArea at THAT dashboard id — not just that some dashboard- // subarea exists. Missing/unresolvable dashboard => not present.- const rows = await read.queryRecords('systemform', { select: ['formid'], filter: `type eq 0 and name eq '${odataLit(sa.dashboard)}'`, top: 1 });- const dashId = rows && rows[0] && rows[0].formid;- add('subarea', sa.title || sa.dashboard, dashId ? subareaHasDashboard(xml, dashId) : false);+ // Confirm the sitemap points a SubArea at the dashboard this spec builds — not just that+ // some dashboard subarea exists, and not at another app's same-named dashboard, which the+ // name lookup returns too (see ownDashboard above). Absent or unidentifiable => not present.+ const own = await ownDashboard(sa.dashboard);+ add('subarea', sa.title || sa.dashboard, own.id ? subareaHasDashboard(xml, own.id) : false, own.id ? '' : own.detail);}if (sa.icon) {// Prefer matching the icon on the SubArea that also declares this entity; fall back to any@@ -1028,6 +1118,31 @@ async function verifySpec(spec, read, opts = {}) {}}+ // App routing description (`app.aiDescription`, #583). Asserted only when the spec sets one: absent+ // means the build left the deployed value alone, so there is nothing to compare. The oracle is the+ // row's own `appmodule.aiappdescription`, found by the SAME identity the build wrote under+ // (`appUniqueName(spec)`). Reader-gated on `queryRecords`; a failed read FAILS the check, because a+ // routing description nobody can read back is not proven applied.+ const wantAiDescription = spec.app && typeof spec.app.aiDescription === 'string' && spec.app.aiDescription.trim()+ ? spec.app.aiDescription : null;+ if (wantAiDescription && typeof read.queryRecords === 'function') {+ let got;+ let error;+ try {+ const rows = await read.queryRecords('appmodule', { select: ['aiappdescription'], filter: `uniquename eq '${odataLit(appUniqueName(spec))}'`, top: 1 });+ if (!rows || !rows[0]) error = `no app module with unique name '${appUniqueName(spec)}' was found`;+ else got = rows[0].aiappdescription;+ } catch (e) {+ error = (e && e.message) || String(e);+ }+ const present = !error && got === wantAiDescription;+ const shown = (s) => JSON.stringify(s.length > 80 ? `${s.slice(0, 77)}...` : s);+ add('app-ai-description', 'app.aiDescription', present, present ? ''+ : error ? `could not read the app's routing description: ${error}`+ : got ? `the deployed routing description ${shown(got)} differs from the spec's`+ : 'the app has no routing description (appmodule.aiappdescription is empty)');+ }+// AI row summaries (`ai.summaries`). AB#6689110.//// Without this a spec that REQUESTS a row summary verified clean when none was created: the build@@ -1362,10 +1477,13 @@ function parseFormTopology(xml) {// Only BOUND fields reach `fields[]`. A control with no `datafieldname` is a sub-grid, the// notes timeline or a web resource — engine-owned, never something the spec's field list// claims to place. The CELL still records that a control was present, because that is what- // distinguishes an engine-owned section from a merely empty one.+ // distinguishes an engine-owned section from a merely empty one — and its `classid`+ // (`{06375649-C143-495E-A496-C962E5B4488E}`, braces and case as written), which is what still+ // marks a timeline or sub-grid host a maker added a field to (isEngineHostSection).const f = attr(raw, 'datafieldname');+ const classId = attr(raw, 'classid');if (f) section.fields.push(String(f).toLowerCase());- if (cell) cell.control = f ? { fieldName: String(f).toLowerCase() } : {};+ if (cell) cell.control = Object.assign(f ? { fieldName: String(f).toLowerCase() } : {}, classId ? { classId } : {});}}return tabs;diff --git a/plugins/model-apps/scripts/teardown-model-app.js b/plugins/model-apps/scripts/teardown-model-app.jsindex c2bb34730..69598a372 100644--- a/plugins/model-apps/scripts/teardown-model-app.js+++ b/plugins/model-apps/scripts/teardown-model-app.js@@ -8,7 +8,8 @@//// Usage:// node scripts/teardown-model-app.js --env <orgUrl> --spec @<app-folder>/app-spec.json [--apply]-// [--clear-workspace] [--workspace <dir>] (--workspace only scopes --clear-workspace)+// [--clear-workspace] [--workspace <dir>] (--workspace names the build's workspace: teardown+// fences its --changed-only snapshot there, and --clear-workspace removes it after a clean run)//// Order: app -> security roles -> dashboards -> command bars -> forms -> charts -> views// (then reset enriched default views) -> relationships -> AI row summaries -> tables@@ -60,8 +61,9 @@ async function makeSdk(env) {}// Turn engine progress events into a phase-grouped, status-marked teardown log — the same shape-// build-model-app.js uses: ▶ <phase>, then per step [n/total] with ✓ (deleted) / ⊘ (not found) /-// ✗ (failed). A dry-run lists the same plan with a ▢ marker. `opts.counts` accumulates totals.+// build-model-app.js uses: ▶ <phase>, then per step [n/total] with ✓ (deleted) / ⊘ (not found, kept on+// purpose, or not attempted — the label says which) / ✗ (failed). A dry-run lists the same plan with a ▢+// marker. `opts.counts` accumulates totals, with skips also tallied by kind for the summary.function cliEmit(log, opts = {}) {const counts = opts.counts;let phase = null;@@ -69,7 +71,10 @@ function cliEmit(log, opts = {}) {if (e.phase !== phase) { phase = e.phase; log(`\n▶ ${phase}`); }if (e.status === 'start') return;if (!opts.apply) { log(` [${e.n}/${e.total}] ▢ ${e.label}`); return; }- if (counts) counts[e.status] = (counts[e.status] || 0) + 1;+ if (counts) {+ counts[e.status] = (counts[e.status] || 0) + 1;+ if (e.status === 'skip') counts[e.skip || 'not-found'] = (counts[e.skip || 'not-found'] || 0) + 1;+ }const glyph = e.status === 'ok' ? '✓' : e.status === 'skip' ? '⊘' : '✗';const tail = e.status === 'error' && e.detail ? ` — ${e.detail}` : '';log(` [${e.n}/${e.total}] ${glyph} ${e.label}${tail}`);@@ -98,22 +103,77 @@ async function teardownModelApp(spec, opts, deps) {}}// TOMBSTONE the changed-only snapshot BEFORE any delete (design core invariant): eligible:false +- // teardown-in-progress debt, so a partial/crashed teardown leaves the tombstone and a surviving artifact- // can never be rebaselined as an eligible fast-path source. Best-effort — a lease contention is logged,- // not fatal (once the app is deleted, the fast-path identity check also blocks any stale snapshot).+ // teardown-in-progress debt + a rotated generation, so a partial/crashed teardown leaves the tombstone,+ // a surviving artifact can never be rebaselined as an eligible fast-path source, and a changed-only run+ // already in flight is fenced off (#587 item 1).+ //+ // The tombstone IS the fence, so failing to write it stops the teardown before it mutates (#587 item 2).+ // It used to warn and proceed — and if the app delete then failed after lower-level artifacts were+ // gone, the old ELIGIBLE snapshot survived describing a state that no longer existed. The usual cause+ // is a build holding the workspace lease right now; a stale lease is reclaimed automatically, so a+ // persistent failure means real contention or an unwritable workspace, and waiting is the fix.+ //+ // A workspace with NO snapshot gets a fresh tombstone too (a first changed-only build has none until it+ // finishes — see tombstoneSnapshot), creating the folder if it has to; `createdDir` is what to remove+ // again once the teardown is clean, so a folder that never had a workspace is left without one.+ let createdWorkspaceDir = null;+ let teardownId = null;+ let heartbeat = null;if (opts.apply && opts.workspaceDir) {const tomb = snapStore.tombstoneSnapshot(opts.workspaceDir);- if (!tomb.ok) log(`⚠ could not tombstone the changed-only snapshot before teardown (${tomb.reason}) — proceeding; the app-deletion identity check still blocks a stale snapshot`);+ if (!tomb.ok) {+ const msg = `could not fence the changed-only snapshot before teardown (${tomb.reason}) — nothing was deleted. Let any running build of this app finish, then re-run the teardown.`;+ log(`\n✗ ${msg}`);+ return { ok: false, errors: [msg] };+ }+ createdWorkspaceDir = tomb.createdDir || null;+ teardownId = tomb.teardownId || null;+ // While it runs, the teardown keeps its entry fresh (apply-snapshot-store.js liveTeardowns): an entry+ // counts as running only while it keeps being seen, so one a killed teardown left behind stops counting+ // within minutes. unref'd, so it never keeps the process alive; cleared the moment the teardown ends.+ if (teardownId) {+ heartbeat = setInterval(() => snapStore.beatTeardown(opts.workspaceDir, teardownId), snapStore.TEARDOWN_BEAT_MS);+ if (typeof heartbeat.unref === 'function') heartbeat.unref();+ }}- const r = await runTeardown(spec, { apply: opts.apply }, { sdk: deps.sdk, emit });- // After a CLEAN teardown, DELETE the snapshot envelope — the app is gone, so a fresh rebuild must start a- // new baseline. A teardown that finished WITH ERRORS leaves the tombstone in place (a surviving artifact- // must not be rebaselined). Best-effort.- if (opts.apply && opts.workspaceDir && r && r.ok && !r.dryRun) {- snapStore.deleteSnapshot(opts.workspaceDir);+ let r;+ try {+ r = await runTeardown(spec, { apply: opts.apply }, { sdk: deps.sdk, emit });+ } finally {+ if (heartbeat) clearInterval(heartbeat);+ // Every teardown that FINISHES drops its entry from the tombstone's list of teardowns in flight — a+ // clean one, one that finished with errors, and one that threw. An entry left behind read as a+ // teardown still running whenever its pid was alive (reused, slow to exit, or this very process), and+ // a later clean teardown then kept the fence for up to a day.+ //+ // Only a CLEAN teardown may also delete the snapshot — the app is gone, so a fresh rebuild must start a+ // new baseline — and then only as the last one to finish: an overlapping teardown still deleting keeps+ // its fence (releaseTombstone). One that failed or threw keeps the tombstone (`keep`: a surviving+ // artifact must not be rebaselined), in a folder it created too, since that tombstone is what keeps it.+ if (teardownId) {+ const clean = !!(r && r.ok && !r.dryRun);+ const rel = snapStore.releaseTombstone(opts.workspaceDir, teardownId, clean ? {} : { keep: true });+ if (clean && rel.ok && !rel.left) {+ if (createdWorkspaceDir) snapStore.removeCreatedDir(opts.workspaceDir, createdWorkspaceDir);+ } else if (clean) {+ // On the result, so main() leaves the workspace alone: --clear-workspace would delete the fence.+ r.snapshotKept = rel.reason;+ log(`\n▸ the changed-only snapshot stays tombstoned: ${rel.reason}.${rel.left ? ' The last of them to finish removes it.' : ' A --changed-only build full-builds until a clean teardown removes it.'}`);+ } else if (!rel.ok) {+ log(`\n▸ could not drop this teardown from the changed-only fence (${rel.reason}); the snapshot stays tombstoned, and a later teardown may keep it until this process has exited.`);+ }+ }}if (opts.apply && r && !r.dryRun) {- log(`\n${r.ok ? '✓' : '✗'} teardown ${r.ok ? 'complete' : 'finished with errors'} — ${counts.ok} deleted, ${counts.skip} not found, ${counts.error} failed (${counts.ok + counts.skip + counts.error} steps)`);+ // A skip is one of three different facts, and the summary used to call all of them "not found" —+ // after an app-delete abort that read "0 deleted, 8 not found, 1 failed" for eight steps nobody+ // queried. `kept` (left in place on purpose: existing:true, system tables, …) and `not attempted`+ // are shown only when non-zero, so an ordinary run reads exactly as it always did.+ const notFound = counts['not-found'] || 0;+ const kept = counts.kept || 0;+ const notAttempted = counts['not-attempted'] || 0;+ const extra = `${kept ? `, ${kept} kept` : ''}${notAttempted ? `, ${notAttempted} not attempted` : ''}`;+ log(`\n${r.ok ? '✓' : '✗'} teardown ${r.ok ? 'complete' : 'finished with errors'} — ${counts.ok} deleted, ${notFound} not found, ${counts.error} failed${extra} (${counts.ok + counts.skip + counts.error} steps)`);}return r;}@@ -123,7 +183,7 @@ async function main() {const { positional, flags } = parseArgs(argv);const USAGE ='Usage: node scripts/teardown-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--allow-destructive] [--clear-workspace] [--workspace <dir>]\n' +- ' Note: --workspace only controls the optional --clear-workspace cleanup; teardown itself uses a throwaway SDK workspace.';+ ' Note: --workspace names the build\'s workspace (default: .maker-workspace next to the spec). Teardown fences its --changed-only snapshot there before deleting anything, and --clear-workspace removes it after a clean run; the SDK itself uses a throwaway workspace.';// Strictness matters more here than anywhere else: this tool deletes. A mistyped// `--allow-destructiv` was previously dropped in silence, and the safety flag the operator// believed they had passed simply did not exist.@@ -163,12 +223,21 @@ async function main() {// shell variable that expanded to a repo root, destroyed real work. Refusal is a WARNING,// not a failure: the teardown itself already succeeded, and the cost of refusing is only a// stale cache directory the operator can remove by hand.- const clearable = checkWorkspaceClearable(workspaceDir);- if (clearable.ok) {- fs.rmSync(clearable.target, { recursive: true, force: true });- process.stderr.write(`\ncleared workspace ${clearable.target}\n`);+ //+ // A workspace whose changed-only snapshot is still tombstoned — another teardown of it is running,+ // or the release failed — is left whole: deleting it deletes the fence that teardown depends on.+ const clearable = r.snapshotKept+ ? { ok: false, reason: `the workspace still holds the changed-only fence (${r.snapshotKept}); clear it once that is done` }+ : checkWorkspaceClearable(workspaceDir);+ //+ // The clear itself runs under the workspace's lease, and only while no snapshot has appeared since this+ // teardown's release — another teardown's tombstone, say, which removing the folder in place after the+ // release deleted (apply-snapshot-store.js clearWorkspace).+ const cleared = clearable.ok ? snapStore.clearWorkspace(clearable.target) : clearable;+ if (cleared.ok) {+ process.stderr.write(`\ncleared workspace ${clearable.target}${cleared.leftover ? ` (${cleared.reason})` : ''}\n`);} else {- process.stderr.write(`\nskipped --clear-workspace: ${clearable.reason}\n`);+ process.stderr.write(`\nskipped --clear-workspace: ${cleared.reason}\n`);}}} catch (err) {diff --git a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.jsnew file mode 100644index 000000000..1d22db4bb--- /dev/null+++ b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js@@ -0,0 +1,291 @@+'use strict';+// REAL BUNDLE: the app routing description (`app.aiDescription` -> `appmodule.aiappdescription`, #583).+//+// The plugin's `applyAppAiDescription` and `haltOnUnpublishedAppHeader` lean on five SDK behaviours that+// its own unit tests can only stub:+// 1. a fetched app carries `aiDescription` ONLY when the row has a value;+// 2. `updateElement('/aiDescription')` on such an app rejects with PATH_NOT_FOUND, while an+// `addElement` at the artifact root adds the key;+// 3. the push PATCHes `aiappdescription` only when the value is set AND differs from the draft row —+// so an equal value, or a spec that leaves it out, never touches a platform-written description;+// 4. a 412 on that PATCH RESOLVES `{ saved:false }` with a VERSION_CONFLICT error rather than throwing,+// which is the shape the plugin's pending-draft halt keys on;+// 5. after such a refused push, a plain fetch refuses to discard the unpushed copy once the server has+// moved (LOCAL_EDITS_WOULD_BE_LOST), and `{ overwrite: true }` resets it — which is why the halt+// resets the copy before telling the operator to publish and re-run.+// A re-vendor could change any of them with every plugin test still green, so each is pinned here+// against the real bundle over a fake Dataverse — the same way sitemap-icon-real-bundle.test.js pins+// the sitemap write.+const test = require('node:test');+const assert = require('node:assert');+const os = require('node:os');+const path = require('node:path');+const fs = require('node:fs');+const { appDef, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader } = require('../lib/sdk-build.js');+const { requireSuccessfulPush } = require('../lib/entity-provision.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');+const APP_ID = '11111111-1111-1111-1111-111111111111';+const APP_UNIQUE = 'new_probeapp';+const APP_IDUNIQUE = '33333333-3333-3333-3333-333333333333';+const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';+const SITEMAP_ID = '55555555-5555-5555-5555-555555555555';+// Every app the plugin creates carries an icon, and the SDK requires one at create (see+// header-nav-real-bundle.test.js).+const APP_ICON_ID = '11111111-2222-3333-4444-555555555555';+const WANT = 'Dispatch work: assigning and rescheduling tickets. Prefer My Work for your own items.';++const SITEMAP_XML = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0" ShowGroups="true"><Titles><Title LCID="1033" Title="Main" /></Titles>'+ + '<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" /></Titles>'+ + '<SubArea Id="sub_0_0_0" Entity="new_torder" Client="All" Sku="All"><Titles><Title LCID="1033" Title="Orders" /></Titles></SubArea>'+ + '</Group></Area></SiteMap>';++const tempDirs = [];+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });++/**+ * A real SDK over a fake Dataverse holding one app. `ai` is the row's `aiappdescription` (omitted when+ * undefined), `componentstate` its draft state, and `headerStatus` the status the appmodule PATCH answers.+ * All three live on the returned `state`, which the fake reads on every call, so a test can change the+ * server under the SDK — e.g. the operator publishing between two runs, which also moves the etag.+ */+async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapStatus = 204 } = {}) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-description-'));+ tempDirs.push(dir);+ const writes = [];+ const reads = [];+ const state = { ai, componentstate, headerStatus, sitemapStatus, etag: 'W/"1"' };+ const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: 'Tickets', componentstate: state.componentstate, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), '@odata.etag': state.etag });+ const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: SITEMAP_XML, '@odata.etag': state.etag });+ const httpClient = {+ get: async (url) => {+ reads.push(String(url));+ const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);+ if (m) return { status: 200, headers: {}, body: { LogicalName: m[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${m[1]}s` } };+ if (/\/appmodulecomponents/.test(url)) {+ // componenttype 62 is the SITEMAP component; 1 is a table. The filter arrives URL-encoded.+ const wantsSitemap = /componenttype(%20| )eq(%20| )62/.test(url);+ return { status: 200, headers: {}, body: { value: wantsSitemap ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }] } };+ }+ // A collection read (`?$filter=…` or RetrieveUnpublishedMultiple) answers `{ value: [...] }`; a+ // by-id read answers the row itself.+ if (/\/sitemaps/.test(url)) {+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/sitemaps\?/.test(url);+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };+ }+ if (/\/appmodules/.test(url)) {+ // The halt's own draft read. While a draft exists, put the PUBLISHED row first, so the test proves+ // the unpublished layer is found wherever it sits: the live platform returned only the draft row,+ // but does not document that. The SDK's own reads never select componentstate, so they are unaffected.+ if (/componentstate/.test(decodeURIComponent(url)) && state.componentstate === 1) {+ return { status: 200, headers: {}, body: { value: [{ ...appRow(), componentstate: 0 }, appRow()] } };+ }+ const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);+ return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [appRow()] } : appRow() };+ }+ if (/\/roles/.test(url)) return { status: 200, headers: {}, body: { value: [{ roleid: '66666666-6666-6666-6666-666666666666' }] } };+ return { status: 200, headers: {}, body: { value: [] } };+ },+ post: async (url, body) => {+ writes.push({ verb: 'post', url: String(url), body });+ return { status: 204, headers: { 'odata-entityid': `https://x/y(${APP_ID})` }, body: {} };+ },+ patch: async (url, body) => {+ writes.push({ verb: 'patch', url: String(url), body });+ if (/\/appmodules\(/.test(url)) {+ if (state.headerStatus !== 204) {+ // 400 is how Dataverse refuses a header write on a never-published appmodule; the SDK recognises+ // it by this phrase and THROWS APP_DRAFT_HEADER_NOT_WRITABLE. 412 is the returned conflict.+ const message = state.headerStatus === 400 ? 'The retrieval of version numbers failed.' : 'The version of the existing record doesn\'t match the RowVersion property provided.';+ return { status: state.headerStatus, headers: {}, body: { error: { code: '0x80060882', message } } };+ }+ if (body && body.aiappdescription !== undefined) state.ai = body.aiappdescription;+ // LIVE-MEASURED: a header write that is not yet published leaves the row an unpublished layer.+ state.componentstate = 1;+ }+ if (/\/sitemaps\(/.test(url) && state.sitemapStatus !== 204) {+ return { status: state.sitemapStatus, headers: {}, body: { error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match the RowVersion property provided.' } } };+ }+ return { status: 204, headers: { etag: 'W/"2"' }, body: {} };+ },+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ put: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ return { sdk, writes, reads, state };+}++const spec = (aiDescription) => ({+ solution: { uniqueName: 'probe', publisherPrefix: 'new' },+ app: { name: 'Probe', description: 'Tickets', ...(aiDescription !== undefined ? { aiDescription } : {}) },+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [{ entity: 'new_torder', label: 'Orders' }] }] }] },+});+const headerWrites = (writes) => writes.filter((w) => /\/appmodules/.test(w.url) && w.body && typeof w.body === 'object');+const anyWriteCarries = (writes) => writes.some((w) => w.body && typeof w.body === 'object' && 'aiappdescription' in w.body);++test('REAL BUNDLE: a new app is created with the routing description the plugin projects', async () => {+ const { sdk, writes } = await freshSdk();+ const def = appDef(spec(WANT), { forms: {}, views: {}, charts: {} }, { iconWebResourceId: APP_ICON_ID });+ const art = await sdk.createArtifact('app', def);+ await sdk.pushArtifact('app', art.id);+ const create = writes.find((w) => w.verb === 'post' && /\/appmodules\b/.test(w.url) && w.body && w.body.uniquename);+ assert.ok(create, `an appmodule create was posted; writes: ${JSON.stringify(writes.map((w) => `${w.verb} ${w.url}`))}`);+ assert.strictEqual(create.body.aiappdescription, WANT);+});++test('REAL BUNDLE: an app with none has no key, refuses an update, and gets it ADDED and written', async () => {+ const { sdk, writes } = await freshSdk();+ const fetched = await sdk.fetchArtifact('app', APP_ID);+ assert.ok(!('aiDescription' in fetched), 'a fetched app carries the key only when the row has a value');+ // The contract the helper's add-vs-update branch exists for.+ // sdk-async-ok: the promise is handed to assert.rejects, which awaits it.+ await assert.rejects(sdk.updateElement('app', APP_ID, '/aiDescription', WANT), (e) => e && e.code === 'PATH_NOT_FOUND');++ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ const res = await sdk.pushArtifact('app', APP_ID);+ assert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));+ const header = headerWrites(writes);+ assert.strictEqual(header.length, 1, 'one header write');+ assert.strictEqual(header[0].body.aiappdescription, WANT);+ assert.strictEqual(header[0].body.description, 'Tickets', 'the tile description rides through unchanged');+});++test('REAL BUNDLE: a different value is updated in place and written', async () => {+ const { sdk, writes } = await freshSdk({ ai: 'Old routing text.' });+ assert.strictEqual((await sdk.fetchArtifact('app', APP_ID)).aiDescription, 'Old routing text.');+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ assert.strictEqual((await sdk.pushArtifact('app', APP_ID)).saved, true);+ assert.deepStrictEqual(headerWrites(writes).map((w) => w.body.aiappdescription), [WANT]);+});++test('REAL BUNDLE: an equal value, or a spec without one, never writes the header', async () => {+ for (const [what, row, want] of [['an equal value', WANT, WANT], ['a spec without one', 'Written by the platform.', undefined]]) {+ const { sdk, writes } = await freshSdk({ ai: row });+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual(await applyAppAiDescription(sdk, spec(want), APP_ID), false, what);+ // The rebuild still rewrites the sitemap, exactly as the existing-app path does.+ await sdk.updateElement('app', APP_ID, '/siteMap', appDef(spec(want), { forms: {}, views: {}, charts: {} }).siteMap);+ assert.strictEqual((await sdk.pushArtifact('app', APP_ID)).saved, true, what);+ assert.ok(writes.some((w) => /\/sitemaps\(/.test(w.url)), `${what}: the sitemap was written`);+ assert.strictEqual(headerWrites(writes).length, 0, `${what}: the appmodule header is not PATCHed`);+ assert.ok(!anyWriteCarries(writes), `${what}: no write carries aiappdescription`);+ }+});++test('REAL BUNDLE: a 412 on the header resolves saved:false, and only a PROVEN draft is re-explained', async () => {+ for (const [componentstate, expected] of [[1, 'app-header-unpublished'], [0, 'version-conflict']]) {+ const { sdk, reads } = await freshSdk({ ai: 'Route Q1', componentstate, headerStatus: 412 });+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ const res = await sdk.pushArtifact('app', APP_ID);+ // The by-value shape the halt keys on. Were the SDK to THROW here instead, the plugin's halt would+ // never run and the operator would get a raw SDK error.+ assert.strictEqual(res.saved, false);+ assert.strictEqual(res.error && res.error.code, 'VERSION_CONFLICT');+ // …and the refused request is named, which is how the halt tells the header's 412 from the sitemap's.+ assert.match(String(res.error.detail), /^Version conflict \(412\) from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v[\d.]+\/appmodules\(11111111-1111-1111-1111-111111111111\)$/);++ const readsBefore = reads.length;+ let halt;+ try {+ await haltOnUnpublishedAppHeader(sdk, APP_ID, res, 'Probe');+ requireSuccessfulPush(res, 'app Probe');+ } catch (e) { halt = e; }+ assert.ok(halt, 'the refused push halts');+ assert.strictEqual(halt.code, expected, `componentstate ${componentstate}: ${halt.message}`);+ const draftRead = reads.slice(readsBefore).find((u) => /RetrieveUnpublishedMultiple/.test(u) && /componentstate/.test(u));+ assert.ok(draftRead, 'the draft state is read through the SDK\'s own Dataverse client');+ assert.match(decodeURIComponent(draftRead), /appmoduleid eq 11111111-1111-1111-1111-111111111111/);+ }+});++// The SDK writes an app header first and its sitemap second. A 412 on the SITEMAP — someone saved a+// sitemap edit since this run's fetch — comes after this push's header write has committed, so the draft+// read finds the unpublished layer that write just left. It is still a concurrent edit: the copy is kept,+// and a blind re-run stops instead of overwriting the other edit.+test('REAL BUNDLE: a sitemap 412 after the header committed is a concurrent edit, and the copy is kept', async () => {+ const { sdk, state, reads } = await freshSdk({ ai: 'Route Q1', sitemapStatus: 412 });+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ const readsBefore = reads.length;+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);+ assert.deepStrictEqual([state.ai, state.componentstate], [WANT, 1], 'precondition: the header PATCH committed and left the unpublished layer');+ assert.strictEqual(res.saved, false);+ assert.match(String(res.error && res.error.detail), /^Version conflict \(412\) from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v[\d.]+\/sitemaps\(55555555-5555-5555-5555-555555555555\)$/);+ assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict');+ assert.ok(!reads.slice(readsBefore).some((u) => /componentstate/.test(decodeURIComponent(u))), 'not re-diagnosed as a pending draft');+ // Someone saved the sitemap: the server has moved, and the kept copy stops the re-run's plain fetch.+ state.etag = 'W/"9"';+ await assert.rejects(sdk.fetchArtifact('app', APP_ID), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST');+});++// The deferred routing-description push refuses a DIRTY copy (sdk-build.js): a plain fetch returns a copy+// holding an earlier run's unpushed sitemap rewrite unchanged, and pushing the routing description would+// replay it. That leans on the SDK's own dirty flag, pinned here: an app edit a failed push left behind is+// reported dirty, and a fresh fetch clears it.+test('REAL BUNDLE: an app edit a failed push left behind is reported dirty, and a fresh fetch clears it', async () => {+ const { sdk } = await freshSdk({ sitemapStatus: 500 });+ const listed = async () => (await sdk.listArtifacts('app')).find((a) => a.id === APP_ID);+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual((await listed()).isDirty, false, 'a fresh copy is clean');+ const edited = spec(undefined);+ edited.appShell.areas[0].groups[0].subAreas[0].label = 'Tickets';+ await sdk.updateElement('app', APP_ID, '/siteMap', appDef(edited, { forms: {}, views: {}, charts: {} }).siteMap);+ // sdk-async-ok: the push is expected to fail, and only the copy it leaves behind matters here.+ await sdk.pushArtifact('app', APP_ID).catch(() => {});+ assert.strictEqual((await listed()).isDirty, true, 'the unpushed rewrite is still in the copy');+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual((await listed()).isDirty, true, 'and a plain fetch keeps it while the server has not moved');+ await sdk.fetchArtifact('app', APP_ID, { overwrite: true });+ assert.strictEqual((await listed()).isDirty, false, 'a fresh fetch clears it');+});++test('REAL BUNDLE: after the pending-draft halt, "publish, then re-run" really converges', async () => {+ // Run 1 is refused; the operator publishes, which settles the draft and MOVES the server's etag; run 2+ // does exactly what the build does — a plain fetch, then the helper, then a push.+ const run1 = async ({ halt }) => {+ const env = await freshSdk({ ai: 'Route Q1', componentstate: 1, headerStatus: 412 });+ await env.sdk.fetchArtifact('app', APP_ID);+ await applyAppAiDescription(env.sdk, spec(WANT), APP_ID);+ const res = await env.sdk.pushArtifact('app', APP_ID);+ assert.strictEqual(res.saved, false);+ if (halt) await assert.rejects(haltOnUnpublishedAppHeader(env.sdk, APP_ID, res, 'Probe'), (e) => e.code === 'app-header-unpublished' && !/\.maker-workspace/.test(e.message));+ Object.assign(env.state, { componentstate: 0, headerStatus: 204, etag: 'W/"8"' });+ return env;+ };++ // CONTROL — why the halt resets the copy: without it, the re-run's plain fetch refuses to discard the+ // refused push's edits now that the server has moved, and the re-run halts again.+ const control = await run1({ halt: false });+ await assert.rejects(control.sdk.fetchArtifact('app', APP_ID), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST');++ const { sdk, state } = await run1({ halt: true });+ const fetched = await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual(fetched.aiDescription, 'Route Q1', 'the re-run sees the server again, not the refused edit');+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ assert.strictEqual((await sdk.pushArtifact('app', APP_ID)).saved, true);+ assert.strictEqual(state.ai, WANT, 'the routing description lands on the re-run');+});++test('REAL BUNDLE: a never-published app THROWS its header refusal, and pushAppHeader turns it into the precise halt', async () => {+ // The raw SDK throws rather than resolving saved:false — the shape pushAppHeader exists to catch.+ const raw = await freshSdk({ headerStatus: 400 });+ await raw.sdk.fetchArtifact('app', APP_ID);+ await applyAppAiDescription(raw.sdk, spec(WANT), APP_ID);+ // sdk-async-ok: the promise is handed to assert.rejects, which awaits it.+ await assert.rejects(raw.sdk.pushArtifact('app', APP_ID), (e) => e && e.code === 'APP_DRAFT_HEADER_NOT_WRITABLE');++ const { sdk, state } = await freshSdk({ headerStatus: 400 });+ await sdk.fetchArtifact('app', APP_ID);+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ await assert.rejects(pushAppHeader(sdk, APP_ID, 'Probe', true), (e) => e.code === 'app-header-unpublished' && /never been published/.test(e.message) && !/\.maker-workspace/.test(e.message));++ // The operator publishes (the header becomes writable and the etag moves); the re-run converges.+ Object.assign(state, { headerStatus: 204, etag: 'W/"8"' });+ assert.ok(!('aiDescription' in await sdk.fetchArtifact('app', APP_ID)), 'the reset copy is the server\'s, not the refused edit');+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);+ assert.strictEqual((await pushAppHeader(sdk, APP_ID, 'Probe', true)).saved, true);+ assert.strictEqual(state.ai, WANT);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/app-spec-doc.test.js b/plugins/model-apps/scripts/tests/app-spec-doc.test.jsindex 2dcf7f0eb..31ee5fdf4 100644--- a/plugins/model-apps/scripts/tests/app-spec-doc.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-doc.test.js@@ -107,6 +107,16 @@ function unescapedPipeCount(row) {return n;}+test('the routing description is shown beside the tile text, and only when the spec sets one (#583)', () => {+ const spec = realisticSpec();+ assert.ok(!renderAppSpecDoc(spec, {}).includes('Routing description'));+ spec.app.aiDescription = 'Support work. Prefer My Tickets for your own assigned items.';+ const md = renderAppSpecDoc(spec, {});+ const at = md.indexOf('**Routing description:** Support work. Prefer My Tickets for your own assigned items.');+ assert.ok(at > md.indexOf(spec.app.description), 'after the tile description');+ assert.ok(at < md.indexOf('## Environment'), 'in the overview, before the first section');+});+test('renders every expected section heading in document order', () => {const md = renderAppSpecDoc(realisticSpec(), { envUrl: 'https://x.crm.dynamics.com' });const expected = [diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.jsindex 8e33c778d..a0133ebfd 100644--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js@@ -2,6 +2,7 @@ const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');const { validateAppSpec } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));+const { buildSeedGroup } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));function base() {return {@@ -196,6 +197,28 @@ test('app.newLook must be a boolean', () => {// Absent is fine — the new look is opt-in.assert.strictEqual(validateAppSpec(base(), { profile: 'plan' }).ok, true);});++// #583: the routing description. A non-empty string up to the column's 1,048,576-character maximum.+// Blank is refused rather than written: absent means "leave the deployed value alone", so an empty+// string is the one value that could blank a description nobody asked to remove.+test('app.aiDescription is a non-empty string within the column maximum', () => {+ const withValue = (v) => { const s = base(); s.app.aiDescription = v; return validateAppSpec(s, { profile: 'plan' }); };+ const ok = withValue('Dispatch work. Prefer My Work for your own assigned items.');+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.errors));+ assert.strictEqual(withValue('x'.repeat(1048576)).ok, true, 'exactly the maximum is accepted');+ for (const [v, re] of [+ [42, /app.aiDescription must be a string/],+ ['', /app.aiDescription must not be blank/],+ [' ', /app.aiDescription must not be blank/],+ ['x'.repeat(1048577), /app.aiDescription is 1048577 characters \(max 1048576\)/],+ ]) {+ const r = withValue(v);+ assert.strictEqual(r.ok, false, String(v).slice(0, 20));+ assert.ok(r.errors.some((e) => re.test(e)), JSON.stringify(r.errors));+ }+ assert.strictEqual(validateAppSpec(base(), { profile: 'plan' }).ok, true, 'absent is fine');+ assert.strictEqual(withValue(null).ok, true, 'null reads as absent, like an omitted key');+});// ---------------------------------------------------------------------------------------------// #537 — entities[] had no allow-list, so a key with no reader validated clean and was dropped.@@ -587,6 +610,42 @@ test('sampleData: duplicate detection keys values exactly the way the loader doe'and so are two identical numbers');});+// #586 item 2: the loader looks for duplicates only AFTER resolveSampleRecords has turned every Choice+// value into its option integer, so a label, its other-language alias and the raw integer are ONE key+// there. The gate compared the values as authored, passed the spec, and the seed then refused it —+// after tables, forms and views were already deployed. The gate must see what the loader sees, so this+// checks the two against each other rather than against a hand-written expectation.+test('sampleData: duplicate detection compares Choice values as the options they resolve to', () => {+ const withChoiceKey = (rows) => {+ const s = base();+ s.entities[0].columns = [{ schemaName: 'contoso_code', displayName: 'Code', type: 'Choice',+ options: [{ 1033: 'Open', 1036: 'Ouvert' }, { 1033: 'Closed', 1036: 'Fermé' }] }];+ s.entities[0].alternateKeys = [{ name: 'k', columns: ['contoso_code'] }];+ s.sampleData = { contoso_order: rows };+ return s;+ };+ const gateSays = (s) => validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /duplicate contoso_code/.test(e));+ const loaderSays = (s) => {+ try { buildSeedGroup({ spec: s, e: s.entities[0], records: s.sampleData.contoso_order, statusReasonValues: {} }); return null; } catch (e) { return e.message; }+ };+ const cases = [+ ['a label and its other-language alias', ['Open', 'Ouvert'], true],+ ['a label and the raw option integer', ['Open', 100000000], true],+ ['an alias and the raw option integer', ['Ouvert', 100000000], true],+ ['two different options, in two languages', ['Open', 'Fermé'], false],+ ];+ for (const [what, [first, second], dup] of cases) {+ const s = withChoiceKey([{ contoso_name: 'A', contoso_code: first }, { contoso_name: 'B', contoso_code: second }]);+ const loader = loaderSays(s);+ assert.strictEqual(Boolean(loader), dup, `precondition — the loader ${dup ? 'refuses' : 'accepts'} ${what}: ${loader}`);+ assert.strictEqual(gateSays(s).length, dup ? 1 : 0, `${what}: the gate must agree with the loader; got ${JSON.stringify(gateSays(s))}`);+ }+ // The author wrote neither side as an integer, so the message names what they DID write.+ const [msg] = gateSays(withChoiceKey([{ contoso_name: 'A', contoso_code: 'Open' }, { contoso_name: 'B', contoso_code: 'Ouvert' }]));+ assert.match(msg, /'Ouvert'/);+ assert.match(msg, /same option as 'Open'/);+});+// A generated fallback name is a REAL identity, not a placeholder: the reconcile matches a deployed// container by name. So an unnamed section and an explicit `name: "section_0_0"` are the same// container to every rebuild path, while create emits two. MEASURED before this gate: the compiled@@ -767,8 +826,8 @@ test('minimumPluginVersion refuses a spec that needs a newer plugin than the oneassert.match(tooNew[0], new RegExp(`running plugin is ${String(version).replace(/\./g, '\\.')}`), 'and the version actually running');assert.match(tooNew[0], /upgrade the plugin/, 'and tells the author to upgrade rather than delete the line');- // Pre-release and build-metadata suffixes compare on the release CORE. Astra review caught the- // first attempt splitting on dots BEFORE stripping the suffix, which turned `2.8.0-beta.1` into+ // Pre-release and build-metadata suffixes compare on the release CORE. A first attempt split on+ // dots BEFORE stripping the suffix, which turned `2.8.0-beta.1` into// [2,8,0,1] — so the running release compared as OLDER than its own pre-release and refused to// build. A dotted suffix is the case a single-token `-beta` test cannot catch.for (const suffix of ['-beta', '-beta.1', '+build.1', '-rc.2']) {@@ -802,8 +861,8 @@ test('minimumPluginVersion refuses a spec that needs a newer plugin than the one`${JSON.stringify(good)} must be accepted as well-formed, got ${JSON.stringify(e)}`);}- // FAIL CLOSED when this plugin cannot read its own version. Astra review caught the first attempt- // downgrading that to a warning, which let an incompatible install reach the write path with the+ // FAIL CLOSED when this plugin cannot read its own version. A first attempt downgraded+ // that to a warning, which let an incompatible install reach the write path with the// requirement neither satisfied nor overridden. Driven by making BOTH manifest reads throw.const fs = require('node:fs');const realRead = fs.readFileSync;diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.jsindex c15a7b908..5adda76c2 100644--- a/plugins/model-apps/scripts/tests/app-spec.test.js+++ b/plugins/model-apps/scripts/tests/app-spec.test.js@@ -2,7 +2,7 @@ const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');const fs = require('node:fs');-const { validateAppSpec, columnTypeMap, relationshipFor, lookupColumnsFor, childRelationshipsFor, relationshipSchemaName, manyToManySchemaName, resolveSampleRecords, migrateAppSpec, quickCreateEnabledFor } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));+const { validateAppSpec, columnTypeMap, relationshipFor, lookupColumnsFor, childRelationshipsFor, relationshipSchemaName, manyToManySchemaName, resolveSampleRecords, migrateAppSpec, quickCreateEnabledFor, dashboardNameKey } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));const sample = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.project-tracker.json'), 'utf8')@@ -442,14 +442,112 @@ test('validateAppSpec rejects a command with no function', () => {test('validateAppSpec accepts a dashboard with chart + list tiles on declared view/chart', () => {const ok = cloneDesk();+ // The chart and its view must be on the SAME table (a mismatch cross-wires the tile, #586 item 3).+ const chart = ok.charts[0];+ const view = ok.views.find((v) => v.entity === chart.entity);ok.dashboards = [{ name: 'Ops', tiles: [- { type: 'chart', chart: ok.charts[0].name, view: ok.views[0].name },+ { type: 'chart', chart: chart.name, view: view.name },{ type: 'list', view: ok.views[0].name, name: 'List' },] }];const r = validateAppSpec(ok);assert.strictEqual(r.ok, true, JSON.stringify(r.errors));});+// #586 item 3: view and chart names are unique only PER TABLE, and the build resolves both on the+// tile's table. Same names across tables are legitimate; a tile that mixes tables, or cannot say+// which table it means, is not.+test('validateAppSpec accepts same-named charts on two tables when each tile stays on one table', () => {+ const ok = cloneDesk();+ const ticketChart = ok.charts.find((c) => c.entity === 'new_ticket');+ ok.charts.push({ ...ticketChart, entity: 'new_customer', groupBy: 'new_segment' }); // same name, other table+ ok.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: ticketChart.name, view: 'Active Tickets' }] }];+ const r = validateAppSpec(ok);+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+});++test("validateAppSpec rejects a chart tile whose chart is declared on a different table than its view", () => {+ const bad = cloneDesk();+ const ticketChart = bad.charts.find((c) => c.entity === 'new_ticket');+ bad.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: ticketChart.name, view: 'Active Customers' }] }];+ const r = validateAppSpec(bad);+ assert.ok(r.errors.some((e) => /chart tile shows new_customer .* is declared on new_ticket/.test(e)), JSON.stringify(r.errors));+});++test('validateAppSpec requires a tile to name its table when its view name exists on more than one', () => {+ const spec = cloneDesk();+ const customerView = spec.views.find((v) => v.entity === 'new_customer');+ spec.views.push({ ...customerView, name: 'Active Tickets' }); // now "Active Tickets" exists on two tables+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'List' }] }];+ const ambiguous = validateAppSpec(spec);+ assert.ok(ambiguous.errors.some((e) => /declared on more than one table .* set the tile's entity/.test(e)), JSON.stringify(ambiguous.errors));+ spec.dashboards[0].tiles[0].entity = 'new_ticket';+ const pinned = validateAppSpec(spec);+ assert.strictEqual(pinned.ok, true, JSON.stringify(pinned.errors));+});++test("validateAppSpec rejects a tile whose entity does not declare the view it names", () => {+ const bad = cloneDesk();+ bad.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Customers', entity: 'new_ticket', name: 'List' }] }];+ const r = validateAppSpec(bad);+ assert.ok(r.errors.some((e) => /names view 'Active Customers' on new_ticket, but that view is declared on new_customer/.test(e)), JSON.stringify(r.errors));+});++// #586 item 4: a sitemap subarea and the build find a dashboard by NAME, through a Dataverse filter+// that ignores case, most accents and trailing spaces, so two such names collapse into one dashboard+// and the other leaves the nav.+test('validateAppSpec rejects two dashboards whose names Dataverse would treat as one', () => {+ const bad = cloneDesk();+ const tile = { type: 'list', view: bad.views[0].name, name: 'List' };+ for (const [first, second] of [['Overview', 'OVERVIEW '], ['Café', 'CAFE'], ['Overview', 'Overview']]) {+ bad.dashboards = [{ name: first, tiles: [tile] }, { name: second, tiles: [tile] }];+ const r = validateAppSpec(bad);+ assert.ok(r.errors.some((e) => e.includes(`dashboard '${second}': has the same name as dashboard '${first}'`)), `${first} / ${second}: ${JSON.stringify(r.errors)}`);+ }+ // Differences the server keeps must stay legal: a leading space, and a vowel sign (a letter, not an accent).+ for (const [first, second] of [['Overview', 'Pipeline'], ['Overview', ' Overview'], ['कार', 'कर']]) {+ bad.dashboards = [{ name: first, tiles: [tile] }, { name: second, tiles: [tile] }];+ assert.strictEqual(validateAppSpec(bad).ok, true, `${JSON.stringify(first)} / ${JSON.stringify(second)} are distinct`);+ }+});++// Every pair below was written to a live English environment and read back with `eq`; `server` is what+// Dataverse answered. The key must agree, except where it deliberately folds MORE (a false rejection+// is loud and fixed by a rename; a missed collision silently drops a dashboard).+test('dashboardNameKey folds exactly what the server was measured to ignore', () => {+ const MEASURED = [+ ['Alpha', 'ALPHA', true], ['Café', 'Cafe', true], ['Résumé', 'Re\u0301sume\u0301', true],+ ['Bravo', 'Bravo ', true], ['Charlie ', 'Charlie', true], [' Delta', 'Delta', false],+ ['Echo\u00a0', 'Echo', false], ['Foxtrot\t', 'Foxtrot', false], ['कार', 'कर', false], ['กิน', 'กน', false],+ ['ばす', 'はす', true], ['مُحَمَّد', 'محمد', false], ['йод', 'иод', false], ['ёж', 'еж', true], ['Жук', 'ЖУК', true],+ ['Straße', 'Strasse', true], ['Golf', 'Golf', true], ['Æther', 'AEther', true], ['file', 'file', true],+ ['Άλφα', 'Αλφα', true], ['Việt', 'Viet', true], ['שָׁלוֹם', 'שלום', true], ['Tăng', 'Tang', true],+ ['Øre', 'Ore', true], ['Łódź', 'Lodz', true], ['Đà', 'Da', true], ['Œuvre', 'Oeuvre', true],+ ['İstanbul', 'Istanbul', true], ['カナ', 'カナ', true], ['カナ', 'かな', true], ['λόγος', 'λόγοσ', true],+ ['عـلم', 'علم', true], ['क़', 'क', true],+ ];+ for (const [a, b, server] of MEASURED) {+ assert.strictEqual(dashboardNameKey(a) === dashboardNameKey(b), server, `${JSON.stringify(a)} vs ${JSON.stringify(b)}: the server says ${server ? 'equal' : 'distinct'}`);+ }+ // The one accepted over-fold: the server keeps a decomposed Hangul syllable distinct from its+ // precomposed form, which no keyboard produces for a dashboard name.+ assert.strictEqual(dashboardNameKey('한'), dashboardNameKey('\u1112\u1161\u11ab'));+ assert.notStrictEqual(dashboardNameKey('Sales Overview'), dashboardNameKey('SalesOverview'), 'inner space still counts');+ assert.strictEqual(dashboardNameKey(undefined), '');+});++// A column with no schemaName is reported by name. The sample-data gate resolves Choice values through+// the loader's helpers, which used to key every Choice/MultiChoice column by `schemaName.toLowerCase()`+// and threw a TypeError instead — taking validate, verify and even a teardown dry-run down with it.+test('validateAppSpec reports a Choice column with no schemaName instead of crashing on its sample data', () => {+ const s = cloneDesk();+ const e = s.entities[0];+ e.columns = [...(e.columns || []), { displayName: 'Tags', type: 'MultiChoice' }, { displayName: 'Tier', type: 'Choice', options: ['A', 'B'] }];+ s.sampleData = { [e.schemaName]: [{ [e.primaryAttribute.schemaName]: 'One' }] };+ let r;+ assert.doesNotThrow(() => { r = validateAppSpec(s); });+ assert.ok(r.errors.some((m) => /a column is missing schemaName/.test(m)), JSON.stringify(r.errors));+});+test('validateAppSpec accepts id-passthrough dashboard tiles (viewId/visualizationId + entity, no declared view/chart)', () => {const ok = cloneDesk();ok.views = []; ok.charts = []; // round-tripped spec declares no views/chartsdiff --git a/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js b/plugins/model-apps/scripts/tests/apply-snapshot-index.test.jsindex fa2e8512c..fc24f763a 100644--- a/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js+++ b/plugins/model-apps/scripts/tests/apply-snapshot-index.test.js@@ -28,7 +28,7 @@ function created() {entities: { new_x: 'ent-1' },views: { 'new_x|Active X': 'view-1' },forms: { new_x: 'form-1' }, // Main only, keyed by entity logical- charts: { 'By Status': 'chart-1' },+ charts: { 'new_x|By Status': 'chart-1' },commands: { new_x: 'cmd-1' },dashboards: { Ops: 'dash-1' },webResources: { wr_a: 'wr-1' },diff --git a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.jsindex 94490ca36..d555379c9 100644--- a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js+++ b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js@@ -59,15 +59,23 @@ test('acquireLease is exclusive: a live young holder blocks a second acquire; re} finally { rm(d); }});-test('acquireLease reclaims a STALE lease (token older than staleMs)', () => {+// A live holder may be paused mid-write (a machine asleep): reclaiming its lease by age let it resume and+// commit a stale view over the generation fence. So a lease that names a live holder is never reclaimed,+// however old — and an old one says which file to delete, since a crashed holder's pid may have been reused.+test('acquireLease never reclaims a live holder\u2019s lease, however old, and says how to clear an old one', () => {const d = ws();try {const a = store.acquireLease(d, { now: () => 1000, pid: 111, processAlive: () => true, staleMs: 10000 });assert.ok(a.ok);- // 20s later — older than the 10s stale window — a different build reclaims it.const b = store.acquireLease(d, { now: () => 21000, pid: 222, processAlive: () => true, staleMs: 10000 });- assert.ok(b.ok);- assert.strictEqual(b.reclaimed, true);+ assert.strictEqual(b.ok, false, 'older than the stale window, but its holder is alive');+ assert.match(b.reason, /held by pid 111/);+ assert.ok(b.reason.includes(`delete ${store.leasePath(d)} and re-run`), b.reason);+ assert.strictEqual(fs.readFileSync(store.leasePath(d), 'utf8'), a.token, 'the lock is untouched');+ const young = store.acquireLease(d, { now: () => 5000, pid: 222, processAlive: () => true, staleMs: 10000 });+ assert.ok(!young.ok && !/delete /.test(young.reason), 'a young one is simply held');+ const dead = store.acquireLease(d, { now: () => 21000, pid: 222, processAlive: () => false, staleMs: 10000 });+ assert.ok(dead.ok && dead.reclaimed, 'once its holder is dead, it is reclaimed');} finally { rm(d); }});@@ -85,7 +93,7 @@ test('releaseLease is owner-checked: a late release does NOT delete a lock anothconst d = ws();try {const a = store.acquireLease(d, { now: () => 1000, pid: 111, processAlive: () => true, staleMs: 10000 });- const b = store.acquireLease(d, { now: () => 21000, pid: 222, processAlive: () => true, staleMs: 10000 });+ const b = store.acquireLease(d, { now: () => 21000, pid: 222, processAlive: () => false, staleMs: 10000 });assert.ok(b.ok && b.reclaimed);store.releaseLease(a); // a's token no longer on disk — must be a no-opassert.ok(fs.existsSync(store.leasePath(d)), "the reclaimer's lock must survive the original holder's release");@@ -150,6 +158,795 @@ test('tombstoneSnapshot persists eligible:false + teardown debt (before any dele} finally { rm(d); }});+// #587 item 1: a tombstone must FENCE, not merely mark. A changed-only run that read the snapshot before+// the tombstone holds its generation; a tombstone that keeps that generation lets the run's later writes+// still match it — and measured before this fix, the run re-blessed its stale copy over the tombstone.+test('tombstoneSnapshot rotates the generation, so every write by a pre-tombstone reader is refused', () => {+ const d = ws();+ try {+ store.writeSnapshotAtomic(d, eligible('g1'));+ assert.ok(store.tombstoneSnapshot(d).ok);+ const disk = store.readSnapshot(d);+ assert.ok(disk.generation && disk.generation !== 'g1', `the tombstone must rotate the generation; got ${disk.generation}`);+ assert.strictEqual(store.invalidateSnapshot(d, { expectedGeneration: 'g1' }).ok, false);+ assert.strictEqual(store.casWriteSnapshot(d, eligible('g2'), 'g1').ok, false);+ assert.ok(S.isTombstoned(store.readSnapshot(d)), 'and the tombstone is intact');+ } finally { rm(d); }+});++test('invalidateSnapshot with an expected generation refuses a snapshot that changed or vanished since it was read', () => {+ const d = ws();+ try {+ store.writeSnapshotAtomic(d, eligible('g1'));+ const stale = store.invalidateSnapshot(d, { expectedGeneration: 'gOTHER' });+ assert.strictEqual(stale.ok, false);+ assert.match(stale.reason, /changed since/);+ assert.strictEqual(store.readSnapshot(d).eligible, true, 'a refused invalidate writes nothing');+ const good = store.invalidateSnapshot(d, { expectedGeneration: 'g1' });+ assert.ok(good.ok && good.generation && good.generation !== 'g1', JSON.stringify(good));+ store.deleteSnapshot(d);+ const gone = store.invalidateSnapshot(d, { expectedGeneration: good.generation });+ assert.strictEqual(gone.ok, false, 'a snapshot deleted since it was read is not "nothing to invalidate"');+ assert.match(gone.reason, /deleted/);+ assert.strictEqual(store.invalidateSnapshot(d).ok, true, 'without a fence, a missing snapshot is still already-safe');+ } finally { rm(d); }+});++// Its read and its write are two steps, so a tombstone written between them was overwritten. The+// lease is what serializes a tombstone against everything else, so the CAS write must take it too.+test('casWriteSnapshot takes the lease itself, so it cannot interleave with a tombstone', () => {+ const d = ws();+ try {+ store.writeSnapshotAtomic(d, eligible('g1'));+ const held = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ assert.ok(held.ok);+ const r = store.casWriteSnapshot(d, eligible('g2'), 'g1');+ assert.strictEqual(r.ok, false, 'a CAS write must not proceed while another writer holds the lease');+ assert.strictEqual(store.readSnapshot(d).generation, 'g1');+ store.releaseLease(held);+ assert.strictEqual(store.casWriteSnapshot(d, eligible('g2'), 'g1').ok, true);+ } finally { rm(d); }+});++// A workspace with NO snapshot is fenced too. A first changed-only build has none until it finishes, and+// answering "nothing to fence" there let that build write an eligible baseline for the app this teardown had+// just deleted. The fresh tombstone refuses the build's claim; the folder it had to create is reported so a+// clean teardown can remove it again.+test('tombstoneSnapshot with no snapshot writes a fresh tombstone that refuses a later claim, and reports the folder it created', () => {+ const parent = ws();+ try {+ const d = path.join(parent, 'a', '.maker-workspace');+ const r = store.tombstoneSnapshot(d);+ assert.ok(r.ok, JSON.stringify(r));+ assert.strictEqual(path.resolve(r.createdDir), path.resolve(parent, 'a'), 'the first folder mkdir created');+ const disk = store.readSnapshot(d);+ assert.ok(S.isTombstoned(disk) && disk.eligible === false && disk.generation, JSON.stringify(disk));+ assert.deepStrictEqual(fs.readdirSync(d), [store.SNAPSHOT_FILE], 'the lease is released');+ const claim = store.claimBaselineSnapshot(d, LIVE);+ assert.strictEqual(claim.ok, false, 'a build that has not claimed yet must not start under a teardown');+ assert.match(claim.reason, /appeared since/);+ // After a clean teardown the caller deletes the snapshot and removes what the tombstone created.+ store.deleteSnapshot(d);+ store.removeCreatedDir(d, r.createdDir);+ assert.deepStrictEqual(fs.readdirSync(parent), [], 'a folder that never had a workspace is left without one');+ } finally { rm(parent); }+});++test('tombstoneSnapshot in an existing folder reports no createdDir, and fences an unreadable snapshot too', () => {+ const d = ws();+ try {+ fs.writeFileSync(store.snapshotPath(d), '{ not json');+ const r = store.tombstoneSnapshot(d);+ assert.ok(r.ok, JSON.stringify(r));+ assert.strictEqual(r.createdDir, null);+ assert.ok(S.isTombstoned(store.readSnapshot(d)), 'the unreadable file is replaced by a tombstone');+ } finally { rm(d); }+});++test('tombstoneSnapshot where no folder can exist has nothing to fence, and writes nothing', () => {+ const parent = ws();+ try {+ const file = path.join(parent, 'afile');+ fs.writeFileSync(file, 'x');+ for (const d of [file, path.join(file, '.maker-workspace')]) {+ const r = store.tombstoneSnapshot(d);+ assert.ok(r.ok, JSON.stringify(r));+ assert.match(r.reason, /no workspace can exist/);+ }+ assert.deepStrictEqual(fs.readdirSync(parent), ['afile']);+ assert.strictEqual(fs.readFileSync(file, 'utf8'), 'x');+ } finally { rm(parent); }+});++// Those codes mean "no workspace" only when none is there: a platform that refuses mkdir over an EXISTING folder+// would otherwise leave that folder's snapshot unfenced while the teardown deletes the app.+test('tombstoneSnapshot fails closed when mkdir is refused over a workspace that exists', () => {+ const d = ws();+ try {+ store.writeSnapshotAtomic(d, eligible('g1'));+ for (const code of ['EACCES', 'EPERM', 'EROFS']) {+ const refuse = () => { throw Object.assign(new Error(`refused (${code})`), { code }); };+ const r = store.tombstoneSnapshot(d, { mkdirSync: refuse });+ assert.strictEqual(r.ok, false, code);+ assert.match(r.reason, /is there but could not be prepared/, code);+ }+ assert.strictEqual(store.readSnapshot(d).eligible, true, 'the snapshot is untouched, so the teardown stops before it deletes');+ } finally { rm(d); }+});++// A TRANSIENT mkdir failure is not proof that no build can use the folder, so the fence fails closed.+test('tombstoneSnapshot fails closed when the folder cannot be created for a transient reason', () => {+ const busy = () => { const e = new Error('resource busy or locked'); e.code = 'EBUSY'; throw e; };+ const r = store.tombstoneSnapshot(path.join(os.tmpdir(), 'never-created-ws'), { mkdirSync: busy });+ assert.strictEqual(r.ok, false);+ assert.match(r.reason, /tombstone failed: resource busy/);+});++test('removeCreatedDir leaves a folder that is no longer empty, everything above it, and an unrelated pair', () => {+ const parent = ws();+ try {+ const d = path.join(parent, 'a', 'b');+ const created = fs.mkdirSync(d, { recursive: true });+ fs.writeFileSync(path.join(d, 'build-owned.json'), '{}');+ store.removeCreatedDir(d, created);+ assert.ok(fs.existsSync(path.join(d, 'build-owned.json')), 'a concurrent build\'s file survives');+ fs.rmSync(path.join(d, 'build-owned.json'));+ store.removeCreatedDir(d, path.join(parent, 'unrelated'));+ store.removeCreatedDir(path.join(parent, 'a'), d);+ store.removeCreatedDir(d, null);+ assert.ok(fs.existsSync(d), 'nothing outside what was created is touched');+ store.removeCreatedDir(d, created);+ assert.deepStrictEqual(fs.readdirSync(parent), [], 'the created chain is removed deepest first');+ } finally { rm(parent); }+});++// The build-side half: a FIRST build claims a placeholder so it has a generation to be fenced by.+test('claimBaselineSnapshot writes an ineligible, debt-free placeholder whose generation the baseline CAS then needs', () => {+ const d = ws();+ try {+ const claim = store.claimBaselineSnapshot(d, LIVE);+ assert.ok(claim.ok && claim.generation, JSON.stringify(claim));+ const disk = store.readSnapshot(d);+ assert.strictEqual(disk.generation, claim.generation);+ assert.strictEqual(disk.eligible, false);+ assert.deepStrictEqual(disk.debt, [], 'no debt: a later baseline inherits its prior\'s debt');+ assert.strictEqual(disk.priorSpec, null);+ assert.deepStrictEqual([disk.orgId, disk.envUrl, disk.appUniqueName], [LIVE.orgId, LIVE.envUrl, LIVE.appUniqueName]);+ assert.strictEqual(store.claimBaselineSnapshot(d, LIVE).ok, false, 'a second claim is refused');+ assert.strictEqual(store.casWriteSnapshot(d, eligible('g2'), null).ok, false, 'an "expected none" write no longer matches');+ assert.ok(store.casWriteSnapshot(d, eligible('g2'), claim.generation).ok, 'the claimer\'s own baseline write succeeds');+ } finally { rm(d); }+});++test('a teardown after the claim tombstones the placeholder, so the claimer\'s baseline write is refused', () => {+ const d = ws();+ try {+ const claim = store.claimBaselineSnapshot(d, LIVE);+ assert.ok(claim.ok);+ assert.ok(store.tombstoneSnapshot(d).ok);+ assert.strictEqual(store.casWriteSnapshot(d, eligible('g2'), claim.generation).ok, false);+ assert.ok(S.isTombstoned(store.readSnapshot(d)), 'the tombstone survives');+ } finally { rm(d); }+});++test('claimBaselineSnapshot is refused while another writer holds the lease, and writes nothing', () => {+ const d = ws();+ try {+ const held = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ assert.ok(held.ok);+ const r = store.claimBaselineSnapshot(d, LIVE);+ store.releaseLease(held);+ assert.strictEqual(r.ok, false);+ assert.match(r.reason, /lease/);+ assert.strictEqual(store.readSnapshot(d), null);+ } finally { rm(d); }+});++// A claim that cannot be written must say so — the flow aborts on { ok:false } — rather than throw out of+// the build. A folder squatting on the snapshot path makes the atomic rename fail.+test('claimBaselineSnapshot reports a failed write instead of throwing, and releases the lease', () => {+ const d = ws();+ try {+ fs.mkdirSync(store.snapshotPath(d));+ const r = store.claimBaselineSnapshot(d, LIVE);+ assert.strictEqual(r.ok, false);+ assert.match(r.reason, /^claim failed: /);+ assert.strictEqual(fs.existsSync(store.leasePath(d)), false, 'the lease is released');+ } finally { rm(d); }+});++// A clean teardown releases its own entry; the tombstone goes only with the LAST entry of a teardown still+// alive — and then whatever the snapshot has become, so an eligible baseline is never left behind.+test('releaseTombstone keeps the fence for teardowns still running, and deletes whatever is there after the last', (t) => {+ const d = ws();+ try {+ const a = store.tombstoneSnapshot(d);+ const b = store.tombstoneSnapshot(d);+ assert.ok(a.teardownId && b.teardownId && a.teardownId !== b.teardownId);+ assert.deepStrictEqual(store.readSnapshot(d).teardowns.map((x) => x.id), [a.teardownId, b.teardownId]);+ const genBefore = store.readSnapshot(d).generation;+ const first = store.releaseTombstone(d, b.teardownId);+ assert.deepStrictEqual([first.ok, first.deleted, first.left], [true, false, true]);+ assert.match(first.reason, /1 other teardown\(s\) of this workspace are still running/);+ const kept = store.readSnapshot(d);+ assert.ok(S.isTombstoned(kept) && kept.eligible === false);+ assert.deepStrictEqual(kept.teardowns.map((x) => x.id), [a.teardownId]);+ assert.notStrictEqual(kept.generation, genBefore, 'the generation is rotated, fencing any build that read it');+ assert.strictEqual(store.claimBaselineSnapshot(d, LIVE).ok, false, 'no first build can claim meanwhile');+ // Whatever the snapshot has become — here an ELIGIBLE one that took the tombstone's place, still+ // listing a second teardown — a release re-fences it while any other teardown runs, and the last one+ // deletes it rather than leave it describing an app that is gone.+ const c = { id: 'td-c', pid: process.pid, at: Date.now() };+ const eligibleOverIt = eligible('g9');+ eligibleOverIt.teardowns = [...kept.teardowns, c];+ store.writeSnapshotAtomic(d, eligibleOverIt);+ assert.strictEqual(store.releaseTombstone(d, c.id).left, true);+ const refenced = store.readSnapshot(d);+ assert.ok(S.isTombstoned(refenced) && refenced.eligible === false, 'no eligible snapshot is left standing while a teardown runs');+ assert.deepStrictEqual(store.releaseTombstone(d, a.teardownId), { ok: true, deleted: true });+ assert.strictEqual(store.readSnapshot(d), null);+ assert.deepStrictEqual(store.releaseTombstone(d, a.teardownId), { ok: true, deleted: false, gone: true }, 'nothing left to release');+ } finally { rm(d); }+});++test('releaseTombstone drops entries whose teardown is gone, never recreates a removed folder, and reports a failed delete', (t) => {+ const d = ws();+ try {+ const dead = store.tombstoneSnapshot(d, { pid: 999991 });+ const mine = store.tombstoneSnapshot(d, { processAlive: () => true });+ assert.ok(store.readSnapshot(d).teardowns.some((x) => x.id === dead.teardownId), 'listed while its process counts as alive');+ // The other entry's process is dead, so this teardown is the last one alive.+ const rel = store.releaseTombstone(d, mine.teardownId, { processAlive: (pid) => pid !== 999991 });+ assert.deepStrictEqual(rel, { ok: true, deleted: true });+ // A day-old entry is dropped too, whatever its pid says (a pid can be reused).+ const old = store.tombstoneSnapshot(d, { now: () => Date.now() - store.TEARDOWN_STALE_MS - 1000 });+ const again = store.tombstoneSnapshot(d);+ assert.ok(!store.readSnapshot(d).teardowns.some((x) => x.id === old.teardownId), 'a day-old entry is pruned at the next tombstone');+ const realRm = fs.rmSync;+ const rmMock = t.mock.method(fs, 'rmSync', (p, o) => {+ if (String(p).endsWith(store.SNAPSHOT_FILE)) throw new Error('EBUSY: resource busy or locked');+ return realRm(p, o);+ });+ const failed = store.releaseTombstone(d, again.teardownId);+ rmMock.mock.restore();+ assert.deepStrictEqual([failed.ok, failed.deleted], [false, false]);+ assert.match(failed.reason, /^release failed: EBUSY/);+ const held = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ const blocked = store.releaseTombstone(d, again.teardownId, { sleep: () => {} });+ store.releaseLease(held);+ assert.deepStrictEqual([blocked.ok, blocked.deleted], [false, false]);+ assert.match(blocked.reason, /lease unavailable/);+ } finally { rm(d); }+ const parent = ws();+ try {+ const gone = path.join(parent, '.maker-workspace');+ assert.deepStrictEqual(store.releaseTombstone(gone, 'x'), { ok: true, deleted: false, gone: true });+ assert.strictEqual(fs.existsSync(gone), false, 'releasing into a removed workspace does not recreate it');+ } finally { rm(parent); }+});++// A teardown that failed or threw still drops its entry — it is no longer in flight — but never deletes:+// the tombstone stays, so a surviving artifact is never rebaselined.+test('releaseTombstone with keep drops the entry but keeps the tombstone, even as the last one', () => {+ const d = ws();+ try {+ const a = store.tombstoneSnapshot(d);+ const gen = store.readSnapshot(d).generation;+ assert.deepStrictEqual(store.releaseTombstone(d, a.teardownId, { keep: true }), { ok: true, deleted: false, kept: true, left: false });+ const kept = store.readSnapshot(d);+ assert.ok(S.isTombstoned(kept) && kept.eligible === false);+ assert.deepStrictEqual(kept.teardowns, []);+ assert.notStrictEqual(kept.generation, gen, 'the generation is rotated');+ const b = store.tombstoneSnapshot(d);+ const c = store.tombstoneSnapshot(d);+ assert.deepStrictEqual(store.releaseTombstone(d, b.teardownId, { keep: true }), { ok: true, deleted: false, kept: true, left: true });+ assert.deepStrictEqual(store.readSnapshot(d).teardowns.map((x) => x.id), [c.teardownId]);+ assert.deepStrictEqual(store.releaseTombstone(d, c.teardownId), { ok: true, deleted: true }, 'the last clean release still deletes it');+ // An unreadable snapshot becomes a fresh tombstone, never stays unreadable.+ fs.writeFileSync(store.snapshotPath(d), '{ not json');+ assert.strictEqual(store.releaseTombstone(d, 'td-x', { keep: true }).kept, true);+ assert.ok(S.isTombstoned(store.readSnapshot(d)));+ } finally { rm(d); }+});++// A lease held for a moment (a build persisting its snapshot) is waited out, a bounded number of times:+// giving up at once left a finished teardown's entry behind, reading as one still running.+test('releaseTombstone retries a briefly held lease, then gives up', () => {+ const d = ws();+ try {+ const hold = () => store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ const a = store.tombstoneSnapshot(d);+ const held = hold();+ let waits = 0;+ const r = store.releaseTombstone(d, a.teardownId, { sleep: () => { waits += 1; if (waits === 2) store.releaseLease(held); } });+ assert.deepStrictEqual(r, { ok: true, deleted: true });+ assert.strictEqual(waits, 2, 'it waited while the lease was held, then went ahead');+ const b = store.tombstoneSnapshot(d);+ const held2 = hold();+ let tries = 0;+ const gaveUp = store.releaseTombstone(d, b.teardownId, { sleep: () => { tries += 1; } });+ store.releaseLease(held2);+ assert.deepStrictEqual([gaveUp.ok, gaveUp.deleted], [false, false]);+ assert.match(gaveUp.reason, /lease unavailable/);+ assert.strictEqual(tries, store.RELEASE_ATTEMPTS - 1, 'a bounded number of waits');+ } finally { rm(d); }+});++// Two writers finding the same stale lock both overwrote it, and each could read its own token back before+// the other's write landed — two holders. Only the writer that creates the claim file may reclaim, and only+// while the lock still holds exactly what it judged stale.+test('a stale lock is reclaimed by one writer only, and never once it has changed', (t) => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ const claim = `${lp}.reclaim`;+ const stale = JSON.stringify({ pid: 7, at: 0 });+ const reclaim = () => store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => false, staleMs: store.LEASE_STALE_MS });+ // Another writer is reclaiming right now: this one fails closed and leaves the lock alone.+ fs.writeFileSync(lp, stale);+ fs.writeFileSync(claim, 'another writer');+ const busy = reclaim();+ assert.deepStrictEqual([busy.ok, busy.reason], [false, 'lease being reclaimed by another writer']);+ assert.strictEqual(fs.readFileSync(lp, 'utf8'), stale);+ assert.ok(fs.existsSync(claim), 'a young claim is not removed');+ // A claim older than the staleness window was abandoned — yet no writer but its creator removes it: removing+ // it was a read and then a delete, and a second reclaimer's live claim could be the one deleted, so both held+ // the lease. Every attempt fails closed and names the file to delete, and the claim and lock stay as they are.+ const old = new Date(Date.now() - store.LEASE_STALE_MS - 60000);+ fs.utimesSync(claim, old, old);+ for (const attempt of [reclaim(), reclaim()]) {+ assert.strictEqual(attempt.ok, false);+ assert.match(attempt.reason, /the reclaim was abandoned \(its claim is older than the staleness window\); if no build or teardown of this workspace is running, delete .*\.reclaim and re-run/);+ }+ assert.strictEqual(fs.readFileSync(claim, 'utf8'), 'another writer', 'the abandoned claim is left for the operator');+ assert.strictEqual(fs.readFileSync(lp, 'utf8'), stale, 'and so is the lock');+ // …and one whose claimer's pid is gone, likewise.+ fs.writeFileSync(claim, JSON.stringify({ pid: 424242, at: Date.now(), rnd: 'x' }));+ const dead = reclaim();+ assert.strictEqual(dead.ok, false);+ assert.match(dead.reason, /its claimer, pid 424242, is gone/);+ assert.ok(fs.existsSync(claim));+ // Once the operator deletes it, the next attempt reclaims.+ fs.rmSync(claim);+ const won = reclaim();+ assert.deepStrictEqual([won.ok, won.reclaimed], [true, true]);+ assert.ok(!fs.existsSync(claim), 'and a reclaim leaves no claim behind');+ store.releaseLease(won);+ // The lock changed between the judgment and the claim — another writer reclaimed it meanwhile, say: it+ // is not overwritten.+ fs.writeFileSync(lp, stale);+ const realRead = fs.readFileSync;+ let reads = 0;+ const readMock = t.mock.method(fs, 'readFileSync', (p, ...rest) => {+ if (p === lp && ++reads === 2) return JSON.stringify({ pid: 9, at: Date.now() });+ return realRead(p, ...rest);+ });+ const changed = reclaim();+ readMock.mock.restore();+ assert.deepStrictEqual([changed.ok, changed.reason], [false, 'lease changed while it was being reclaimed']);+ assert.strictEqual(fs.readFileSync(lp, 'utf8'), stale, 'the lock is not overwritten');+ assert.ok(!fs.existsSync(claim));+ } finally { rm(d); }+});++// --clear-workspace used to remove the folder in place, after the release: a second teardown's tombstone written+// in between went with it, and a changed-only build could then bless a baseline while that teardown was still+// deleting. The clear holds the lease, refuses a snapshot written since, and moves the folder aside in one step.+test('clearWorkspace removes the folder under its lease, never a snapshot written since, and never in place', () => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-clear-'));+ try {+ const d = path.join(base, '.maker-workspace');+ fs.mkdirSync(d);+ fs.writeFileSync(path.join(d, 'manifest.json'), '{}');+ // A second teardown's tombstone, written after this teardown's release: refused, and kept.+ assert.ok(store.tombstoneSnapshot(d).ok);+ const kept = store.clearWorkspace(d);+ assert.strictEqual(kept.ok, false);+ assert.match(kept.reason, /a changed-only snapshot was written to it after this teardown finished/);+ assert.ok(store.readSnapshot(d), 'the fence is still there');+ fs.rmSync(store.snapshotPath(d));+ // A lease another live writer holds: refused, and nothing removed.+ fs.writeFileSync(store.leasePath(d), JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'other' }));+ const busy = store.clearWorkspace(d);+ assert.strictEqual(busy.ok, false);+ assert.match(busy.reason, /the workspace is in use/);+ assert.ok(fs.existsSync(path.join(d, 'manifest.json')));+ fs.rmSync(store.leasePath(d));+ // While the clear holds the lease, a teardown arriving cannot fence the folder: it is refused, never lost.+ let during = null;+ const cleared = store.clearWorkspace(d, { beforeRename: () => { during = store.tombstoneSnapshot(d, { attempts: 1, sleep: () => {} }); } });+ assert.ok(during && during.ok === false, `a teardown arriving mid-clear is refused: ${JSON.stringify(during)}`);+ assert.ok(cleared.ok, JSON.stringify(cleared));+ assert.ok(!fs.existsSync(d), 'the folder is gone');+ assert.deepStrictEqual(fs.readdirSync(base), [], 'and nothing is left beside it');+ // The path is free for whoever comes next.+ assert.ok(store.tombstoneSnapshot(d).ok);+ } finally { rm(base); }+});++// A reclaimer's claim that moved with the folder was later deleted by that reclaimer by PATH — in a folder recreated+// there, another writer's live claim. The clear reserves the claim itself: a reclaim in progress refuses it.+test('clearWorkspace refuses while a reclaim of the lease is in progress, and leaves no claim behind', () => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-clear-claim-'));+ try {+ const d = path.join(base, '.maker-workspace');+ fs.mkdirSync(d);+ const claim = `${store.leasePath(d)}.reclaim`;+ fs.writeFileSync(claim, JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'reclaimer' }));+ const busy = store.clearWorkspace(d);+ assert.strictEqual(busy.ok, false);+ assert.match(busy.reason, /a reclaim of its lease is in progress — if no build or teardown of this workspace is running, delete .*\.reclaim and re-run/);+ assert.ok(fs.existsSync(d), 'nothing moved');+ assert.strictEqual(JSON.parse(fs.readFileSync(claim, 'utf8')).rnd, 'reclaimer', 'the reclaimer\u2019s claim is untouched');+ assert.ok(!fs.existsSync(store.leasePath(d)), 'and the clear released its lease');+ fs.rmSync(claim);+ // While the clear holds the claim, a reclaimer finds it taken by a live writer.+ let during = null;+ const cleared = store.clearWorkspace(d, { beforeRename: () => { during = fs.existsSync(claim); } });+ assert.ok(cleared.ok, JSON.stringify(cleared));+ assert.strictEqual(during, true, 'the claim is reserved while the folder moves');+ assert.ok(!fs.existsSync(d));+ } finally { rm(base); }+});++// writeFileSync with 'wx' creates the file BEFORE it writes: a write that failed (ENOSPC) left an empty claim, which+// only its creator may remove — so every later clear refused. The claim is created, then written, and removed again+// when the write fails.+test('a reservation whose write fails leaves no claim behind, and the next clear succeeds', (t) => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-clear-enospc-'));+ try {+ const d = path.join(base, '.maker-workspace');+ fs.mkdirSync(d);+ const claim = `${store.leasePath(d)}.reclaim`;+ const realWrite = fs.writeFileSync;+ // The lease is written by path, the claim through its exclusively opened descriptor: fail the claim's write.+ const mock = t.mock.method(fs, 'writeFileSync', (target, ...rest) => {+ if (typeof target === 'number') throw Object.assign(new Error('no space'), { code: 'ENOSPC' });+ return realWrite(target, ...rest);+ });+ const failed = store.clearWorkspace(d);+ mock.mock.restore();+ assert.strictEqual(failed.ok, false, JSON.stringify(failed));+ assert.match(failed.reason, /its lease could not be reserved \(ENOSPC\)/);+ assert.ok(!fs.existsSync(claim), 'the empty claim is removed again');+ assert.ok(!fs.existsSync(store.leasePath(d)), 'and the lease released');+ assert.ok(store.clearWorkspace(d).ok, 'so the next clear is not blocked');+ } finally { rm(base); }+});++// The LOCK is not rolled back when its write fails: an empty lock ages into a reclaimable one, and deleting it after+// another writer had reclaimed it let a third take the path fresh — two holders.+test('a lock whose write fails is left in place for the tokenless-lock rule, never deleted', (t) => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ const realWrite = fs.writeFileSync;+ const mock = t.mock.method(fs, 'writeFileSync', (target, data, o) => {+ if (target === lp && o && o.flag === 'wx') { fs.closeSync(fs.openSync(lp, 'wx')); throw Object.assign(new Error('no space'), { code: 'ENOSPC' }); }+ return realWrite(target, data, o);+ });+ const r = store.acquireLease(d);+ mock.mock.restore();+ assert.strictEqual(r.ok, false);+ assert.match(r.reason, /lease create failed/);+ assert.ok(fs.existsSync(lp), 'the empty lock stays');+ assert.strictEqual(fs.readFileSync(lp, 'utf8'), '');+ } finally { rm(d); }+});++// One writeSync may write only part of its text (a full disk, a signal): a claim cut short that way read as having+// no token, so another writer judged its claimer by age instead of by pid. The whole text lands however the OS+// splits the write.+test('createExclusive writes the whole text even when the OS takes it one byte at a time', (t) => {+ const d = ws();+ try {+ const text = JSON.stringify({ pid: 4242, at: 1, rnd: 'abcdef' });+ // A Buffer goes through writeFileSync's own loop over fs.writeSync, which the mock splits. A string does not:+ // newer Node writes a UTF-8 string natively, whole, without calling fs.writeSync — checked separately below.+ const bytes = Buffer.from(text, 'utf8');+ const split = path.join(d, 'split');+ const realWriteSync = fs.writeSync;+ let calls = 0;+ t.mock.method(fs, 'writeSync', (fd, data, ...rest) => {+ calls += 1;+ const buf = typeof data === 'string' ? Buffer.from(data, 'utf8') : data;+ const offset = typeof data === 'string' ? 0 : (rest[0] || 0);+ return realWriteSync(fd, buf, offset, 1);+ });+ store.createExclusive(split, bytes);+ const writes = calls;+ t.mock.restoreAll();+ assert.strictEqual(writes, bytes.length, 'each byte went through its own write');+ assert.strictEqual(fs.readFileSync(split, 'utf8'), text);+ // The string every caller passes is written whole too, and a second create is still refused.+ const file = path.join(d, 'claim');+ store.createExclusive(file, text);+ assert.strictEqual(fs.readFileSync(file, 'utf8'), text);+ assert.throws(() => store.createExclusive(file, 'other'), { code: 'EEXIST' });+ assert.strictEqual(fs.readFileSync(file, 'utf8'), text);+ } finally { rm(d); }+});++// The final close is part of the write. A close that reported an error (EIO) threw past the rollback and left the+// claim behind: only its creator removes a claim, so every later clear or reclaim then refused. A descriptor whose+// close failed is not closed again — the number may belong to another file by then.+test('createExclusive removes its file when the final close reports an error, and closes only once', (t) => {+ const d = ws();+ try {+ const file = path.join(d, 'claim');+ const realClose = fs.closeSync;+ let closes = 0;+ t.mock.method(fs, 'closeSync', (fd) => { closes += 1; realClose(fd); throw Object.assign(new Error('i/o error'), { code: 'EIO' }); });+ assert.throws(() => store.createExclusive(file, 'token'), { code: 'EIO' });+ t.mock.restoreAll();+ assert.strictEqual(closes, 1, 'a close that failed is not repeated');+ assert.strictEqual(fs.existsSync(file), false, 'the file it created is removed');+ } finally { rm(d); }+});++// Fails only the CLAIM's close: writeFileSync by path opens and closes through fs on some Node versions, and the+// lease must not fail with it.+function failClaimClose(t, claim) {+ const realOpen = fs.openSync;+ const realClose = fs.closeSync;+ let claimFd = null;+ t.mock.method(fs, 'openSync', (target, ...rest) => {+ const fd = realOpen(target, ...rest);+ if (target === claim) claimFd = fd;+ return fd;+ });+ t.mock.method(fs, 'closeSync', (fd) => {+ realClose(fd);+ if (fd === claimFd) { claimFd = null; throw Object.assign(new Error('i/o error'), { code: 'EIO' }); }+ });+}++test('a reservation whose close fails leaves no claim behind, and the next clear succeeds', (t) => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-clear-eio-'));+ try {+ const d = path.join(base, '.maker-workspace');+ fs.mkdirSync(d);+ const claim = `${store.leasePath(d)}.reclaim`;+ failClaimClose(t, claim);+ const failed = store.clearWorkspace(d);+ t.mock.restoreAll();+ assert.strictEqual(failed.ok, false, JSON.stringify(failed));+ assert.match(failed.reason, /its lease could not be reserved \(EIO\)/);+ assert.ok(!fs.existsSync(claim), 'the claim is removed again');+ assert.ok(!fs.existsSync(store.leasePath(d)), 'and the lease released');+ assert.ok(store.clearWorkspace(d).ok, 'so the next clear is not blocked');+ } finally { rm(base); }+});++test('a stale-lease reclaim whose claim close fails leaves no claim behind, and the next reclaim succeeds', (t) => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ fs.writeFileSync(lp, JSON.stringify({ pid: 999999, at: 1, rnd: 'dead' }));+ const dead = { processAlive: () => false };+ failClaimClose(t, `${lp}.reclaim`);+ const failed = store.acquireLease(d, dead);+ t.mock.restoreAll();+ assert.strictEqual(failed.ok, false, JSON.stringify(failed));+ assert.match(failed.reason, /stale lease reclaim failed/);+ assert.ok(!fs.existsSync(`${lp}.reclaim`), 'the claim is removed again');+ const again = store.acquireLease(d, dead);+ assert.strictEqual(again.ok, true, JSON.stringify(again));+ assert.strictEqual(again.reclaimed, true);+ store.releaseLease(again);+ } finally { rm(d); }+});++// A folder renamed away between mkdir's own steps surfaced as ENOENT from a folder that had existed, and read as+// "no workspace can exist here": the teardown then ran with no fence. An ENOENT is retried.+test('tombstoneSnapshot retries a mkdir that fails with ENOENT, and fences the folder it then makes', () => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-tomb-enoent-'));+ try {+ const d = path.join(base, '.maker-workspace');+ let calls = 0;+ const flaky = (p, o) => { calls += 1; if (calls === 1) throw Object.assign(new Error('gone mid-mkdir'), { code: 'ENOENT' }); return fs.mkdirSync(p, o); };+ const tomb = store.tombstoneSnapshot(d, { mkdirSync: flaky });+ assert.ok(tomb.ok && tomb.teardownId, JSON.stringify(tomb));+ assert.strictEqual(calls, 2);+ assert.ok(store.readSnapshot(d), 'the fence is written');+ // A folder that keeps vanishing is no proof that none can exist: running out of retries fails closed, never an+ // unfenced teardown.+ let tries = 0;+ const never = () => { tries += 1; throw Object.assign(new Error('gone again'), { code: 'ENOENT' }); };+ const none = store.tombstoneSnapshot(path.join(base, 'nowhere', '.maker-workspace'), { mkdirSync: never });+ assert.strictEqual(none.ok, false, JSON.stringify(none));+ assert.match(none.reason, /kept vanishing while it was being prepared \(ENOENT\)/);+ assert.ok(tries > 1, 'retried before concluding');+ } finally { rm(base); }+});++// The folder is moved aside BEFORE anything is deleted, so a delete that fails leaves the path free, not a half-+// deleted workspace — and names what is left, instead of a stack trace.+test('clearWorkspace moves the folder aside first, and names what a failed delete leaves', (t) => {+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'snap-clear-busy-'));+ try {+ const d = path.join(base, '.maker-workspace');+ fs.mkdirSync(d);+ fs.writeFileSync(path.join(d, 'manifest.json'), '{}');+ const realRm = fs.rmSync;+ const rmMock = t.mock.method(fs, 'rmSync', (p, ...rest) => {+ if (String(p).includes('.cleared-')) throw Object.assign(new Error('busy'), { code: 'EBUSY' });+ return realRm(p, ...rest);+ });+ const r = store.clearWorkspace(d);+ rmMock.mock.restore();+ assert.ok(r.ok, JSON.stringify(r));+ assert.ok(!fs.existsSync(d), 'the workspace path is free');+ assert.match(r.reason, /its contents were moved to .*\.cleared-.*, which could not be deleted \(EBUSY\); delete it by hand/);+ assert.ok(fs.existsSync(r.leftover), 'the moved folder is where the reason says');+ } finally { rm(base); }+});++// A running teardown refreshes its entry, and an entry counts only while it keeps being seen: a KILLED+// teardown never drops its entry, and under a reused (live) pid that entry kept every changed-only build+// refused — and every later clean teardown "left" — for a day.+test('beatTeardown keeps an entry counted, and an entry no longer seen stops counting even under a live pid', (t) => {+ const d = ws();+ try {+ const old = Date.now() - store.TEARDOWN_STALE_MS - 1000;+ const killed = store.tombstoneSnapshot(d, { now: () => old, pid: process.pid });+ assert.deepStrictEqual(store.teardownsInFlight(store.readSnapshot(d)), [], 'not seen for longer than the window: not running, though its pid is alive');+ const gen = store.readSnapshot(d).generation;+ assert.deepStrictEqual(store.beatTeardown(d, killed.teardownId), { ok: true });+ const beaten = store.readSnapshot(d);+ assert.deepStrictEqual(store.teardownsInFlight(beaten).map((x) => x.id), [killed.teardownId], 'a fresh beat counts again');+ assert.strictEqual(beaten.generation, gen, 'a beat rotates no fence');+ // Quiet, one-attempt skips: an unknown entry, a held lease, no snapshot.+ assert.deepStrictEqual(store.beatTeardown(d, 'td-unknown'), { ok: false, reason: 'no entry for this teardown' });+ const held = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ const blocked = store.beatTeardown(d, killed.teardownId);+ store.releaseLease(held);+ assert.equal(blocked.ok, false);+ assert.match(blocked.reason, /^lease held by pid/);+ fs.rmSync(store.snapshotPath(d));+ assert.deepStrictEqual(store.beatTeardown(d, killed.teardownId), { ok: false, reason: 'no snapshot' });+ } finally { rm(d); }+});++// A lock released between our exclusive create and our look at it is free — but free for everyone, so it is+// re-taken exclusively. Overwriting it let a writer that created it meanwhile hold the lease as well.+test('acquireLease re-takes a lock that vanished meanwhile exclusively, never by overwriting it', (t) => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ const realRead = fs.readFileSync;+ for (const [what, onRead, want] of [+ ['released, nobody else took it', () => fs.rmSync(lp, { force: true }), (r) => r.ok && !r.reclaimed],+ ['released and re-taken by another writer', () => {}, (r) => r.ok === false && /taken by another writer just now/.test(r.reason)],+ ]) {+ fs.writeFileSync(lp, JSON.stringify({ pid: 7, at: Date.now() }));+ let once = true;+ const readMock = t.mock.method(fs, 'readFileSync', (p, ...rest) => {+ if (once && p === lp) { once = false; onRead(); throw Object.assign(new Error('ENOENT: no such file'), { code: 'ENOENT' }); }+ return realRead(p, ...rest);+ });+ const r = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ readMock.mock.restore();+ assert.ok(want(r), `${what}: ${JSON.stringify(r)}`);+ if (r.ok) store.releaseLease(r);+ fs.rmSync(lp, { force: true });+ }+ // A token that cannot be read whole, in a file that cannot be looked at either, is left held+ // (fail-closed): only a lock proven gone is re-taken.+ fs.writeFileSync(lp, '');+ const realStat = fs.statSync;+ const statMock = t.mock.method(fs, 'statSync', (p, ...rest) => {+ if (p === lp) throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });+ return realStat(p, ...rest);+ });+ const unknown = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS });+ statMock.mock.restore();+ assert.strictEqual(unknown.ok, false);+ assert.match(unknown.reason, /^lease held/);+ fs.rmSync(lp, { force: true });+ // A stale lock reclaimed by overwrite is held only if OUR token is still there when read back.+ fs.writeFileSync(lp, JSON.stringify({ pid: 7, at: 0 }));+ const realWrite = fs.writeFileSync;+ const writeMock = t.mock.method(fs, 'writeFileSync', (p, data, o) => {+ realWrite(p, data, o);+ if (p === lp && !o) realWrite(p, JSON.stringify({ pid: 8, at: Date.now() })); // another reclaimer's write lands after ours+ });+ const lost = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => false, staleMs: store.LEASE_STALE_MS });+ writeMock.mock.restore();+ assert.strictEqual(lost.ok, false);+ assert.match(lost.reason, /reclaimed by another writer just now/);+ } finally { rm(d); }+});++// The reclaim CLAIM follows the lock's own rule: a claimer that is alive keeps it however old it is — one+// paused mid-reclaim lost it to age, a second writer reclaimed, and both held the lease — and a dead+// claimer's is abandoned. An abandoned claim is left for the operator, never removed by another writer: that+// removal was a read and then a delete, and it could take a second reclaimer's live claim.+test('a reclaim claim is abandoned only when its claimer is dead, and then left for the operator', () => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ const claim = `${lp}.reclaim`;+ fs.writeFileSync(lp, JSON.stringify({ pid: 7, at: 0 }));+ fs.writeFileSync(claim, JSON.stringify({ pid: 4242, at: 0 }));+ const old = new Date(Date.now() - store.LEASE_STALE_MS - 60000);+ fs.utimesSync(claim, old, old);+ const attempt = (alive) => store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: (p) => alive.includes(p), staleMs: store.LEASE_STALE_MS });+ const busy = attempt([4242]);+ assert.strictEqual(busy.ok, false);+ assert.match(busy.reason, /^lease being reclaimed by another writer/);+ assert.ok(busy.reason.includes(`delete ${claim} and re-run`), `an old one says which file to delete: ${busy.reason}`);+ assert.ok(fs.existsSync(claim), 'a live claimer keeps its claim, however old');+ const gone = attempt([]);+ assert.strictEqual(gone.ok, false);+ assert.match(gone.reason, /the reclaim was abandoned \(its claimer, pid 4242, is gone\)/);+ assert.ok(gone.reason.includes(`delete ${claim} and re-run`), gone.reason);+ assert.ok(fs.existsSync(claim), 'a dead claimer\u2019s claim is left for the operator');+ fs.rmSync(claim);+ const won = attempt([]);+ assert.deepStrictEqual([won.ok, won.reclaimed], [true, true]);+ store.releaseLease(won);+ } finally { rm(d); }+});++// A reclaim whose write landed but whose read-back failed used to leave the lock holding this process's+// token: nobody else reclaims it (the pid is alive), so the process then blocked itself. It is released.+test('a reclaim that fails after its write leaves no lock holding its own token', (t) => {+ const d = ws();+ try {+ const lp = store.leasePath(d);+ fs.writeFileSync(lp, JSON.stringify({ pid: 7, at: 0 }));+ const realRead = fs.readFileSync;+ let reads = 0;+ const readMock = t.mock.method(fs, 'readFileSync', (p, ...rest) => {+ if (p === lp && ++reads === 3) throw Object.assign(new Error('resource busy'), { code: 'EBUSY' });+ return realRead(p, ...rest);+ });+ const r = store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => false, staleMs: store.LEASE_STALE_MS });+ readMock.mock.restore();+ assert.deepStrictEqual([r.ok, /stale lease reclaim failed: resource busy/.test(r.reason)], [false, true]);+ assert.ok(!fs.existsSync(lp), 'the lock it wrote is released');+ assert.ok(store.acquireLease(d, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: store.LEASE_STALE_MS }).ok, 'and the next acquire succeeds');+ } finally { rm(d); }+});++// Node 22 on Windows returns the folder a recursive mkdirSync created in its NAMESPACED form (`\\?\C:\…`),+// and the teardown then never recognised the folder it had made, and left it behind. The same return is+// simulated here, so every Node version runs the case CI hit.+test('the folder tombstoneSnapshot created is reported, and removed, in its plain form', () => {+ const base = ws();+ try {+ const d = path.join(base, 'a', 'ws');+ const r = store.tombstoneSnapshot(d, { mkdirSync: (p, o) => { const first = fs.mkdirSync(p, o); return first && (first.startsWith('\\\\?\\') ? first : `\\\\?\\${first}`); } });+ assert.ok(r.ok, r.reason);+ assert.strictEqual(r.createdDir, path.join(base, 'a'), 'the namespace prefix is dropped');+ store.deleteSnapshot(d);+ store.removeCreatedDir(d, `\\\\?\\${r.createdDir}`);+ assert.deepStrictEqual(fs.readdirSync(base), [], 'and the folders it created are removed, a namespaced one too');+ for (const [p, plain] of [['\\\\?\\C:\\x', 'C:\\x'], ['\\\\?\\UNC\\srv\\share\\x', '\\\\srv\\share\\x'], ['C:\\x', 'C:\\x'], ['/tmp/x', '/tmp/x']]) {+ assert.strictEqual(store.plainPath(p), plain, p);+ }+ } finally { rm(base); }+});++// The 'wx' create makes the lock BEFORE it writes the token, so a reader can find it empty. Presuming such+// a lock abandoned let two writers hold the lease at once; an unreadable token is aged by its FILE instead.+test('acquireLease treats an unreadable token as held until the lock file itself is stale', () => {+ const d = ws();+ try {+ const deps = { now: () => Date.now(), pid: 2, processAlive: () => false, staleMs: store.LEASE_STALE_MS };+ for (const body of ['', '{"pid":7}']) {+ fs.writeFileSync(store.leasePath(d), body);+ const young = store.acquireLease(d, deps);+ assert.strictEqual(young.ok, false, `a young lock holding ${JSON.stringify(body)} is not abandoned`);+ }+ const old = (Date.now() - store.LEASE_STALE_MS - 60000) / 1000;+ fs.utimesSync(store.leasePath(d), old, old);+ const stale = store.acquireLease(d, deps);+ assert.ok(stale.ok && stale.reclaimed, 'an unreadable lock that old is');+ } finally { rm(d); }+});+test('deleteSnapshot removes the file; deleting a missing file is success', () => {const d = ws();try {@@ -179,3 +976,81 @@ test('invalidate BUMPS the generation (fencing) and returns it; eligible stays fassert.strictEqual(store.casWriteSnapshot(d, eligible('g2'), inv.generation).ok, true);} finally { rm(d); }});++// Each refusal is its own marker file, and a run clears only the markers it found when it started: one written since is+// another run's, and stays, whatever is cleared around it.+test('clearDistrust deletes only the markers it was given, and markers written since stay', () => {+ const d = ws();+ try {+ assert.strictEqual(store.readDistrust(d), null, 'none yet');+ assert.strictEqual(store.markDistrusted(d, { reason: 'first' }).ok, true);+ const a = store.readDistrust(d);+ assert.deepStrictEqual([a.names.length, a.reason], [1, 'first']);+ assert.strictEqual(store.markDistrusted(d, { reason: 'second' }).ok, true);+ const b = store.readDistrust(d);+ assert.strictEqual(b.names.length, 2, 'every refusal is its own marker');+ assert.strictEqual(store.markDistrusted(d, { reason: 'third' }).ok, true);+ assert.strictEqual(store.clearDistrust(d, a.names).ok, true);+ assert.strictEqual(store.readDistrust(d).names.length, 2, 'the markers written since stay');+ // A run that found the first two clears those; the third, written after it looked, stays.+ assert.strictEqual(store.clearDistrust(d, b.names).ok, true);+ const last = store.readDistrust(d);+ assert.deepStrictEqual([last.names.length, last.reason], [1, 'third']);+ assert.strictEqual(store.clearDistrust(d, last.names).ok, true);+ assert.strictEqual(store.readDistrust(d), null);+ assert.deepStrictEqual(fs.readdirSync(d), [], 'and nothing is left behind');+ } finally { rm(d); }+});++// A concurrent reader never sees the workspace without a marker while another run's marker exists: a clear deletes its+// own markers by name, and moves nothing.+test('while a run clears its markers, a marker another run wrote stays visible throughout', (t) => {+ const d = ws();+ try {+ store.markDistrusted(d, { reason: 'mine' });+ const mine = store.readDistrust(d).names;+ store.markDistrusted(d, { reason: 'theirs' });+ const theirs = store.readDistrust(d).names.filter((n) => !mine.includes(n));+ const realRm = fs.rmSync;+ const seen = [];+ t.mock.method(fs, 'rmSync', (p, o) => { seen.push(store.readDistrust(d)); const r = realRm(p, o); seen.push(store.readDistrust(d)); return r; });+ store.clearDistrust(d, mine);+ t.mock.restoreAll();+ assert.ok(seen.length >= 2, 'the clear deleted something');+ for (const s of seen) assert.ok(s && theirs.every((n) => s.names.includes(n)), 'the other marker is never out of sight');+ assert.deepStrictEqual(store.readDistrust(d).names, theirs);+ } finally { t.mock.restoreAll(); rm(d); }+});++// A marker nobody can read has not said the workspace is trusted again, so it counts; a half-written one is no marker+// yet; either is deleted by its name.+test('readDistrust counts an unreadable marker, ignores a temp one, and clearDistrust deletes it by name', () => {+ const d = ws();+ try {+ fs.writeFileSync(path.join(d, `${store.DISTRUST_PREFIX}half${store.DISTRUST_SUFFIX}.tmp`), '{"reason":"half-written"}');+ assert.strictEqual(store.readDistrust(d), null, 'a temp file is no marker');+ fs.writeFileSync(path.join(d, `${store.DISTRUST_PREFIX}corrupt${store.DISTRUST_SUFFIX}`), 'not json');+ const seen = store.readDistrust(d);+ assert.ok(seen, 'it counts');+ assert.strictEqual(seen.reason, 'no readable reason recorded');+ assert.strictEqual(store.clearDistrust(d, seen.names).ok, true);+ assert.strictEqual(store.readDistrust(d), null);+ } finally { rm(d); }+});++// The last clean teardown deletes the marker with the snapshot, since the app it distrusted is gone; a teardown that+// keeps its tombstone keeps the marker too.+test('releaseTombstone deletes the distrust marker with the snapshot, and keeps it with a kept tombstone', () => {+ for (const [what, keep] of [['a clean last release', false], ['a kept release', true]]) {+ const d = ws();+ try {+ store.writeSnapshotAtomic(d, eligible('g1'));+ assert.strictEqual(store.markDistrusted(d, { reason: 'x' }).ok, true);+ const tomb = store.tombstoneSnapshot(d);+ assert.ok(tomb.ok, what);+ const rel = store.releaseTombstone(d, tomb.teardownId, keep ? { keep: true } : {});+ assert.strictEqual(rel.ok, true, what);+ assert.strictEqual(store.readDistrust(d) === null, !keep, what);+ } finally { rm(d); }+ }+});diff --git a/plugins/model-apps/scripts/tests/apply-snapshot.test.js b/plugins/model-apps/scripts/tests/apply-snapshot.test.jsindex 825963164..6f5314ff6 100644--- a/plugins/model-apps/scripts/tests/apply-snapshot.test.js+++ b/plugins/model-apps/scripts/tests/apply-snapshot.test.js@@ -96,6 +96,16 @@ test('tombstone: eligible->false + teardown debt, and the gate refuses even a prassert.match(gate.reason, /tombstone/);});+// A teardown that found no snapshot writes a fresh tombstone with no identity (it never asks WhoAmI). An+// identity-first gate reported that as another org — fail-closed, but pointing at the wrong problem.+test('a tombstone with no identity is reported as tombstoned, not as a different org', () => {+ const env = S.makeEnvelope({});+ S.tombstone(env);+ const gate = S.isFastPathEligible(env, LIVE);+ assert.strictEqual(gate.eligible, false);+ assert.match(gate.reason, /tombstone/);+});+test('markIneligible forces eligible:false (the invalidate-before-write step), idempotently', () => {const env = eligibleEnvelope();S.markIneligible(env);diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex dc365d395..36ecbf50f 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -284,6 +284,10 @@ test('isTransientHalt classifies lock/timeout/429/503 as transient, others not',assert.ok(!isTransientHalt({ recoverable: true }));assert.ok(!isTransientHalt({ message: 'validation failed', cause: { statusCode: 400 } }));assert.ok(!isTransientHalt(null));+ // An error that declares itself non-transient is never retried, whatever status or text it quotes: a+ // dashboard left outside the app's solution would be silently reused by the retry.+ assert.ok(!isTransientHalt({ message: 'x', cause: { transient: false, statusCode: 429, message: 'CustomizationLockException … try again later' } }));+ assert.ok(!isTransientHalt({ transient: false, cause: { statusCode: 503 } }));});test('transient auto-retry: a transient halt is retried and then succeeds', async () => {@@ -621,6 +625,19 @@ test('makeSdk\u2019s return shape and main\u2019s destructure stay in agreement''main destructures keys makeSdk does not return (or ignores ones it does)');});+// The build's verify read each dashboard through an isolated reader made with no client, so it created one of its+// own — and a second Azure CLI token acquisition — beside the build's. makeSdk builds the reader around its own+// client, and the verify wiring uses that reader.+test('the build verifies dashboards through makeSdk\u2019s isolated reader, sharing the build\u2019s client', () => {+ const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');+ const body = src.slice(src.indexOf('async function makeSdk'), src.indexOf('return { sdk, provisionSdk'));+ assert.match(body, /const httpClient = createAzHttpClient\(env\);/);+ assert.match(body, /isolatedReaderFor\(env, \{ httpClient \}\)/, 'the reader is made around the build\u2019s own client');+ const wiring = src.slice(src.indexOf('verify: (s, verifyOpts) =>'));+ assert.match(wiring.slice(0, wiring.indexOf('\n')), /isolatedReader \}/, 'verify takes the reader makeSdk returned');+ assert.strictEqual((src.match(/isolatedReaderFor\(/g) || []).length, 1, 'no second reader, and so no second client, is made');+});+// #447 follow-up: an LCID reaches Dataverse as a label LanguageCode, so a value that merely SURVIVES// a `Number()` cast is not good enough. `Number(true) === 1` and `Number([1033]) === 1033` both pass// a naive positive-integer check, so a spec containing `"languageCode": true` would have built everydiff --git a/plugins/model-apps/scripts/tests/changed-only-flow.test.js b/plugins/model-apps/scripts/tests/changed-only-flow.test.jsindex b4e45a529..a5cdbc430 100644--- a/plugins/model-apps/scripts/tests/changed-only-flow.test.js+++ b/plugins/model-apps/scripts/tests/changed-only-flow.test.js@@ -109,6 +109,16 @@ test('decide: identity mismatch -> full (gate blocks)', () => {assert.match(d.reason, /orgId/);});+test('decide: a distrust marker forces a full build, even on an eligible snapshot with nothing changed', () => {+ const prior = annotate(baseSpec(), 'v1');+ const env = seedFromPrior(prior);+ const cur = annotate(baseSpec(), 'v1');+ assert.strictEqual(flow.decideChangedOnly({ annotatedSpec: cur, snapshot: env, live: LIVE }).decision, 'noop', 'control: nothing changed');+ const d = flow.decideChangedOnly({ annotatedSpec: cur, snapshot: env, live: LIVE, distrust: { names: ['apply-snapshot.distrust.x.json'], reason: 'snapshot lease unavailable (held)' } });+ assert.strictEqual(d.decision, 'full');+ assert.match(d.reason, /could not invalidate the snapshot \(snapshot lease unavailable \(held\)\)/);+});+test('decide: ineligible (debt-carrying) snapshot -> full even for a page edit', () => {const prior = annotate(baseSpec(), 'v1');const env = snap.makeEnvelope(LIVE, { generation: 'g' });@@ -349,6 +359,584 @@ test('run: invalidate failure (lease held) ABORTS a fast apply without building'} finally { rm(dir); }});+// #587 item 1: a teardown that tombstones the snapshot while a changed-only run is between its read and+// its first write must fence that run. Measured before the fix: the run resumed with decision FAST,+// invalidated the tombstoned copy, and its re-bless CAS still matched — leaving the snapshot eligible with+// no debt, i.e. the tombstone erased. The identity lookup is the slow network step where that lands.+for (const [path_, spec, content] of [+ ['FAST', baseSpec, 'v2'],+ ['FULL', () => { const s = baseSpec(); s.charts[0].kind = 'pie'; return s; }, 'v1'],+]) {+ test(`run: a teardown tombstone landing during identity discovery fences a ${path_} apply (#587 item 1)`, async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, {+ buildModelApp: stubBuild(record), readContent: readFor(content),+ resolveLiveIdentity: async () => { assert.ok(store.tombstoneSnapshot(dir).ok); return LIVE; },+ }) });+ assert.strictEqual(r.changedOnly.decision, path_.toLowerCase(), 'precondition: the stale read still decides this path');+ assert.strictEqual(r.ok, false, 'the run must fail closed');+ assert.strictEqual(record.length, 0, 'nothing may be applied on a snapshot a teardown has fenced');+ assert.match(r.errors[0], /changed since/);+ const disk = store.readSnapshot(dir);+ assert.ok(snap.isTombstoned(disk) && disk.eligible === false, 'the tombstone survives');+ } finally { rm(dir); }+ });++ // The other window: the tombstone lands AFTER this run's invalidate, while its build is running. The+ // run's re-bless must then lose its CAS rather than write its pre-teardown view over the tombstone.+ test(`run: a teardown tombstone landing during a ${path_} build is not re-blessed away (#587 item 1)`, async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ const build = async () => {+ assert.ok(store.tombstoneSnapshot(dir).ok);+ return { ok: true, dryRun: false, created: { app: 'app-1', pages: { overview: 'page-1' } }, verify: { ok: true } };+ };+ const r = await flow.runChangedOnlyApply({ spec: spec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor(content) }) });+ assert.strictEqual(r.changedOnly.decision, path_.toLowerCase());+ const disk = store.readSnapshot(dir);+ assert.ok(snap.isTombstoned(disk) && disk.eligible === false, `the tombstone must survive the re-bless; got ${JSON.stringify({ eligible: disk && disk.eligible, debt: disk && disk.debt })}`);+ // And the run fails: what it built may already be deleted, and no baseline records it.+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[r.errors.length - 1], /the workspace changed while this (fast apply|build) ran/);+ } finally { rm(dir); }+ });+}++// The same fence for a FIRST build, which has no snapshot to be fenced by. Its baseline write expected+// "no snapshot", and a teardown that found none either wrote nothing, so the build blessed an app the+// teardown had just deleted — the fence above only covered a workspace that already had a snapshot. The+// build now claims a placeholder before it builds, and a teardown tombstones even an empty workspace.+const FRESH = { orgId: 'org-1', envUrl: 'https://e', appUniqueName: 'new_app', appId: null };+test('run: a teardown landing during identity discovery stops a FIRST build before it builds anything', async () => {+ const dir = ws();+ try {+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, {+ buildModelApp: stubBuild(record), readContent: readFor('v1'),+ resolveLiveIdentity: async () => { assert.ok(store.tombstoneSnapshot(dir).ok); return FRESH; },+ }) });+ assert.match(r.changedOnly.reason, /no snapshot/, 'precondition: the run read no snapshot');+ assert.strictEqual(r.ok, false, 'the run must fail closed');+ assert.strictEqual(record.length, 0, 'nothing may be built while a teardown holds the workspace');+ assert.match(r.errors[0], /could not claim the workspace for the first baseline \(a snapshot appeared since/);+ const disk = store.readSnapshot(dir);+ assert.ok(snap.isTombstoned(disk) && disk.eligible === false, 'the tombstone survives');+ } finally { rm(dir); }+});++for (const [when, teardown] of [+ ['finishes with errors', (dir) => assert.ok(store.tombstoneSnapshot(dir).ok)],+ ['finishes cleanly', (dir) => { assert.ok(store.tombstoneSnapshot(dir).ok); assert.ok(store.deleteSnapshot(dir).ok); }],+]) {+ test(`run: a teardown that ${when} during a FIRST build leaves no eligible baseline behind`, async () => {+ const dir = ws();+ try {+ const build = async () => {+ teardown(dir);+ return { ok: true, dryRun: false, created: { app: 'app-1', pages: { overview: 'page-1' } }, verify: { ok: true } };+ };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, resolveLiveIdentity: async () => FRESH, readContent: readFor('v1') }) });+ assert.match(r.changedOnly.reason, /no snapshot/);+ const disk = store.readSnapshot(dir);+ assert.ok(!disk || (disk.eligible === false && snap.isTombstoned(disk)), `no eligible baseline may be written over a teardown; got ${JSON.stringify(disk && { eligible: disk.eligible, debt: disk.debt })}`);+ } finally { rm(dir); }+ });+}++// The placeholder a crashed first build leaves must not poison the next one: no debt (a baseline inherits+// its prior's), and no identity mismatch in the reason a reader sees.+test('run: a FIRST build that fails leaves a debt-free placeholder, and the next run still certifies a fresh baseline', async () => {+ const dir = ws();+ try {+ const failed = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: async () => ({ ok: false, errors: ['boom'] }), resolveLiveIdentity: async () => FRESH, readContent: readFor('v1') }) });+ assert.strictEqual(failed.ok, false);+ const placeholder = store.readSnapshot(dir);+ assert.ok(placeholder && placeholder.eligible === false && placeholder.debt.length === 0 && placeholder.priorSpec === null, JSON.stringify(placeholder));+ const d = flow.decideChangedOnly({ annotatedSpec: annotate(baseSpec(), 'v1'), snapshot: placeholder, live: FRESH });+ assert.strictEqual(d.decision, 'full');+ assert.match(d.reason, /not eligible/, `reported as not eligible, not as an identity mismatch: ${d.reason}`);+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), resolveLiveIdentity: async () => FRESH, readContent: readFor('v1') }) });+ assert.strictEqual(r.ok, true);+ assert.strictEqual(record.length, 1);+ const disk = store.readSnapshot(dir);+ assert.strictEqual(disk.eligible, true, `the retry certifies its fresh baseline; debt ${JSON.stringify(disk.debt)}`);+ assert.strictEqual(disk.appId, 'app-1');+ } finally { rm(dir); }+});++// A tombstone that lists a teardown still running means that teardown is deleting the app right now: a+// build would recreate what it deletes, and its fenced invalidate would pass — the generation it compares+// is the tombstone's own. So a changed-only run refuses and builds nothing until the teardown finishes.+test('run: a changed-only build refuses while a teardown of the workspace is still running', async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ const t = store.tombstoneSnapshot(dir);+ const before = store.readSnapshot(dir);+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor('v1') }) });+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[0], /^changed-only: 1 teardown\(s\) of this workspace are still running \(pid \d+, last seen \d+s ago\) — re-run the build once they have finished\. A teardown that died stops counting 5 minutes after it was last seen\.$/);+ assert.strictEqual(record.length, 0, 'nothing is built while the teardown deletes');+ assert.deepStrictEqual(store.readSnapshot(dir), before, 'and the tombstone is untouched');+ assert.deepStrictEqual(store.releaseTombstone(dir, t.teardownId), { ok: true, deleted: true }, 'the teardown then finishes as usual');+ } finally { rm(dir); }+});++// …whichever build it would have run: a run that cannot resolve its live identity falls back to a plain+// full build, and that one waits for the teardown too — before it even asks for the identity.+test('run: the no-identity fallback also waits for a teardown still running', async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ store.tombstoneSnapshot(dir);+ const record = [];+ let asked = 0;+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor('v1'), resolveLiveIdentity: async () => { asked += 1; return null; } }) });+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[0], /teardown\(s\) of this workspace are still running/);+ assert.deepStrictEqual([record.length, asked], [0, 0], 'nothing built, and the identity never asked for');+ } finally { rm(dir); }+});++// …and a teardown that BEGINS while the identity is being resolved is not in the first read. The fenced+// branches catch it through their invalidate; the no-identity one writes no snapshot, so it reads the+// workspace again and refuses when it moved — a teardown's tombstone, or another build's invalidate.+test('run: the no-identity fallback refuses when the workspace changed during identity discovery', async () => {+ for (const [what, seed, during] of [+ ['a teardown began', (dir) => seedEligible(dir, annotate(baseSpec(), 'v1')), (dir) => store.tombstoneSnapshot(dir)],+ ['a teardown began on a workspace with no snapshot', () => {}, (dir) => store.tombstoneSnapshot(dir)],+ ['another build invalidated it', (dir) => seedEligible(dir, annotate(baseSpec(), 'v1')), (dir) => store.invalidateSnapshot(dir, { expectedGeneration: store.readSnapshot(dir).generation })],+ ]) {+ const dir = ws();+ try {+ seed(dir);+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor('v1'), resolveLiveIdentity: async () => { during(dir); return null; } }) });+ assert.strictEqual(r.ok, false, what);+ assert.match(r.errors[0], /the workspace changed while the live identity was being resolved/, what);+ assert.strictEqual(record.length, 0, `${what}: nothing is built`);+ } finally { rm(dir); }+ }+});++// A teardown that begins after that re-read, while the build runs, is not fenced by it, and this path writes no+// baseline whose CAS could be refused. The workspace is read again when the build returns, and a moved generation+// fails the run: what the build made may already be partly deleted.+test('run: the no-identity fallback fails when the workspace changed while the build ran', async () => {+ for (const [what, seed, during] of [+ ['a teardown began', (dir) => seedEligible(dir, annotate(baseSpec(), 'v1')), (dir) => store.tombstoneSnapshot(dir)],+ ['a teardown began on a workspace with no snapshot', () => {}, (dir) => store.tombstoneSnapshot(dir)],+ ['another build invalidated it', (dir) => seedEligible(dir, annotate(baseSpec(), 'v1')), (dir) => store.invalidateSnapshot(dir, { expectedGeneration: store.readSnapshot(dir).generation })],+ ]) {+ const dir = ws();+ try {+ seed(dir);+ const record = [];+ const build = async (spec, opts) => { record.push(opts.phases); during(dir); return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } }; };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(record.length, 1, `${what}: the build ran`);+ assert.strictEqual(r.ok, false, what);+ assert.match(r.errors[r.errors.length - 1], /the workspace changed while this build ran/, what);+ assert.strictEqual(r.changedOnly.reason, 'the workspace changed during the build', what);+ } finally { rm(dir); }+ }+ // CONTROL: nothing changes the workspace during the build — the full build's result stands.+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual(r.changedOnly, { decision: 'full', reason: 'no live identity' });+ } finally { rm(dir); }+});++// With no snapshot there was no generation to compare: a teardown that began AND finished during the build wrote its+// tombstone and deleted it on release, and "none" before and after hid it. The run claims a placeholder first, and+// drops it afterwards when nothing raced, so this path still leaves no snapshot behind.+test('run: the no-identity fallback on a workspace with no snapshot sees a teardown that came and went during the build', async () => {+ const dir = ws();+ try {+ const record = [];+ const build = async (spec, opts) => {+ record.push(opts.phases);+ assert.ok(store.readSnapshot(dir), 'the build runs under the placeholder the run claimed');+ const t = store.tombstoneSnapshot(dir);+ assert.deepStrictEqual(store.releaseTombstone(dir, t.teardownId), { ok: true, deleted: true }, 'precondition: the teardown finished and deleted its tombstone');+ return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } };+ };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(record.length, 1);+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[r.errors.length - 1], /the workspace changed while this build ran/);+ } finally { rm(dir); }+ // CONTROL: nothing raced — the build's result stands, and the placeholder is gone again.+ const quiet = ws();+ try {+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: quiet, apply: true }, deps: baseDeps(quiet, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.strictEqual(store.readSnapshot(quiet), null, 'no snapshot is left behind');+ } finally { rm(quiet); }+ // A claim that cannot be made (another writer holds the lease) stops the run before it builds anything.+ const busy = ws();+ try {+ fs.writeFileSync(store.leasePath(busy), JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'held' }));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: busy, apply: true }, deps: baseDeps(busy, { buildModelApp: stubBuild(record), readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[0], /could not claim the workspace before the build/);+ assert.strictEqual(record.length, 0, 'nothing is built');+ } finally { rm(busy); }+});++// Two no-identity builds that read the same generation, one inside the other, each saw it unchanged at the end and+// both reported success. Each now takes a generation of its own before it builds, so the first sees the second's.+test('run: overlapping no-identity builds do not both pass', async () => {+ for (const [what, seed] of [+ ['on a workspace with no snapshot', () => {}],+ ['on a workspace with an eligible snapshot', (dir) => seedEligible(dir, annotate(baseSpec(), 'v1'))],+ ]) {+ const dir = ws();+ try {+ seed(dir);+ let inner = null;+ const innerDeps = baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => null });+ const build = async () => {+ inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: innerDeps });+ return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } };+ };+ const outer = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.ok(inner, `${what}: the second build ran inside the first`);+ assert.strictEqual(outer.ok, false, `${what}: the first build saw the second`);+ assert.match(outer.errors[outer.errors.length - 1], /the workspace changed while this build ran/, what);+ } finally { rm(dir); }+ }+});++// A no-identity build outdates the baseline it read, as any full build does, so the baseline is invalidated first —+// fenced to the generation read — and never left eligible behind the build.+test('run: the no-identity fallback invalidates an existing baseline before it builds', async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ const seen = store.readSnapshot(dir).generation;+ let during = null;+ const build = async () => { during = store.readSnapshot(dir); return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } }; };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.ok(during && during.eligible === false && during.generation !== seen, 'invalidated, with a rotated generation, before the build ran');+ assert.strictEqual(store.readSnapshot(dir).eligible, false, 'and still ineligible afterwards');+ } finally { rm(dir); }+ // An invalidate that cannot be made (the lease is held) stops the run before it builds anything.+ const busy = ws();+ try {+ seedEligible(busy, annotate(baseSpec(), 'v1'));+ fs.writeFileSync(store.leasePath(busy), JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'held' }));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: busy, apply: true }, deps: baseDeps(busy, { buildModelApp: stubBuild(record), readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(r.ok, false);+ assert.match(r.errors[0], /could not invalidate the snapshot before the build/);+ assert.strictEqual(record.length, 0);+ } finally { rm(busy); }+});++// A build that sees the workspace change under it cannot vouch for a baseline another build blessed meanwhile: it may+// have overwritten what that baseline certifies since. The snapshot it finds is made ineligible, so the next run+// cannot noop on it.+test('run: a build that saw the workspace change under it leaves no eligible baseline behind', async () => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ const blessedInside = async (dir) => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ assert.strictEqual(inner.ok, true, JSON.stringify(inner.errors));+ assert.strictEqual(store.readSnapshot(dir).eligible, true, 'precondition: the inner build blessed a fresh baseline');+ };+ for (const [what, seed, outerIdentity] of [+ ['a no-identity build', () => {}, async () => null],+ ['a full build whose baseline write is refused', () => {}, async () => FRESH],+ ]) {+ const dir = ws();+ try {+ seed(dir);+ const build = async () => { await blessedInside(dir); return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } }; };+ await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: outerIdentity }) });+ assert.strictEqual(store.readSnapshot(dir).eligible, false, `${what}: the baseline blessed meanwhile is no longer eligible`);+ const next = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => ({ ...LIVE }) }) });+ assert.notStrictEqual(next.noop, true, `${what}: the next run does not noop on it`);+ } finally { rm(dir); }+ }+});++// A fresh-app build that has built and verified still holds the generation its baseline write will CAS against, and+// its snapshot is ineligible until then. Distrust that skipped an ineligible snapshot left that generation standing,+// and the paused build then blessed a state the other build had since changed. Distrust rotates it.+test('run: a build paused before its baseline write cannot bless it after another build distrusted the workspace', async () => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ const dir = ws();+ try {+ let signalPaused;+ const paused = new Promise((res) => { signalPaused = res; });+ let release;+ const gate = new Promise((res) => { release = res; });+ let calls = 0;+ const innerDeps = baseDeps(dir, {+ buildModelApp: stubBuild([]),+ readContent: readFor('v1'),+ // The second lookup is the one a fresh build makes after its build, just before its baseline CAS.+ resolveLiveIdentity: async () => { calls += 1; if (calls === 2) { signalPaused(); await gate; } return FRESH; },+ });+ let inner = null;+ const outerBuild = async () => {+ inner = flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: innerDeps });+ await paused;+ return { ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } };+ };+ const outer = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: outerBuild, readContent: readFor('v1'), resolveLiveIdentity: async () => null }) });+ assert.strictEqual(outer.ok, false, 'the older build saw the newer one');+ release();+ await inner;+ assert.notStrictEqual(store.readSnapshot(dir).eligible, true, 'the paused build could not bless its baseline');+ } finally { rm(dir); }+});++// A build that fails verification, or halts, has still changed the environment. Its way out skipped the conflict check,+// and a baseline another build blessed while it ran stayed eligible.+test('run: a build that fails or throws still distrusts a baseline another build blessed while it ran', async () => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ for (const [what, finish, outerIdentity] of [+ ['a full build whose verify fails', () => ({ ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: false } }), async () => FRESH],+ ['a full build that throws', () => { throw new Error('build halted'); }, async () => FRESH],+ ['a no-identity build that throws', () => { throw new Error('build halted'); }, async () => null],+ ]) {+ const dir = ws();+ try {+ const build = async () => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ assert.strictEqual(inner.ok, true, `${what}: ${JSON.stringify(inner.errors)}`);+ assert.strictEqual(store.readSnapshot(dir).eligible, true, `${what}: precondition: the inner build blessed a baseline`);+ return finish();+ };+ let threw = null;+ try {+ await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: outerIdentity }) });+ } catch (e) { threw = e; }+ if (/throws/.test(what)) assert.match(String(threw && threw.message), /build halted/, `${what}: the original error goes on`);+ assert.strictEqual(store.readSnapshot(dir).eligible, false, `${what}: the baseline blessed meanwhile is no longer eligible`);+ } finally { rm(dir); }+ }+});++// A writer can also land after the build returns but before the baseline write: a fresh-app build looks its identity up+// again in between. Its refused CAS distrusts what that writer left, too.+test('run: a baseline blessed between a build and its own baseline write is distrusted', async () => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ const dir = ws();+ try {+ let calls = 0;+ const resolve = async () => {+ calls += 1;+ if (calls === 2) {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ assert.strictEqual(inner.ok, true, JSON.stringify(inner.errors));+ assert.strictEqual(store.readSnapshot(dir).eligible, true, 'precondition: blessed between the build and the write');+ }+ return FRESH;+ };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: resolve }) });+ assert.ok(calls >= 2, 'the fresh build looked its identity up again before writing');+ assert.strictEqual(store.readSnapshot(dir).eligible, false);+ assert.strictEqual(r.ok, false, 'the refused write was a conflict, so the run fails');+ assert.match(r.errors[r.errors.length - 1], /the workspace changed while this build ran/);+ } finally { rm(dir); }+});++// A write refused only because another writer held the lease for a moment is no conflict: the generation is still+// this run's, and the build's result stands.+test('run: a baseline write refused by a busy lease leaves the result standing', async (t) => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ const dir = ws();+ try {+ t.mock.method(store, 'casWriteSnapshot', () => ({ ok: false, reason: 'snapshot lease unavailable (held)' }));+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ t.mock.restoreAll();+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.notStrictEqual(store.readSnapshot(dir).eligible, true, 'and nothing is blessed');+ } finally { rm(dir); }+});++// A baseline write refused by a busy lease looked like no conflict: the generation read then was still this run's. But+// that lease can be an older build's, about to rotate the generation. What distrust then sees decides it too, and a+// distrust that cannot land at all fails the run closed.+test('run: a busy-lease refusal whose lease turns out to be another writer\'s fails the run', async (t) => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ for (const [what, invalidate] of [+ ['another writer rotates the generation during distrust', (real) => {+ let calls = 0;+ return (d, o) => {+ calls += 1;+ if (calls === 1) { real(d, { expectedGeneration: o.expectedGeneration }); return { ok: false, reason: 'the snapshot changed since this run read it' }; }+ return real(d, o);+ };+ }],+ ['distrust never lands', () => () => ({ ok: false, reason: 'snapshot lease unavailable (held)' })],+ ]) {+ const dir = ws();+ try {+ const realInvalidate = store.invalidateSnapshot;+ t.mock.method(store, 'casWriteSnapshot', () => ({ ok: false, reason: 'snapshot lease unavailable (held)' }));+ t.mock.method(store, 'invalidateSnapshot', invalidate(realInvalidate));+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ t.mock.restoreAll();+ assert.strictEqual(r.ok, false, what);+ assert.match(r.errors[r.errors.length - 1], /the workspace changed while this build ran/, what);+ } finally { t.mock.restoreAll(); rm(dir); }+ }+});++// When distrust cannot land at all (every invalidate refused, the lease held by a live writer), the run fails, but the+// snapshot that writer leaves can read eligible, and the next run would noop on it. So distrust records the refusal+// beside the snapshot, outside the lease: the next run builds in full, and its landed baseline clears the marker.+test('run: a distrust that cannot land leaves a marker, and the next run builds in full and clears it', async () => {+ const FRESH = { ...LIVE, appId: null, appIdKnown: true };+ for (const [what, finish] of [+ ['a build that throws', () => { throw new Error('build halted'); }],+ ['a build that returns', () => ({ ok: true, dryRun: false, created: { app: 'app-1' }, verify: { ok: true } })],+ ]) {+ const dir = ws();+ try {+ const build = async () => {+ const inner = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild([]), readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ assert.strictEqual(inner.ok, true, `${what}: ${JSON.stringify(inner.errors)}`);+ // Another live writer holds the lease, so no invalidate this run's distrust tries can land.+ fs.writeFileSync(store.leasePath(dir), JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'held' }));+ return finish();+ };+ let threw = null;+ let r = null;+ try {+ r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: build, readContent: readFor('v1'), resolveLiveIdentity: async () => FRESH }) });+ } catch (e) { threw = e; }+ if (/throws/.test(what)) assert.match(String(threw && threw.message), /build halted/, `${what}: the original error goes on`);+ else assert.strictEqual(r.ok, false, `${what}: the overlapped run fails`);+ assert.strictEqual(store.readSnapshot(dir).eligible, true, `${what}: precondition: the other writer's baseline stayed eligible`);+ assert.ok(store.readDistrust(dir), `${what}: the refusal is recorded`);+ fs.rmSync(store.leasePath(dir), { force: true });+ // Nothing changed since that eligible baseline, which alone would be a noop; the marker makes it a full build.+ let built = 0;+ const record = [];+ const next = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: async (...a) => { built += 1; return stubBuild(record)(...a); }, readContent: readFor('v1'), resolveLiveIdentity: async () => ({ ...LIVE }) }) });+ assert.strictEqual(next.ok, true, `${what}: ${JSON.stringify(next.errors)}`);+ assert.strictEqual(built, 1, `${what}: the next run builds`);+ assert.strictEqual(record[0].phases, undefined, `${what}: in full`);+ assert.match(next.changedOnly.reason, /could not invalidate the snapshot/, `${what}: because of the marker`);+ assert.strictEqual(store.readDistrust(dir), null, `${what}: its landed baseline clears the marker`);+ } finally { rm(dir); }+ }+});++// A full build clears only the marker it read when it started. One written while it built is another run's, which+// found the workspace changed under it, and this build's baseline cannot vouch for what that run did.+test('run: a full build clears the distrust marker it read, and leaves one written while it built', async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'), 'g-seeded');+ assert.strictEqual(store.markDistrusted(dir, { reason: 'before' }).ok, true);+ const during = async (...a) => { store.markDistrusted(dir, { reason: 'during' }); return stubBuild([])(...a); };+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: during, readContent: readFor('v1'), resolveLiveIdentity: async () => ({ ...LIVE }) }) });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.strictEqual((store.readDistrust(dir) || {}).reason, 'during', 'the marker written during the build stays');+ } finally { rm(dir); }+});++// A writer can land between distrust's read and its invalidate (the fenced invalidate is then refused). What it left is+// read again and invalidated in turn, rather than left eligible.+test('distrustWorkspace invalidates a baseline that landed between its read and its invalidate', (t) => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'), 'g-first');+ const realInvalidate = store.invalidateSnapshot;+ let calls = 0;+ t.mock.method(store, 'invalidateSnapshot', (d, o) => {+ calls += 1;+ if (calls === 1) {+ seedEligible(dir, annotate(baseSpec(), 'v1'), 'g-landed');+ return realInvalidate(d, o);+ }+ return realInvalidate(d, o);+ });+ flow.distrustWorkspace(dir, () => {});+ t.mock.restoreAll();+ assert.strictEqual(calls, 2, 'the refused invalidate is retried');+ const disk = store.readSnapshot(dir);+ assert.strictEqual(disk.eligible, false, 'the baseline that landed is invalidated too');+ assert.notStrictEqual(disk.generation, 'g-landed', 'and its generation rotated');+ } finally { rm(dir); }+});++// readSnapshot answers null for an absent snapshot and for one it could not read alike. A snapshot that exists but reads+// as nothing, a transient read error, may still be another writer's eligible baseline, readable again by the next run,+// so distrust reads it again, and records the refusal if it never reads. Only a snapshot that is provably absent leaves+// nothing to distrust.+test('distrustWorkspace does not take a snapshot it cannot read for an absent one', (t) => {+ const dir = ws();+ const empty = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'), 'g-first');+ const realRead = store.readSnapshot;+ let failures = 1;+ t.mock.method(store, 'readSnapshot', (d) => (failures-- > 0 ? null : realRead(d)));+ const once = flow.distrustWorkspace(dir, () => {});+ t.mock.restoreAll();+ assert.strictEqual(once.resolved, true, 'a read that recovers is retried');+ assert.strictEqual(store.readSnapshot(dir).eligible, false, 'and the baseline is invalidated');+ assert.strictEqual(store.readDistrust(dir), null, 'with no marker needed');+ seedEligible(dir, annotate(baseSpec(), 'v1'), 'g-second');+ t.mock.method(store, 'readSnapshot', () => null);+ const never = flow.distrustWorkspace(dir, () => {});+ t.mock.restoreAll();+ assert.strictEqual(never.resolved, false, 'a snapshot that never reads is not an absent one');+ assert.strictEqual(store.readSnapshot(dir).eligible, true, 'precondition: it stayed as the other writer left it');+ assert.match(store.readDistrust(dir).reason, /exists but could not be read/, 'so the refusal is recorded');+ assert.deepStrictEqual(flow.distrustWorkspace(empty, () => {}), { foreign: false, resolved: true }, 'CONTROL: an absent snapshot');+ assert.strictEqual(store.readDistrust(empty), null, 'leaves nothing to record');+ } finally { t.mock.restoreAll(); rm(dir); rm(empty); }+});++test('dropBaselineClaim removes only the placeholder it was given', () => {+ const dir = ws();+ try {+ const claim = store.claimBaselineSnapshot(dir, {});+ assert.strictEqual(claim.ok, true);+ assert.strictEqual(store.dropBaselineClaim(dir, 'another-generation').ok, false, 'not a placeholder this run claimed');+ assert.ok(store.readSnapshot(dir), 'so it stays');+ assert.deepStrictEqual(store.dropBaselineClaim(dir, claim.generation), { ok: true });+ assert.strictEqual(store.readSnapshot(dir), null);+ assert.strictEqual(store.dropBaselineClaim(dir, claim.generation).ok, false, 'nothing left to drop');+ } finally { rm(dir); }+});++// A tombstone no teardown still holds — one that failed, or a day old — does not block: the build runs, and+// the tombstone's debt keeps its baseline ineligible, as it always did.+test('run: a tombstone no teardown still holds only makes the baseline ineligible', async () => {+ const dir = ws();+ try {+ seedEligible(dir, annotate(baseSpec(), 'v1'));+ store.tombstoneSnapshot(dir, { now: () => Date.now() - store.TEARDOWN_STALE_MS - 1000 });+ assert.deepStrictEqual(store.teardownsInFlight(store.readSnapshot(dir)), [], 'precondition: no teardown is still running');+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor('v1') }) });+ assert.strictEqual(r.changedOnly.decision, 'full');+ assert.strictEqual(record.length, 1);+ const disk = store.readSnapshot(dir);+ assert.ok(disk && disk.eligible === false && snap.isTombstoned(disk), 'the teardown debt keeps the baseline ineligible');+ } finally { rm(dir); }+});+test('run: FULL fallback for an unsupported edit records the sticky debt (ineligible baseline)', async () => {const dir = ws();try {diff --git a/plugins/model-apps/scripts/tests/classify-changes.test.js b/plugins/model-apps/scripts/tests/classify-changes.test.jsindex 0202aaf69..356f4f3e2 100644--- a/plugins/model-apps/scripts/tests/classify-changes.test.js+++ b/plugins/model-apps/scripts/tests/classify-changes.test.js@@ -135,6 +135,19 @@ test('app ICON/description change -> full (not a sitemap-only edit)', () => {assert.ok(r.fullReasons.some((x) => /app object/.test(x)));});+// #583: the fast app-shell apply writes only the sitemap, so a routing-description edit riding on it+// would be dropped. The app object is compared WHOLE, which is what routes this to a full build — pin+// it so narrowing that comparison to named keys cannot silently skip `app.aiDescription`.+test('#583 an app.aiDescription-only change -> full, and phase-diff reports app-shell', () => {+ const prior = spec();+ const cur = spec();+ cur.app.aiDescription = 'Route order work here.';+ const r = C.classifyChanges(cur, prior);+ assert.strictEqual(r.verdict, 'full');+ assert.ok(r.fullReasons.some((x) => /app object/.test(x)));+ assert.deepStrictEqual(require('../lib/phase-diff.js').diffPhases(cur, prior), ['app-shell']);+});+test('data-model change -> full build, NO debt (a full build applies it)', () => {const cur = spec();cur.entities[0].columns.push({ schemaName: 'new_amount', type: 'Money' });diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex 0e32fe3f1..fe058d685 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -494,10 +494,12 @@ test('#564 a GLOBAL-bound picklist emits a globalChoice reference instead of inlassert.strictEqual(status.type, 'Choice');assert.strictEqual(status.globalChoice, 'shared_stage');assert.strictEqual(status.options, undefined, 'a global-bound column must not ALSO carry inline options');- // The shared set itself has to be declared, or a fresh-environment rebuild has nothing to bind to.+ // The shared set itself has to be declared, or a fresh-environment rebuild has nothing to bind to —+ // and declared `existing: true`, so a teardown does not delete an org-wide set it cannot prove this+ // app created (#587 item 6).const decls = new Map();collectGlobalChoices(meta, decls);- assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Draft', 'Final'] }]);+ assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Draft', 'Final'], existing: true }]);});test('#564 a MultiSelect picklist downloads as MultiChoice', async () => {@@ -531,7 +533,7 @@ test('#564 inline options keep their localizations, but a global declaration isassert.deepStrictEqual(e.columns.find((c) => c.schemaName === 'new_status').options, [{ 1033: 'Open', 3082: 'Abierto' }]);const decls = new Map();collectGlobalChoices(meta, decls);- assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Open'] }]);+ assert.deepStrictEqual([...decls.values()], [{ name: 'shared_stage', options: ['Open'], existing: true }]);});test('#564 one global set bound by two columns is declared exactly once', async () => {@@ -651,6 +653,49 @@ test('readDashboards reconstructs supported tile shapes and skips unreadable das]);});+// #586 item 4: an App Spec refers to a dashboard by NAME (the sitemap subarea, and the build's lookup+// of an existing one), so two different dashboards whose names Dataverse compares equal collapse into+// one on rebuild and the other silently leaves the nav. They are withheld — which drops their+// subareas and trips the lossy-download gate — and the reason names both.+test('readDashboards withholds dashboards whose names Dataverse treats as one, and says why', async () => {+ const A = '{AAAAAAAA-0000-4000-8000-00000000000A}';+ const B = '{BBBBBBBB-0000-4000-8000-00000000000B}';+ const C = '{CCCCCCCC-0000-4000-8000-00000000000C}';+ const bare = (g) => String(g).replace(/[{}]/g, '').toLowerCase();+ // The REAL names come from systemform; the subarea titles differ on purpose, so this proves the+ // clash is judged on the dashboard's own name and not on whatever the nav entry happens to say.+ // Case, an accent and a trailing space all compare equal on the server — a leading space would not.+ const names = { [bare(A)]: 'Overview', [bare(B)]: 'OVERVIÉW ', [bare(C)]: 'Pipeline' };+ // C sits behind TWO subareas (its id in two cases): one dashboard, which must not clash with itself.+ const subAreas = [[A, 'Nav A'], [B, 'Nav B'], [C, 'Nav C'], [C.toLowerCase(), 'Nav C again']]+ .map(([id, title]) => ({ type: 'DashBoard', dashboardId: id, title }));+ const app = { siteMap: { areas: [{ groups: [{ subAreas }] }] } };+ const sdk = {+ fetchArtifact: async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] }),+ queryRecords: async (_set, q) => {+ const hit = Object.keys(names).find((k) => bare(q.filter).includes(k));+ assert.ok(hit, `name query must target a known dashboard: ${q.filter}`);+ return [{ name: names[hit] }];+ },+ };+ const warnings = [];+ const dashboards = await readDashboards(sdk, app, (m) => warnings.push(m));+ assert.deepStrictEqual(dashboards.map((d) => d.name), ['Pipeline'], 'only the uniquely named dashboard round-trips');+ const clash = warnings.filter((w) => /share the name/.test(w));+ assert.strictEqual(clash.length, 1, JSON.stringify(warnings));+ assert.ok(bare(clash[0]).includes(bare(A)) && bare(clash[0]).includes(bare(B)), clash[0]);+ assert.ok(clash[0].includes("('Overview')") && clash[0].includes("('OVERVIÉW ')") && /rename one in Maker/.test(clash[0]), clash[0]);+ // And their subareas are then reported as dropped rather than silently re-pointed.+ const spec = await hydrateSpec({+ app: async () => ({ name: 'A', description: '', uniquename: 'p_a', siteMap: app.siteMap }),+ pages: async () => [], entities: async () => [], webResources: async () => [],+ solution: async () => ({ uniqueName: 'S', publisherPrefix: 'p' }),+ dashboards: async () => dashboards,+ });+ assert.strictEqual(spec.droppedSubareas, 2, 'both ambiguous subareas are counted as not round-tripped');+ assert.deepStrictEqual(spec.appShell.areas[0].groups[0].subAreas.map((s) => s.dashboard), ['Pipeline', 'Pipeline']);+});+// A chart tile renders a visualization OVER a view. A deployed component that carries a ViewId but no// VisualizationId therefore has nothing to plot, and emitting it anyway hands back a spec that fails// its own lint ("id-based chart tile with viewId also needs visualizationId") — the exact #572 defect@@ -789,6 +834,7 @@ test('readDescriptionInventory captures view, chart, form, business-rule, and glconst FORM_ID_RESTRICTED = '5111e0f2-0000-4000-8000-000000000007';const RULE_COPY_ID = '5111e0f2-0000-4000-8000-000000000008';const CLASSIC_ID = '5111e0f2-0000-4000-8000-000000000009';+ const OPTIONSET_ID = '5111e0f2-0000-4000-8000-00000000000a';const calls = [];const sdk = {// A real table logical name is the ONLY thing queryRecords can take: it resolves its argument@@ -818,6 +864,8 @@ test('readDescriptionInventory captures view, chart, form, business-rule, and gl];}if (set === 'solution') return [{ solutionid: SOL_ID }];+ // Component type 9 is OptionSet, whose objectid is the set's MetadataId (#586 item 5).+ if (set === 'solutioncomponent' && /componenttype eq 9\b/.test(filter)) return [{ objectid: `{${OPTIONSET_ID.toUpperCase()}}` }];if (set === 'solutioncomponent') return [{ objectid: RULE_ID, componenttype: 29 }];if (set === 'workflow') {return [@@ -837,7 +885,12 @@ test('readDescriptionInventory captures view, chart, form, business-rule, and glget: async (url) => {calls.push({ get: url });if (/^\/GlobalOptionSetDefinitions\?/.test(url)) {- return { status: 200, headers: {}, body: { value: [{ Name: 'new_priority', Description: { LocalizedLabels: [{ Label: 'Shared priority choices.', LanguageCode: 1033 }] } }] } };+ return { status: 200, headers: {}, body: { value: [+ { Name: 'new_priority', MetadataId: OPTIONSET_ID, Description: { LocalizedLabels: [{ Label: 'Shared priority choices.', LanguageCode: 1033 }] } },+ // Unmanaged, but neither in the app's solution nor bound by anything it emits: org-wide+ // metadata the app has nothing to do with, which must not be reported as the app's.+ { Name: 'contoso_unrelated', MetadataId: '5111e0f2-0000-4000-8000-00000000000b', IsManaged: false },+ ] } };}return { status: 404, headers: {}, body: {} };},@@ -868,13 +921,14 @@ test('readDescriptionInventory captures view, chart, form, business-rule, and gl`only the type-1 category-2 definition may be listed; got ${JSON.stringify(inv.businessRules.map((r) => r.name))}`);assert.ok(calls.some((c) => c.set === 'workflow' && c.opts.select.includes('category') && c.opts.select.includes('type')),'category and type must be REQUESTED, or the filter decides on undefined');- assert.deepStrictEqual(inv.globalChoices[0], { name: 'new_priority', description: 'Shared priority choices.' });+ assert.deepStrictEqual(inv.globalChoices, [{ name: 'new_priority', description: 'Shared priority choices.' }],+ 'only the set the app\'s solution owns — matched on its MetadataId despite the braces and casing');+ assert.ok(calls.some((c) => c.get === '/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged,MetadataId'),+ `global choices must be read through the RAW client (queryRecords cannot take a metadata path), selecting IsManaged so managed sets can be excluded and MetadataId so they can be joined to the solution; calls: ${JSON.stringify(calls.map((c) => c.get || c.set))}`);assert.ok(calls.some((c) => c.set === 'savedquery' && c.opts.select.includes('description')), 'view read selects description');assert.ok(calls.some((c) => c.set === 'savedqueryvisualization' && c.opts.select.includes('description')), 'chart read selects description');assert.ok(calls.some((c) => c.set === 'systemform' && c.opts.select.includes('description')), 'form read selects description');assert.ok(calls.some((c) => c.set === 'workflow' && c.opts.select.includes('description')), 'business-rule read selects description');- assert.ok(calls.some((c) => c.get === '/GlobalOptionSetDefinitions?$select=Name,Description,IsManaged'),- `global choices must be read through the RAW client (queryRecords cannot take a metadata path), selecting IsManaged so managed sets can be excluded; calls: ${JSON.stringify(calls.map((c) => c.get || c.set))}`);});test('the global-choice inventory excludes MANAGED option sets but keeps an unknown flag', async () => {@@ -885,8 +939,15 @@ test('the global-choice inventory excludes MANAGED option sets but keeps an unkn//// `$filter` cannot do this server-side: GlobalOptionSetDefinitions answers HTTP 405// (0x80060888) for `?$filter=IsManaged eq false`, which is why the filter is client-side.+ // All three sets are OWNED by the app's solution, so the only thing deciding their fate here is the+ // IsManaged filter under test — not the app scoping (#586 item 5) that runs alongside it.+ const ids = { new_priority: 'a1a1a1a1-0000-4000-8000-000000000001', msdyn_solutionhealthruleseverity: 'a1a1a1a1-0000-4000-8000-000000000002', legacy_noflag: 'a1a1a1a1-0000-4000-8000-000000000003' };const sdk = {- queryRecords: async () => [],+ queryRecords: async (set, opts) => {+ if (set === 'solution') return [{ solutionid: 'b2b2b2b2-0000-4000-8000-000000000001' }];+ if (set === 'solutioncomponent' && /componenttype eq 9\b/.test((opts && opts.filter) || '')) return Object.values(ids).map((objectid) => ({ objectid }));+ return [];+ },dataverse: {get: async (url) => {if (/^\/GlobalOptionSetDefinitions\?/.test(url)) {@@ -895,9 +956,9 @@ test('the global-choice inventory excludes MANAGED option sets but keeps an unknheaders: {},body: {value: [- { Name: 'new_priority', IsManaged: false },- { Name: 'msdyn_solutionhealthruleseverity', IsManaged: true },- { Name: 'legacy_noflag' }, // IsManaged absent — must be KEPT, not silently dropped+ { Name: 'new_priority', MetadataId: ids.new_priority, IsManaged: false },+ { Name: 'msdyn_solutionhealthruleseverity', MetadataId: ids.msdyn_solutionhealthruleseverity, IsManaged: true },+ { Name: 'legacy_noflag', MetadataId: ids.legacy_noflag }, // IsManaged absent — must be KEPT, not silently dropped],},};@@ -917,15 +978,110 @@ test('the global-choice inventory excludes MANAGED option sets but keeps an unkn);});-test('readDashboards keeps the sitemap title when the dashboard name lookup fails', async () => {+// #586 item 5: the option-set collection is ORG-wide, so an unscoped read reported an isolated app as+// leaving behind global choices it never had. Scoped to the app: its solution's sets (component type+// 9) plus the ones its emitted columns bind.+test('the global-choice inventory is scoped to the app: its solution\'s sets and the ones its columns bind', async () => {+ const OWNED = 'c3c3c3c3-0000-4000-8000-000000000001';+ const sdkFor = ({ owned = [OWNED], throwOnSolution = false, gets = [] } = {}) => ({+ queryRecords: async (set, opts) => {+ if (set === 'solution') {+ if (throwOnSolution) throw new Error('HTTP 403 on solution');+ return [{ solutionid: 'd4d4d4d4-0000-4000-8000-000000000001' }];+ }+ if (set === 'solutioncomponent' && /componenttype eq 9\b/.test((opts && opts.filter) || '')) return owned.map((objectid) => ({ objectid }));+ return [];+ },+ dataverse: {+ get: async (url) => {+ gets.push(url);+ return { status: 200, headers: {}, body: { value: [+ { Name: 'contoso_owned', MetadataId: OWNED, IsManaged: false },+ { Name: 'contoso_bound', MetadataId: 'c3c3c3c3-0000-4000-8000-000000000002', IsManaged: false },+ { Name: 'contoso_unrelated', MetadataId: 'c3c3c3c3-0000-4000-8000-000000000003', IsManaged: false },+ ] } };+ },+ },+ });+ const names = (inv) => (inv.globalChoices || []).map((g) => g.name).sort();+ const unknown = (inv) => (inv.incomplete || []).filter((i) => i.kind === 'globalChoices');++ assert.deepStrictEqual(names(await readDescriptionInventory(sdkFor(), 'app-1', 'ContosoSolution', new Set(['Contoso_Bound']))),+ ['contoso_bound', 'contoso_owned'], 'owned by the solution, or bound by an emitted column — never the unrelated one');++ // Nothing in scope — no solution that could own a set, and nothing bound — is nothing of THIS app's+ // to find: not an unknown, and not worth an org-wide read.+ for (const [what, sln] of [['no solution', null], ['a built-in container', 'Default']]) {+ const gets = [];+ const inv = await readDescriptionInventory(sdkFor({ gets }), 'app-1', sln, new Set());+ assert.deepStrictEqual(names(inv), [], what);+ assert.deepStrictEqual(unknown(inv), [], what);+ assert.deepStrictEqual(gets.filter((u) => /GlobalOptionSetDefinitions/.test(u)), [], `${what}: the org-wide read is skipped`);+ }+ const ownsNone = await readDescriptionInventory(sdkFor({ owned: [] }), 'app-1', 'ContosoSolution', new Set());+ assert.deepStrictEqual([names(ownsNone), unknown(ownsNone)], [[], []], 'a solution that owns no set is a real "none"');++ // A FAILED solution lookup is an unknown for every class it scopes — never an empty one.+ const failed = await readDescriptionInventory(sdkFor({ throwOnSolution: true }), 'app-1', 'ContosoSolution', new Set(['contoso_bound']));+ assert.deepStrictEqual((failed.incomplete || []).filter((i) => /403/.test(i.reason)).map((i) => i.kind).sort(), ['businessRules', 'globalChoices']);++ // A FULL page of owned sets is indistinguishable from a truncated one: say so, and keep what was read.+ const full = Array.from({ length: 1000 }, (_, i) => (i === 0 ? OWNED : `e5e5e5e5-0000-4000-8000-${String(i).padStart(12, '0')}`));+ const truncated = await readDescriptionInventory(sdkFor({ owned: full }), 'app-1', 'ContosoSolution', new Set());+ assert.deepStrictEqual(names(truncated), ['contoso_owned']);+ assert.match((unknown(truncated)[0] || {}).reason || '', /truncated/);+});++// An app in several solutions (#587 item 9) is inventoried across EVERY candidate — each contains the+// app — and a built-in container among them scopes nothing and is dropped. An Error scope means the+// membership could not be read: unknown, never empty.+test('the global-choice inventory unions the owned sets of every candidate solution', async () => {+ const OWN = { SolA: 'f6f6f6f6-0000-4000-8000-00000000000a', SolB: 'f6f6f6f6-0000-4000-8000-00000000000b' };+ const looked = [];const sdk = {- fetchArtifact: async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] }),- queryRecords: async () => { throw new Error('systemform read throttled'); },+ queryRecords: async (set, opts) => {+ const filter = (opts && opts.filter) || '';+ if (set === 'solution') {+ const m = filter.match(/uniquename eq '([^']+)'/);+ looked.push(m && m[1]);+ return m && OWN[m[1]] ? [{ solutionid: `sol-${m[1]}` }] : [];+ }+ const own = filter.match(/_solutionid_value eq sol-(\w+) and componenttype eq 9/);+ if (set === 'solutioncomponent' && own) return [{ objectid: OWN[own[1]] }];+ return [];+ },+ dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [+ { Name: 'set_a', MetadataId: OWN.SolA, IsManaged: false },+ { Name: 'set_b', MetadataId: OWN.SolB, IsManaged: false },+ { Name: 'set_elsewhere', MetadataId: 'f6f6f6f6-0000-4000-8000-00000000000c', IsManaged: false },+ ] } }) },};- const dashboards = await readDashboards(sdk, {- siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] },- });- assert.strictEqual(dashboards[0].name, 'Operations');+ const inv = await readDescriptionInventory(sdk, 'app-1', ['SolA', 'Default', 'SolB'], new Set());+ assert.deepStrictEqual((inv.globalChoices || []).map((g) => g.name).sort(), ['set_a', 'set_b']);+ assert.deepStrictEqual(looked, ['SolA', 'SolB'], 'the built-in Default container is never looked up');+ const unread = await readDescriptionInventory(sdk, 'app-1', new Error('membership unreadable'), new Set(['set_a']));+ assert.deepStrictEqual((unread.incomplete || []).map((i) => i.kind).filter((k) => k !== 'views' && k !== 'charts' && k !== 'forms').sort(), ['businessRules', 'globalChoices']);+ assert.strictEqual(unread.globalChoices, undefined, 'nothing is claimed about a scope that could not be read');+});++// An App Spec refers to a dashboard by name, and the sitemap title is only its label. Standing in for a name that+// could not be read, it made a rebuild create or bind to another dashboard, and hid a real name clash. Such a+// dashboard is withheld, and said to be — its subarea dropped, which the lossy-download gate reports.+test('readDashboards withholds a dashboard whose name cannot be read, instead of naming it after the sitemap title', async () => {+ const app = { siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: 'dash-1', title: 'Operations' }] }] }] } };+ const fetchArtifact = async () => ({ components: [{ type: 'iframe', name: 'Portal', parameters: { Url: 'https://contoso.example' } }] });+ for (const [what, queryRecords, why] of [+ ['a failed read', async () => { throw new Error('systemform read throttled'); }, /systemform read throttled/],+ ['no row', async () => [], /no row for it/],+ ]) {+ const warnings = [];+ const dashboards = await readDashboards({ fetchArtifact, queryRecords }, app, (m) => warnings.push(m));+ assert.deepStrictEqual(dashboards, [], what);+ assert.ok(warnings.some((w) => /dashboard 'Operations' \(dash-1\): its name could not be read/.test(w) && why.test(w) && /subarea will be dropped/.test(w)), `${what}: ${JSON.stringify(warnings)}`);+ }+ // CONTROL: a name that reads is the one emitted, whatever the title says.+ const named = await readDashboards({ fetchArtifact, queryRecords: async () => [{ name: 'Ops Board' }] }, app);+ assert.deepStrictEqual(named.map((d) => d.name), ['Ops Board']);});// ── Task 11: assignPageKeys + missingDownloads + full round-trip ──────────────@@ -1234,9 +1390,190 @@ test('recoverAppSolution returns null when the app has no solution components (cassert.strictEqual(await recoverAppSolution(sdk, 'app'), null);});-test('recoverAppSolution never throws — a query error resolves to null (best-effort)', async () => {- const sdk = { queryRecords: async () => { throw new Error('boom'); } };- assert.strictEqual(await recoverAppSolution(sdk, 'app'), null);+// A read failure is not "no solution": the caller has to be able to say it could not look.+test('recoverAppSolution never throws — a failed membership read is reported as unreadable, not as "no solution"', async () => {+ const sdk = { queryRecords: async () => { throw new Error('HTTP 403 on solutioncomponent'); } };+ assert.deepStrictEqual(await recoverAppSolution(sdk, 'app'), { unreadable: 'HTTP 403 on solutioncomponent' });+});++// #587 item 9: an app in several unmanaged solutions used to resolve to whichever row the server returned+// first, from a capped first page — so two downloads of one app could name different solutions. That is+// not cosmetic: a rebuild adds to the spec's solution and teardown deletes it.+const twoSolutionSdk = (order, prefixOf) => ({+ queryRecords: async (set, opts) => {+ if (set === 'solutioncomponent') {+ assert.strictEqual(opts.paginate, true, 'every membership page must be read');+ assert.strictEqual(opts.top, undefined, 'a $top is a hard cap with no nextLink, so it cannot be combined with paging');+ return order.map((id) => ({ _solutionid_value: id }));+ }+ if (set === 'solution') return order.map((id) => ({ solutionid: id, uniquename: { a: 'ContosoRelease', b: 'ContosoApp' }[id], ismanaged: false }));+ return [];+ },+ getSolution: async (uniqueName) => {+ const prefix = prefixOf(uniqueName);+ if (prefix instanceof Error) throw prefix;+ return { uniqueName, publisherPrefix: prefix };+ },+});++test('recoverAppSolution never picks between several unmanaged solutions, whatever the row order (#587 item 9)', async () => {+ for (const order of [['a', 'b'], ['b', 'a']]) {+ // Not even the one whose publisher matches the app name's prefix: that is the unreliable app-name+ // guess, and teardown deletes whatever solution the spec names.+ assert.deepStrictEqual(await recoverAppSolution(twoSolutionSdk(order, (u) => (u === 'ContosoApp' ? 'contoso' : 'fabrikam')), 'app-1'),+ { ambiguous: ['ContosoApp', 'ContosoRelease'] }, `row order ${order.join(',')}: the publishers disagree, so no prefix either`);+ assert.deepStrictEqual(await recoverAppSolution(twoSolutionSdk(order, () => 'contoso'), 'app-1'),+ { ambiguous: ['ContosoApp', 'ContosoRelease'], publisherPrefix: 'contoso' }, 'every candidate agrees on its publisher, so that prefix is still authoritative');+ assert.deepStrictEqual(await recoverAppSolution(twoSolutionSdk(order, (u) => (u === 'ContosoApp' ? new Error('boom') : 'contoso')), 'app-1'),+ { ambiguous: ['ContosoApp', 'ContosoRelease'], publisherUnreadable: 'boom' }, 'a failed read never counts as agreement, and is named');+ }+});++// A mock SDK for runDownload over an app in the two solutions above. Solution `a` (ContosoRelease) holds a+// business rule; `members` overrides the membership read (e.g. to make it fail); `order: ['b']` puts the app+// in the one solution ContosoApp.+function ambiguousAppSdk(APP_ID, APP_UNIQUE, { members, prefixOf = () => 'contoso', manyToMany = [], order = ['a', 'b'] } = {}) {+ const base = twoSolutionSdk(order, prefixOf);+ const RULE = '5111e0f2-0000-4000-8000-0000000000d9';+ return {+ fetchArtifact: async () => ({ name: 'Ambig', description: '', siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'Entity', entity: 'contoso_item' }] }] }] } }),+ queryRecords: async (logical, opts) => {+ const filter = (opts && opts.filter) || '';+ if (logical === 'appmodule') {+ const m = filter.match(/uniquename eq '([^']+)'/);+ if (m) return m[1] === APP_UNIQUE ? [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-0000000000d3' }] : [];+ return [{ appmoduleid: APP_ID, appmoduleidunique: 'c0ffee00-0000-4000-8000-0000000000d3', uniquename: APP_UNIQUE }];+ }+ if (logical === 'appmodulecomponent') return [{ objectid: '5111e0f2-0000-4000-8000-0000000000d2', componenttype: 62 }];+ if (logical === 'sitemap') return [{ sitemapxml: '<SiteMap><Area><Group><SubArea Entity="contoso_item"/></Group></Area></SiteMap>' }];+ if (logical === 'solutioncomponent' && filter === `objectid eq ${APP_ID}`) return members ? members() : base.queryRecords(logical, opts);+ if (logical === 'solution' && /solutionid eq/.test(filter)) return base.queryRecords(logical, opts);+ if (logical === 'solution') {+ const m = filter.match(/uniquename eq '([^']+)'/);+ return m ? [{ solutionid: { ContosoRelease: 'a', ContosoApp: 'b' }[m[1]] }].filter((r) => r.solutionid) : [];+ }+ if (logical === 'solutioncomponent' && filter === '_solutionid_value eq a and componenttype eq 29') return [{ objectid: RULE, componenttype: 29 }];+ if (logical === 'workflow') return [{ workflowid: RULE, name: 'Lock Closed', primaryentity: 'contoso_item', category: 2, type: 1 }];+ return [];+ },+ getSolution: base.getSolution,+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name', attributes: [] }),+ dataverse: { get: async (url) => ({ status: 200, headers: {}, body: { value: /ManyToManyRelationships/.test(url) ? manyToMany : [] } }) },+ };+}++async function runCapturing(sdk, APP_ID, APP_UNIQUE) {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-amb-'));+ const written = [];+ const origWrite = process.stderr.write;+ try {+ process.stderr.write = (chunk) => { written.push(String(chunk)); return true; };+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }), download: async () => true };+ const res = await runDownload({ sdk, genpageCli, outDir: out, appId: APP_ID, appUnique: APP_UNIQUE });+ return { res, written };+ } finally {+ process.stderr.write = origWrite;+ fs.rmSync(out, { recursive: true, force: true });+ }+}++test('runDownload does not guess between unmanaged solutions, and still reports what they hold (#587 item 9)', async () => {+ const APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000d1';+ // The app name's prefix differs from the publishers' on purpose, so the prefix below provably comes+ // from the agreeing publishers and not from the app-name guess.+ const APP_UNIQUE = 'zz_ambig';+ const { res, written } = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE), APP_ID, APP_UNIQUE);+ assert.ok(res.ok, JSON.stringify(res));+ assert.strictEqual(res.spec.solution.uniqueName, 'Default', 'no guess — and Default is the one solution a teardown never deletes');+ assert.strictEqual(res.spec.solution.publisherPrefix, 'contoso', 'every candidate shares this publisher, so its prefix survives the ambiguity');+ assert.deepStrictEqual(res.solutionCandidates, ['ContosoApp', 'ContosoRelease']);+ assert.ok(written.some((w) => /ContosoApp, ContosoRelease/.test(w) && /solution\.uniqueName/.test(w)), written.join(''));+ // Scoped by EVERY candidate: the rule in ContosoRelease is still reported. Scoping by the 'Default'+ // placeholder instead said "no business rules" without having looked.+ assert.deepStrictEqual(((res.spec.descriptionInventory || {}).businessRules || []).map((r) => r.name), ['Lock Closed']);+ assert.ok((res.notRoundTripped && res.notRoundTripped.classes || []).some((c) => c.kind === 'businessRules' && c.count === 1), JSON.stringify(res.notRoundTripped));+});++// With candidate solutions whose publishers disagree, the prefix is unknown. The app-name guess is the+// heuristic the ambiguity refuses to use, and a wrong prefix renamed every relationship not carrying it — so a+// same-environment rebuild created each a second time. The prefix stays the unverified default, relationships+// keep their deployed names, and the maker is told to set it.+test('runDownload does not guess a publisher prefix when the candidate solutions disagree', async () => {+ const APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000f1';+ // The app name carries 'contoso', the prefix of ONE candidate's publisher: exactly the guess refused here.+ const APP_UNIQUE = 'contoso_disagree';+ // One with a foreign prefix, and one that still has the name the build generated under its real prefix —+ // which must be carried too: omitted, a rebuild under the placeholder prefix generated another and created it twice.+ const { manyToManySchemaName } = require('../lib/app-spec.js');+ const generated = manyToManySchemaName({ entity1: 'contoso_item', entity2: 'contoso_item' }, 'contoso');+ const manyToMany = [+ { SchemaName: 'fabrikam_ItemItemLink', Entity1LogicalName: 'contoso_item', Entity2LogicalName: 'contoso_item', IsCustomRelationship: true },+ { SchemaName: generated, Entity1LogicalName: 'contoso_item', Entity2LogicalName: 'contoso_item', IsCustomRelationship: true },+ ];+ const sdk = ambiguousAppSdk(APP_ID, APP_UNIQUE, { prefixOf: (u) => (u === 'ContosoApp' ? 'contoso' : 'fabrikam'), manyToMany });+ const { res, written } = await runCapturing(sdk, APP_ID, APP_UNIQUE);+ assert.ok(res.ok, JSON.stringify(res));+ assert.deepStrictEqual(res.solutionCandidates, ['ContosoApp', 'ContosoRelease']);+ assert.strictEqual(res.spec.solution.publisherPrefix, 'new', 'not the app-name guess');+ assert.ok(written.some((w) => /do not share one customization prefix/.test(w) && /solution\.publisherPrefix/.test(w)), written.join(''));+ const nn = (res.spec.relationships || []).filter((r) => r.type === 'ManyToMany');+ assert.deepStrictEqual(nn.map((r) => r.schemaName).sort(), ['fabrikam_ItemItemLink', generated].sort(), `every deployed name is kept; got ${JSON.stringify(res.spec.relationships)}`);+ // With the membership unread the prefix is unknown too, and the generated name is carried the same way.+ const unread = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { members: () => { throw new Error('HTTP 503'); }, manyToMany: [manyToMany[1]] }), APP_ID, APP_UNIQUE);+ assert.deepStrictEqual((unread.res.spec.relationships || []).filter((r) => r.type === 'ManyToMany').map((r) => r.schemaName), [generated]);+ // CONTROL: publishers that agree still give their prefix, and a relationship with the generated name is+ // omitted as before, for the build to compose.+ const agreeing = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { manyToMany: [manyToMany[1]] }), APP_ID, APP_UNIQUE);+ assert.strictEqual(agreeing.res.spec.solution.publisherPrefix, 'contoso');+ assert.deepStrictEqual((agreeing.res.spec.relationships || []).filter((r) => r.type === 'ManyToMany').map((r) => r.schemaName), [undefined]);+ assert.ok(!agreeing.written.some((w) => /do not share one customization prefix/.test(w)));+});++// One solution, but its publisher could not be read: the prefix is unknown, as with disagreeing candidates.+// The failed read used to read as "no prefix", so the app-name guess was used — and when the real publisher is+// another, every relationship under its prefix was renamed to the generated name, and a same-environment+// rebuild created each a second time.+test('runDownload does not guess a publisher prefix when the one solution\'s publisher cannot be read', async () => {+ const APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000f2';+ // The app name carries 'contoso'; the relationship carries its publisher's real prefix, 'fabrikam'.+ const APP_UNIQUE = 'contoso_pubread';+ const manyToMany = [{ SchemaName: 'fabrikam_ItemItemLink', Entity1LogicalName: 'contoso_item', Entity2LogicalName: 'contoso_item', IsCustomRelationship: true }];+ const nn = (res) => (res.spec.relationships || []).filter((r) => r.type === 'ManyToMany').map((r) => r.schemaName);+ const unread = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { order: ['b'], prefixOf: () => new Error('HTTP 503 Service Unavailable'), manyToMany }), APP_ID, APP_UNIQUE);+ assert.ok(unread.res.ok, JSON.stringify(unread.res));+ assert.strictEqual(unread.res.solutionCandidates, undefined);+ assert.strictEqual(unread.res.spec.solution.uniqueName, 'ContosoApp', 'the solution itself was read');+ assert.strictEqual(unread.res.spec.solution.publisherPrefix, 'new', 'not the app-name guess');+ assert.ok(unread.written.some((w) => /the publisher of solution 'ContosoApp' could not be read \(HTTP 503/.test(w) && /solution\.publisherPrefix/.test(w)), unread.written.join(''));+ assert.deepStrictEqual(nn(unread.res), ['fabrikam_ItemItemLink'], 'the deployed name is kept, not renamed under the guess');+ // CONTROL: a publisher that is read gives its prefix, under which the deployed name is kept as well.+ const read = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { order: ['b'], prefixOf: () => 'fabrikam', manyToMany }), APP_ID, APP_UNIQUE);+ assert.strictEqual(read.res.spec.solution.uniqueName, 'ContosoApp');+ assert.strictEqual(read.res.spec.solution.publisherPrefix, 'fabrikam');+ assert.deepStrictEqual(nn(read.res), ['fabrikam_ItemItemLink']);+ assert.ok(!read.written.some((w) => /could not be read|solution\.publisherPrefix/.test(w)), read.written.join(''));+ // With several candidates, one of whose publishers could not be read, the warning says that — not that the+ // publishers disagree, which nobody knows.+ const several = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { prefixOf: (u) => (u === 'ContosoApp' ? new Error('HTTP 503') : 'fabrikam'), manyToMany }), APP_ID, APP_UNIQUE);+ assert.strictEqual(several.res.spec.solution.publisherPrefix, 'new');+ assert.ok(several.written.some((w) => /the publishers of those solutions could not all be read \(HTTP 503\)/.test(w)), several.written.join(''));+ assert.ok(!several.written.some((w) => /do not share one customization prefix/.test(w)), several.written.join(''));+});++test('runDownload reports an unreadable solution membership as unknown, not as "no solution"', async () => {+ const APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000e1';+ const APP_UNIQUE = 'contoso_unread';+ const members = () => { throw new Error('HTTP 503 Service Unavailable'); };+ const { res, written } = await runCapturing(ambiguousAppSdk(APP_ID, APP_UNIQUE, { members }), APP_ID, APP_UNIQUE);+ assert.ok(res.ok, JSON.stringify(res));+ assert.strictEqual(res.spec.solution.uniqueName, 'Default');+ assert.strictEqual(res.solutionCandidates, undefined);+ assert.ok(written.some((w) => /could not be read \(HTTP 503/.test(w) && /solution\.uniqueName/.test(w)), written.join(''));+ // With the solutions unread, the publisher is unknown too: the app-name guess ('contoso') is not used.+ assert.strictEqual(res.spec.solution.publisherPrefix, 'new');+ assert.ok(written.some((w) => /the publisher is unknown/.test(w) && /solution\.publisherPrefix/.test(w)), written.join(''));+ const unknown = ((res.notRoundTripped && res.notRoundTripped.incomplete) || []).map((i) => i.kind).sort();+ assert.deepStrictEqual(unknown.filter((k) => k === 'businessRules' || k === 'globalChoices'), ['businessRules', 'globalChoices'], JSON.stringify(res.notRoundTripped));});// ── OOB-table round-trip fixes (ADO 6603392 / 6603390 / 6603388) ───────────────────────────────@@ -1290,7 +1627,7 @@ test('recoverAppSolution recovers the publisher prefix from the SOLUTION, not thassert.deepStrictEqual(await recoverAppSolution(sdk, 'app-1'), { uniqueName: 'ContosoCustomerManagement', description: 'Customer management assets.', publisherPrefix: 'contoso' });});-test('recoverAppSolution degrades to uniqueName-only when the prefix cannot be recovered', async () => {+test('recoverAppSolution reports no prefix when none can be used, and names a publisher read that failed', async () => {const base = {queryRecords: async (set) => {if (set === 'solutioncomponent') return [{ _solutionid_value: 'sol-1' }];@@ -1300,8 +1637,8 @@ test('recoverAppSolution degrades to uniqueName-only when the prefix cannot be r};// (a) an older vendored bundle with no getSolution at allassert.deepStrictEqual(await recoverAppSolution(base, 'app-1'), { uniqueName: 'ContosoCustomerManagement' });- // (b) getSolution throws- assert.deepStrictEqual(await recoverAppSolution({ ...base, getSolution: async () => { throw new Error('boom'); } }, 'app-1'), { uniqueName: 'ContosoCustomerManagement' });+ // (b) getSolution throws: that is no answer about the publisher, so it is named — the caller must not guess+ assert.deepStrictEqual(await recoverAppSolution({ ...base, getSolution: async () => { throw new Error('boom'); } }, 'app-1'), { uniqueName: 'ContosoCustomerManagement', publisherUnreadable: 'boom' });// (c) a first-party publisher with no customization prefix -> not usable, so not reportedassert.deepStrictEqual(await recoverAppSolution({ ...base, getSolution: async () => ({ publisherPrefix: '' }) }, 'app-1'), { uniqueName: 'ContosoCustomerManagement' });});@@ -2254,6 +2591,8 @@ test('REVIEW-C runDownload emits ONLY referenced globalChoices (drives the realconst APP_ID = 'a1b2c3d4-0000-4000-8000-0000000000c1';const APP_UNIQUE = 'test_gcwiring';const SM_ID = '5111e0f2-0000-4000-8000-0000000000c2';+ const SOL_ID = '5111e0f2-0000-4000-8000-0000000000c4';+ const MID = { bound_set: '5111e0f2-0000-4000-8000-0000000000c5', orphan_set: '5111e0f2-0000-4000-8000-0000000000c6', unrelated_set: '5111e0f2-0000-4000-8000-0000000000c7' };const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-gc-'));try {const sdk = {@@ -2267,6 +2606,11 @@ test('REVIEW-C runDownload emits ONLY referenced globalChoices (drives the real}if (logical === 'appmodulecomponent') return [{ objectid: SM_ID, componenttype: 62 }];if (logical === 'sitemap') return [{ sitemapxml: '<SiteMap><Area><Group><SubArea Entity="contoso_item"/></Group></Area></SiteMap>' }];+ // The app's solution is recoverable and OWNS `orphan_set` (#586 item 5); `bound_set` is only+ // BOUND, so it can reach the inventory through the emitted column alone.+ if (logical === 'solutioncomponent' && filter === `objectid eq ${APP_ID}`) return [{ _solutionid_value: SOL_ID }];+ if (logical === 'solution') return [{ solutionid: SOL_ID, uniquename: 'GcSln', ismanaged: false }];+ if (logical === 'solutioncomponent' && /componenttype eq 9\b/.test(filter)) return [{ objectid: MID.orphan_set }];return [];},fetchEntityMetadata: async (logical) => ({@@ -2292,7 +2636,9 @@ test('REVIEW-C runDownload emits ONLY referenced globalChoices (drives the real{ LogicalName: 'sys_theirs', AttributeTypeName: { Value: 'PicklistType' } },] } };}- if (/GlobalOptionSetDefinitions/.test(url)) return { status: 200, headers: {}, body: { value: [] } };+ if (/GlobalOptionSetDefinitions/.test(url)) {+ return { status: 200, headers: {}, body: { value: Object.entries(MID).map(([Name, MetadataId]) => ({ Name, MetadataId, IsManaged: false })) } };+ }return { status: 200, headers: {}, body: {} };},},@@ -2304,6 +2650,19 @@ test('REVIEW-C runDownload emits ONLY referenced globalChoices (drives the real'a set bound only by a filtered SYSTEM attribute must not be declared — the build writes every declaration into the target org');const col = res.spec.entities[0].columns.find((c) => c.schemaName === 'contoso_mine');assert.strictEqual(col.globalChoice, 'bound_set');+ // The report subtracts what the spec DECLARES. `orphan_set` is a raw candidate (its metadata was+ // read) that is never declared, so subtracting the candidates hid it; and the org-wide+ // `unrelated_set` is not the app's at all (#586 item 5).+ const gc = ((res.notRoundTripped && res.notRoundTripped.orgScoped) || []).find((c) => c.kind === 'globalChoices');+ assert.deepStrictEqual(gc && gc.names, ['orphan_set'], JSON.stringify(res.notRoundTripped));+ // The inventory still carries the BOUND set (its description is kept) though the solution does+ // not own it — which is only possible if the wiring hands the emitted columns' bindings through.+ assert.deepStrictEqual(((res.spec.descriptionInventory || {}).globalChoices || []).map((g) => g.name).sort(), ['bound_set', 'orphan_set']);+ // And tearing down this downloaded spec RETAINS the set it declares, as it retains the tables —+ // an org-wide option set this download cannot prove the app created (#587 item 6).+ const { planTeardown } = require('../lib/sdk-teardown.js');+ const gcSteps = planTeardown(res.spec).filter((s) => s.kind === 'globalChoice');+ assert.deepStrictEqual(gcSteps.map((s) => [s.target.name, s.target.existing]), [['bound_set', true]]);// And the emitted spec must still validate.assert.deepStrictEqual(validateAppSpec(res.spec, { profile: 'plan' }).errors, []);} finally {diff --git a/plugins/model-apps/scripts/tests/download-relationships.test.js b/plugins/model-apps/scripts/tests/download-relationships.test.jsindex 8014b3c1a..26bc27648 100644--- a/plugins/model-apps/scripts/tests/download-relationships.test.js+++ b/plugins/model-apps/scripts/tests/download-relationships.test.js@@ -41,6 +41,8 @@ test('reconstructs a 1:N between two app tables with the properly-cased lookup nreferencing: 'new_ticket',// Cased as deployed — the SDK's own projection lowercases this to `new_customerid`.lookup: { schemaName: 'new_CustomerId', displayName: 'Customer' },+ // Ownership is unprovable from a download, so teardown must retain it like the tables (#587 item 6).+ existing: true,}]);});@@ -108,6 +110,13 @@ test('emits an explicit schemaName only when it diverges from the generated defa// beside the existing one instead of matching it.const diff = await readRelationships(mk('new_CustomerTicketLink'), ['new_customer', 'new_ticket'], 'new');assert.strictEqual(diff.relationships[0].schemaName, 'new_CustomerTicketLink');+ // With the publisher prefix UNKNOWN (the spec carries a placeholder), a name equal to the generated default+ // is carried too: omitted, a rebuild under the placeholder generated another name and created it twice. A+ // foreign-prefix name is carried as it is, not renamed.+ for (const deployed of ['new_customer_new_ticket', 'zzz_CustomerTicketLink']) {+ const unknown = await readRelationships(mk(deployed), ['new_customer', 'new_ticket'], 'new', undefined, { prefixUnknown: true });+ assert.strictEqual(unknown.relationships[0].schemaName, deployed, deployed);+ }});// An unreadable parent and a confirmed-custom parent are different facts. Collapsing them made a@@ -156,7 +165,7 @@ test('reconstructs N:N only when both ends are in the app, and reports the rest// `manyToManySchemaName` SORTS the pair, so it would compose `new_tag_new_ticket`. Without the// deployed name a rebuild into this environment creates a SECOND intersect relationship instead of// matching the existing one.- assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag', schemaName: 'new_ticket_new_tag' }]);+ assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag', schemaName: 'new_ticket_new_tag', existing: true }]);assert.strictEqual(skipped.length, 1);assert.match(skipped[0].reason, /does not include both tables/i);});@@ -174,7 +183,7 @@ test('an N:N is emitted once even though it appears on BOTH tables metadata (#56const r = rel({ SchemaName: 'new_ticket_new_tag', Entity1LogicalName: 'new_ticket', Entity2LogicalName: 'new_tag' });const sdk = makeSdk({ m2m: { new_ticket: [r], new_tag: [r] } });const { relationships } = await readRelationships(sdk, ['new_ticket', 'new_tag'], 'new');- assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag', schemaName: 'new_ticket_new_tag' }]);+ assert.deepStrictEqual(relationships, [{ type: 'ManyToMany', entity1: 'new_ticket', entity2: 'new_tag', schemaName: 'new_ticket_new_tag', existing: true }]);});test('a failed relationship read is REPORTED, not silently read as "this table has none" (#567)', async () => {diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex 7f3a827b2..1588777dd 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -857,6 +857,20 @@ test('requireSuccessfulPush halts on a result that carries an error but neitherassert.throws(() => requireSuccessfulPush(odd, 'chart c1'), (err) => err.name === 'BuildHalt');});+// Both spellings of the commit flag are read — `saved` first, the older bundle's `success` when `saved` is+// absent — and pushFailed is the one place that decides it, for the halt and for the app-header reset.+test('pushFailed reads saved, then the legacy success flag, then a bare error', () => {+ const { pushFailed } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));+ assert.strictEqual(pushFailed({ success: false }), true, 'an older bundle reporting a failure with no error object');+ assert.throws(() => requireSuccessfulPush({ type: 'app', id: 'a1', success: false }, 'app a1'), (err) => err.name === 'BuildHalt');+ assert.strictEqual(pushFailed({ saved: true, success: false }), false, '`saved` wins when both are present');+ assert.strictEqual(pushFailed({ saved: false }), true);+ assert.strictEqual(pushFailed({ success: true, error: new Error('partial') }), false, 'a committed push with a note is not a failure');+ assert.strictEqual(pushFailed({ error: new Error('boom') }), true);+ assert.strictEqual(pushFailed({}), false);+ assert.strictEqual(pushFailed(undefined), false);+});+// #447 regression net. The bug this fixes was a SINGLE label-emitting call that forgot to pass a// language, and it stayed invisible until a user in a German org filed a bug — CI runs offline mocks// and nobody's CI runs against a non-1033 org. So pinning only the two call sites that happened to bediff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.jsindex 0e4a49451..535212caf 100644--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js@@ -471,3 +471,22 @@ test('directEntry is defaulted ONLY where it is missing and actually required',assert.strictEqual(spec2.pages.find((p) => p.key === 'detail').directEntry, undefined,'the default tracks the validation condition exactly, not the mere presence of pageInput');});++// #583: the routing description round-trips when the deployed app has one. When it has none the field+// stays ABSENT — never `""` — because the build writes only a field the spec sets, so a download can+// never plant an empty value that a rebuild would then use to blank a platform-written description.+test('#583 hydrateSpec carries app.aiDescription only when the deployed app has one', async () => {+ const read = deployedRead();+ const app = await read.app();+ const withRouting = { ...read, app: async () => ({ ...app, aiDescription: 'Route order work here.' }) };+ assert.strictEqual((await hydrateSpec(withRouting)).app.aiDescription, 'Route order work here.');+ assert.ok(!('aiDescription' in (await hydrateSpec(deployedRead())).app));+ const blank = { ...read, app: async () => ({ ...app, aiDescription: '' }) };+ assert.ok(!('aiDescription' in (await hydrateSpec(blank)).app), 'an empty value is omitted, not emitted as ""');+ // Whitespace-only is non-empty to the SDK, which sets the key; emitting it would fail the whole+ // download, because validation refuses a blank routing description.+ for (const ws of [' ', '\n', ' \t\r\n ']) {+ const white = { ...read, app: async () => ({ ...app, aiDescription: ws }) };+ assert.ok(!('aiDescription' in (await hydrateSpec(white)).app), `whitespace-only ${JSON.stringify(ws)} is omitted`);+ }+});diff --git a/plugins/model-apps/scripts/tests/review-findings.test.js b/plugins/model-apps/scripts/tests/review-findings.test.jsindex fcfb4cb82..8337b2ddd 100644--- a/plugins/model-apps/scripts/tests/review-findings.test.js+++ b/plugins/model-apps/scripts/tests/review-findings.test.js@@ -288,10 +288,11 @@ test('#6a readDescriptionInventory RECORDS a per-class read failure', async () =},dataverse: { get: async () => ({ status: 404, headers: {}, body: {} }) },};- const inv = await readDescriptionInventory(sdk, APP, null);+ const inv = await readDescriptionInventory(sdk, APP, null, new Set(['contoso_status']));// `globalChoices` is now reported too: the stub answers that metadata read with a 404, and a// non-2xx is no longer coerced to an empty list. Before, it read as "this environment has no- // global choices" — a positive claim made from a failed read.+ // global choices" — a positive claim made from a failed read. (A column binding `contoso_status`+ // puts a set in scope, so the read is actually made; with nothing in scope it is skipped.)assert.deepStrictEqual((inv.incomplete || []).map((i) => i.kind).sort(), ['forms', 'globalChoices'], JSON.stringify(inv.incomplete));assert.match(inv.incomplete.find((i) => i.kind === 'forms').reason, /403/);// The class that DID read is still present — one failed query must not blank the others.@@ -308,17 +309,19 @@ test('#6a3 a non-2xx global-choice read is UNKNOWN, not "this environment has no// `notRoundTrippedSummary` started reporting global choices: a class it omits reads as absent.const { readDescriptionInventory } = require('../download-model-app.js');const base = { queryRecords: async () => [] };+ // A column binding `contoso_status` puts one set in scope, so the metadata read is actually made.+ const bound = new Set(['contoso_status']);for (const [label, get] of [['non-2xx', async () => ({ status: 403, headers: {}, body: {} })],['malformed body', async () => ({ status: 200, headers: {}, body: { notValue: 1 } })],['throws', async () => { throw new Error('socket hang up'); }],]) {- const inv = await readDescriptionInventory({ ...base, dataverse: { get } }, null, null);+ const inv = await readDescriptionInventory({ ...base, dataverse: { get } }, null, null, bound);assert.ok((inv.incomplete || []).some((i) => i.kind === 'globalChoices'),`${label}: expected globalChoices to be recorded as unknown, got ${JSON.stringify(inv.incomplete)}`);}// And a GOOD read records nothing.- const ok = await readDescriptionInventory({ ...base, dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [{ Name: 'contoso_status' }] } }) } }, null, null);+ const ok = await readDescriptionInventory({ ...base, dataverse: { get: async () => ({ status: 200, headers: {}, body: { value: [{ Name: 'contoso_status' }] } }) } }, null, null, bound);assert.ok(!(ok.incomplete || []).some((i) => i.kind === 'globalChoices'));assert.deepStrictEqual((ok.globalChoices || []).map((g) => g.name), ['contoso_status']);});@@ -389,7 +392,7 @@ test('#6a2 an unreadable app-component list marks EVERY class unknown', async ()queryRecords: async () => { throw new Error('HTTP 500'); },dataverse: { get: async () => ({ status: 500, headers: {}, body: {} }) },};- const inv = await readDescriptionInventory(sdk, '11111111-1111-1111-1111-111111111111', null);+ const inv = await readDescriptionInventory(sdk, '11111111-1111-1111-1111-111111111111', null, new Set(['contoso_status']));assert.deepStrictEqual((inv.incomplete || []).map((i) => i.kind).sort(), ['charts', 'forms', 'globalChoices', 'views']);});diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.jsindex 019af8f9e..849c58f45 100644--- a/plugins/model-apps/scripts/tests/sdk-build.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js@@ -97,6 +97,11 @@ function mockSdk(opts = {}) {calls.push({ name: 'queryRecords', args: [e, o] });const filter = (o && o.filter) || '';if (e === 'solution') return opts.solutionExists ? [{ solutionid: 's' }] : [];+ // Which dashboards the app's solution holds (componenttype 60 = systemform) — the ownership+ // evidence the build uses to pick among several same-named dashboards.+ if (e === 'solutioncomponent' && /componenttype eq 60/.test(filter)) {+ return (opts.dashboardsInSolution || []).filter((id) => filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));+ }// The chart description reconcile (#496) reads the deployed value before deciding to write, so// it must only PATCH when the spec's description actually differs.if (e === 'savedqueryvisualization') {@@ -164,6 +169,12 @@ function mockSdk(opts = {}) {return opts.noPublisher ? [] : [{ publisherid: 'pub-1' }];},// Artifact idempotency: reuse existing view/chart/form/app when opts.artifactsExist is set.+ // listArtifacts mirrors the real SDK's dirty flag (a local copy holding unpushed edits); a test marks+ // the existing app's copy dirty with `dirtyApp`.+ listArtifacts: async (kind) => {+ calls.push({ name: 'listArtifacts', args: [kind] });+ return kind === 'app' && opts.artifactsExist ? [{ type: 'app', id: 'app-existing', isDirty: !!opts.dirtyApp }] : [];+ },findArtifact: async (kind, identity) => {calls.push({ name: 'findArtifact', args: [kind, identity] });if (!opts.artifactsExist) return null;@@ -182,7 +193,9 @@ function mockSdk(opts = {}) {calls.push({ name: 'resolveArtifact', args: [kind, identity] });const out = [];if (kind === 'dashboard') {- for (const n of opts.existingDashboards || []) out.push({ id: `dashboard-existing-${n}`, name: n });+ // An entry is a name (id derived from it) or `{ id, name }` when a test needs same-named+ // dashboards with DIFFERENT ids.+ for (const n of opts.existingDashboards || []) out.push(typeof n === 'string' ? { id: `dashboard-existing-${n}`, name: n } : n);for (const k of Object.keys(store)) if (k.startsWith('dashboard:') && store[k].name) out.push({ id: store[k].id, name: store[k].name });return identity && identity.name != null ? out.filter((o) => o.name === identity.name) : out;}@@ -195,8 +208,14 @@ function mockSdk(opts = {}) {},createWebResource: async (o) => { calls.push({ name: 'createWebResource', args: [o] }); return { id: `wr-${++idc}`, name: o.name }; },updateWebResource: async (id, o) => { calls.push({ name: 'updateWebResource', args: [id, o] }); return {}; },- fetchArtifact: async (t, id) => {- calls.push({ name: 'fetchArtifact', args: [t, id] });+ fetchArtifact: async (t, id, o) => {+ calls.push({ name: 'fetchArtifact', args: o === undefined ? [t, id] : [t, id, o] });+ // `{ overwrite: true }` resets the local copy to the server's, as the real SDK does; a test can+ // make that reset fail with `failOverwriteFetch`.+ if (o && o.overwrite) {+ if (opts.failOverwriteFetch) throw new Error('fetch failed: network down');+ delete store[`${t}:${id}`];+ }// Seed the store to mimic a fetched, deployed artifact so reconcile can read + mutate it.if (!store[`${t}:${id}`]) {// `existingFormJson` overrides the single-tab default so a test can seed a deployed form@@ -210,7 +229,7 @@ function mockSdk(opts = {}) {// when its pointer resolves to undefined, whereas this mock's jpSet would happily create the// key. Omitting it would let a test pass against an artifact the SDK would have rejected.else if (t === 'view') store[`${t}:${id}`] = { id, columns: (opts.existingViewColumns || []).slice(), description: opts.existingViewDescription !== undefined ? opts.existingViewDescription : '' };- else if (t === 'app') store[`${t}:${id}`] = { id, siteMap: opts.existingSitemap ? JSON.parse(JSON.stringify(opts.existingSitemap)) : { areas: [] } };+ else if (t === 'app') store[`${t}:${id}`] = { id, siteMap: opts.existingSitemap ? JSON.parse(JSON.stringify(opts.existingSitemap)) : { areas: [] }, ...(opts.existingAppAiDescription ? { aiDescription: opts.existingAppAiDescription } : {}) };// The chart description reconcile reads through fetchArtifact/getArtifact rather than// queryRecords, because a plain query returns the PUBLISHED row while the PATCH writes the// unpublished one (measured live). Seed `description` for the same reason as the view.@@ -284,12 +303,28 @@ function mockSdk(opts = {}) {const n = arr.findIndex((x) => x && x.id === pos.after); at = n < 0 ? arr.length : n + 1;} else throw new TypeError(`Cannot use 'in' operator to search for 'index' in ${pos}`);arr.splice(at, 0, clone(el));+ } else if (arr !== null && typeof arr === 'object' && el !== null && typeof el === 'object' && !Array.isArray(el)) {+ // An OBJECT parent: the real SDK adds each property of `el` (refusing `id` and `position`),+ // which is how a key the fetched artifact lacks — the app's `aiDescription` — gets added.+ if (opts && opts.position !== undefined) throw new Error('position is not supported for an object parent');+ for (const k of Object.keys(el)) {+ if (k === 'id') throw new Error("refusing to write 'id' — that re-keys the node rather than adding a property");+ arr[k] = clone(el[k]);+ }}return clone(art);},updateElement: async (t, id, ptr, patch) => { await Promise.resolve();calls.push({ name: 'updateElement', args: [t, id, ptr, patch] });const art = store[`${t}:${id}`] || (store[`${t}:${id}`] = { id });+ // The real SDK THROWS PathNotFoundError when the pointer resolves to nothing. Modelled here for+ // the app's `aiDescription` — which a fetched app carries only when the row has one — because+ // the build's routing-description write depends on that failure to fall back to addElement.+ if (t === 'app' && ptr === '/aiDescription' && jpGet(art, ptr) === undefined) {+ const e = new Error(`Path ${ptr} not found in ${t}/${id}`);+ e.code = 'PATH_NOT_FOUND';+ throw e;+ }// The real SDK MERGES when the current value and the patch are BOTH plain objects, and// replaces otherwise: `Xu(o) && Xu(i) ? {...o, ...i} : i`.// Measured against the vendored bundle: updateElement('/…/cells/0/control', {isReadOnly:true})@@ -325,7 +360,15 @@ function mockSdk(opts = {}) {return clone(art || { id });},updateRecord: async (e, id, data) => { calls.push({ name: 'updateRecord', args: [e, id, data] }); },- pushArtifact: async (t, id) => { calls.push({ name: 'pushArtifact', args: [t, id] }); return { type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }; },+ // `appPushResult` lets a test answer an APP push the way the real SDK answers a 412: it RESOLVES with+ // `saved:false` and a VERSION_CONFLICT error rather than throwing. `appPushThrows` is the other shape:+ // refusals the SDK THROWS (a never-published app's header, a sitemap target that no longer exists).+ pushArtifact: async (t, id) => {+ calls.push({ name: 'pushArtifact', args: [t, id] });+ if (t === 'app' && opts.appPushThrows) throw Object.assign(new Error(`push refused: ${opts.appPushThrows}`), { code: opts.appPushThrows });+ if (t === 'app' && opts.appPushResult) return { type: t, id, ...opts.appPushResult };+ return { type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } };+ },addSolutionComponent: async (o) => { calls.push({ name: 'addSolutionComponent', args: [o] }); },publishArtifact: async (t, id) => {calls.push({ name: 'publishArtifact', args: [t, id] });@@ -576,6 +619,386 @@ test('sitemap: an existing (edit) app also gets its sitemap added to the solutioassert.ok(find(calls, 'addSolutionComponent').some((c) => c.args[0].componentType === 62 && c.args[0].componentId === 'sm-1'), 'sitemap added to solution on the edit path too');});+// #583: the routing description (`app.aiDescription` → appmodule.aiappdescription). Written at create;+// on an existing app only when the spec sets one that differs from the FETCHED artifact; never blanked+// and never written when the spec omits it (the platform can author this text itself).+const ROUTING = 'Dispatch work: assigning and rescheduling tickets. Prefer My Work for your own assigned items.';+const appShellPhases = ['solution', 'data-model', 'app-shell'];+const appCalls = (calls, name, pred = () => true) => find(calls, name).filter((c) => c.args[0] === 'app' && pred(c));++test('#583 appDef carries app.aiDescription only when the spec sets one', () => {+ const built = { forms: {}, views: {}, charts: {}, dashboards: {} };+ assert.ok(!('aiDescription' in appDef(makeSpec(), built)));+ assert.strictEqual(appDef(makeSpec({ app: { name: 'Support Desk', aiDescription: ROUTING } }), built).aiDescription, ROUTING);+});++test('#583 a new app is created with its routing description', async () => {+ const { sdk, calls } = mockSdk();+ await runSdkBuild(makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } }), { sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(appCalls(calls, 'createArtifact')[0].args[1].aiDescription, ROUTING);+});++test('#583 an existing app without one gets it added, on the same push as its sitemap', async () => {+ // The mock's updateElement THROWS PATH_NOT_FOUND for an absent `/aiDescription`, as the real SDK does,+ // so this also proves the key is added rather than "updated" onto a path that is not there.+ const { sdk, calls } = mockSdk({ artifactsExist: true });+ await runSdkBuild(makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } }), { sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);+ const added = appCalls(calls, 'addElement', (c) => c.args[2] === '');+ assert.deepStrictEqual(added.map((c) => c.args[3]), [{ aiDescription: ROUTING }], 'added at the artifact root');+ // One push: the sitemap rewrite carries the new field. A second push from the same fetch would race+ // the first on the row's If-Match.+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1);+ const addAt = calls.indexOf(added[0]);+ assert.ok(addAt < calls.indexOf(appCalls(calls, 'pushArtifact')[0]), 'added before the push that writes it');+ assert.ok(calls.indexOf(appCalls(calls, 'fetchArtifact')[0]) < calls.indexOf(appCalls(calls, 'getArtifact')[0]), 'compared against the FETCHED artifact');+});++test('#583 an existing app with a different routing description is updated in place', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppAiDescription: 'Old routing text.' });+ await runSdkBuild(makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } }), { sdk, apply: true, phases: appShellPhases });+ assert.deepStrictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').map((c) => c.args[3]), [ROUTING]);+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0);+});++test('#583 an existing app whose routing description already matches is left alone', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppAiDescription: ROUTING });+ await runSdkBuild(makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } }), { sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0);+});++test('#583 a spec with no routing description never reads or writes one', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingAppAiDescription: 'Written by the platform.' });+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(appCalls(calls, 'getArtifact').length, 0, 'not even read');+ assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0);+});++test('#583 when the sitemap write is deferred, the routing description is pushed on its own', async () => {+ // A page subarea defers the existing app's sitemap write to the pages finalizer, which does not run+ // in an app-shell-only build, so the routing description needs its own push or it never lands.+ const spec = makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } });+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });+ const { sdk, calls } = mockSdk({ artifactsExist: true });+ await runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/siteMap').length, 0, 'the sitemap write is deferred');+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 1);+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 1, 'one push carries the routing description');+ assert.strictEqual(appCalls(calls, 'publishArtifact').length, 1);+});++// That push re-sends the workspace copy's sitemap, which is the live one only while the copy is clean: a+// plain fetch returns a copy holding an earlier run's unpushed sitemap rewrite unchanged, and pushing it+// replayed the rewrite — detaching live pages with no gate. A dirty copy is refused before anything is+// applied; a spec with no routing description never looks.+test('#583 the deferred routing-description push refuses a copy holding an earlier run\u2019s unpushed edits', async () => {+ const spec = makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } });+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });+ const { sdk, calls } = mockSdk({ artifactsExist: true, dirtyApp: true });+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'app-copy-unpushed-edits', e.message);+ assert.match(e.message, /holds edits an earlier run did not push/);+ return true;+ });+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0, 'nothing applied');+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 0, 'nothing pushed');+ // …even when the copy already carries the wanted routing description: that may be the very edit the+ // earlier run failed to push, so "unchanged" against the copy is no proof the server has it.+ const same = mockSdk({ artifactsExist: true, dirtyApp: true, existingAppAiDescription: ROUTING });+ await assert.rejects(runSdkBuild(spec, { sdk: same.sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'app-copy-unpushed-edits');+ assert.strictEqual(appCalls(same.calls, 'pushArtifact').length, 0, 'nothing pushed');+ const noRouting = makeSpec();+ noRouting.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });+ const quiet = mockSdk({ artifactsExist: true, dirtyApp: true });+ await runSdkBuild(noRouting, { sdk: quiet.sdk, apply: true, phases: appShellPhases });+ assert.strictEqual(find(quiet.calls, 'listArtifacts').length, 0, 'without a routing description there is nothing to push');+});++// #583: the SDK refuses a header write with a 412 while an earlier header change is unpublished, and the+// generic remedy (re-download) cannot clear that. The explanation is keyed on a PROVEN draft only. The+// error is shaped as the real bundle returns it: `detail` names the refused request (pinned in+// app-ai-description-real-bundle.test.js), and the message carries it too.+const conflictOn = (row) => {+ const detail = `Version conflict (412) from https://contoso.crm.dynamics.com/api/data/v9.2/${row}`;+ return { saved: false, shipped: false, publish: { kind: 'notRequested' }, error: Object.assign(new Error(`Version conflict for app/x: local=W/"2", server=(none). Re-fetch and reapply changes. ${detail}`), { code: 'VERSION_CONFLICT', detail }) };+};+const HEADER_412 = conflictOn('appmodules(x)');+// The SDK writes the header first, then the sitemap: a 412 on the SITEMAP comes after this push's own+// header write committed, and so over the very unpublished layer the header state is proven by.+const SITEMAP_412 = conflictOn('sitemaps(y)');+// Models ONLY the app draft read. The data-model phase's narrow metadata reads also go through+// `dataverse.get`; a failed read is the input each of them already tolerates (they fall back to+// findTables/findColumns/fetchEntityMetadata), so they are handed one rather than a fake draft row.+const draftReader = (answer, seen = []) => ({ get: async (url) => {+ if (!/^\/appmodules\//.test(url)) throw new Error(`not modelled by this test: ${url}`);+ seen.push(url);+ if (answer instanceof Error) throw answer;+ return answer;+} });+const routingSpec = () => makeSpec({ app: { name: 'Support Desk', description: 'Tickets', aiDescription: ROUTING } });++test('#583 a 412 over an unpublished header change halts with the step that works', async () => {+ // The last case puts the PUBLISHED row first: the unpublished layer must be found wherever it is.+ for (const [deferred, value] of [[false, [{ componentstate: 1 }]], [true, [{ componentstate: 1 }]], [false, [{ componentstate: 0 }, { componentstate: 1 }]]]) {+ const spec = routingSpec();+ if (deferred) spec.appShell.areas[0].groups[0].subAreas.push({ page: 'Overview', title: 'Overview' });+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });+ const seen = [];+ sdk.dataverse = draftReader({ status: 200, body: { value } }, seen);+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'app-header-unpublished', `${deferred ? 'deferred' : 'sitemap'} path, rows ${JSON.stringify(value)}: ${e.message}`);+ assert.match(e.message, /unpublished change to its name, description or routing description/);+ assert.match(e.message, /publish the app in Power Apps \(or discard the change\), then re-run the build\.$/);+ return true;+ });+ assert.strictEqual(seen.length, 1);+ assert.match(seen[0], /^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)\?\$select=componentstate&\$filter=appmoduleid eq \S+$/);+ assert.strictEqual(appCalls(calls, 'publishArtifact').length, 0, 'nothing is published after the refused push');+ // The refused push left this run's edits in the workspace copy; it is reset so the re-run's plain+ // fetch is not refused with LOCAL_EDITS_WOULD_BE_LOST once the operator has published.+ const resets = appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true);+ assert.strictEqual(resets.length, 1, 'the workspace copy is reset');+ assert.ok(calls.indexOf(resets[0]) > calls.indexOf(appCalls(calls, 'pushArtifact')[0]), 'after the refused push');+ }+});++test('#583 when the workspace copy cannot be reset, the halt names the workspace to delete', async () => {+ const { sdk } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412, failOverwriteFetch: true });+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'app-header-unpublished', e.message);+ assert.match(e.message, /then re-run the build\. First delete the \.maker-workspace directory \(or the --workspace one\)/);+ return true;+ });+});++test('#583 any other 412 keeps the generic re-download halt', async () => {+ for (const [what, answer] of [+ ['a settled row', { status: 200, body: { value: [{ componentstate: 0 }] } }],+ ['no row', { status: 200, body: { value: [] } }],+ ['a non-2xx draft read, whatever its body', { status: 500, body: { value: [{ componentstate: 1 }] } }],+ ['a failed draft read', new Error('network down')],+ ]) {+ const { sdk } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });+ sdk.dataverse = draftReader(answer);+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'version-conflict', `${what}: ${e.message}`);+ return true;+ });+ }+});++test('#583 a push refused for another reason keeps its own halt, even over a pending draft', async () => {+ const refused = { ...HEADER_412, error: Object.assign(new Error('a row already exists at that id'), { code: 'ARTIFACT_ALREADY_EXISTS' }) };+ const { sdk } = mockSdk({ artifactsExist: true, appPushResult: refused });+ const seen = [];+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } }, seen);+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'already-exists');+ assert.strictEqual(seen.length, 0, 'only a VERSION_CONFLICT is re-diagnosed');+});++// The halt reads a push result the way requireSuccessfulPush does: `saved`, then the older SDK spelling+// `success`. Reading `saved` alone sent a legacy-shaped refusal to the generic conflict remedy.+test('#583 the unpublished-header halt reads the older `success` result shape as well', async () => {+ const legacy = { success: false, error: HEADER_412.error };+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: legacy });+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'app-header-unpublished', e.message);+ return true;+ });+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1, 'and resets the copy');+});++// Only the APPMODULE row's 412 can be the unpublished-header state. A sitemap 412 is a concurrent sitemap+// edit, over the unpublished layer this very push's header write just left — relabelling it reset the copy,+// and "publish, then re-run" then overwrote the other edit. So is a conflict that names no request at all.+test('#583 a 412 that is not the appmodule row\u2019s keeps the generic halt and the copy, over a pending draft too', async () => {+ const unnamed = { ...HEADER_412, error: Object.assign(new Error('Version conflict for app/x: local=W/"2", server=W/"3". Re-fetch and reapply changes.'), { code: 'VERSION_CONFLICT' }) };+ for (const [what, result] of [['a sitemap 412', SITEMAP_412], ['a conflict naming no request', unnamed]]) {+ for (const phases of [appShellPhases, fullPhases]) {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: result });+ const seen = [];+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } }, seen);+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases, genpageCli: noPages }), (e) => {+ assert.strictEqual(e.code, 'version-conflict', `${what}, ${phases.join(',')}: ${e.message}`);+ return true;+ });+ assert.strictEqual(seen.length, 0, `${what}: not re-diagnosed, so no draft read`);+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 0, `${what}: the copy is kept as the fence`);+ }+ }+});++// With the pages phase in the run — every CLI apply — the finalizer is the only existing-app sitemap+// writer, so the routing description must ride ITS push. An app-shell push would re-send the live+// sitemap, which the SDK validates reference by reference: a subarea whose page was deleted in Maker+// would halt the run before the pages phase could drop it.+const fullPhases = ['solution', 'data-model', 'app-shell', 'pages'];+const noPages = { enumerateEnv: async () => ({ ok: true, ids: [] }) };++test('#583 with the pages phase, the routing description rides the finalizer push — app-shell pushes nothing', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true });+ await runSdkBuild(routingSpec(), { sdk, apply: true, phases: fullPhases, genpageCli: noPages });+ const pushes = appCalls(calls, 'pushArtifact');+ const fetches = appCalls(calls, 'fetchArtifact');+ assert.strictEqual(pushes.length, 1, 'one app push in the whole run');+ assert.strictEqual(fetches.length, 2, 'app-shell fetches, the finalizer re-fetches');+ const added = appCalls(calls, 'addElement', (c) => c.args[2] === '');+ assert.deepStrictEqual(added.map((c) => c.args[3]), [{ aiDescription: ROUTING }]);+ const at = (c) => calls.indexOf(c);+ assert.ok(at(fetches[1]) < at(added[0]) && at(added[0]) < at(pushes[0]), 'applied after the finalizer fetch, before its push');+ assert.ok(at(pushes[0]) > at(appCalls(calls, 'updateElement', (c) => c.args[2] === '/siteMap')[0]), 'on the same push as the finalized sitemap');+});++test('#583 the finalizer push halts precisely over an unpublished header change, after resetting the copy', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: fullPhases, genpageCli: noPages }), (e) => {+ assert.strictEqual(e.code, 'app-header-unpublished', e.message);+ assert.match(e.message, /^pages failed: push app Support Desk failed: the app has an unpublished change/);+ return true;+ });+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1);+});++// #583 review: a copy an earlier run left holding unpushed edits went out with the next push of the app, whatever+// that run asked for — a routing description the spec left out was overwritten with the earlier run's, and a+// wanted one read as already set. Every run that pushes the app refuses such a copy before it applies anything.+test('#583 a build that pushes the app refuses a copy holding an earlier run\u2019s unpushed edits, before applying anything', async () => {+ for (const spec of [makeSpec(), routingSpec()]) {+ const { sdk, calls } = mockSdk({ artifactsExist: true, dirtyApp: true });+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: fullPhases, genpageCli: noPages }), (e) => {+ assert.strictEqual(e.code, 'app-copy-unpushed-edits', e.message);+ assert.match(e.message, /holds edits an earlier run did not push/);+ return true;+ });+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 0, 'nothing pushed');+ assert.strictEqual(appCalls(calls, 'updateElement').length + appCalls(calls, 'addElement').length, 0, 'nothing applied');+ }+ // …and so does an app-shell run of a page-less app, whose sitemap push would carry them.+ const pageLess = mockSdk({ artifactsExist: true, dirtyApp: true });+ await assert.rejects(runSdkBuild(makeSpec(), { sdk: pageLess.sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'app-copy-unpushed-edits');+ assert.strictEqual(appCalls(pageLess.calls, 'updateElement', (c) => c.args[2] === '/siteMap').length, 0);+ // CONTROL: a clean copy builds, with the one finalizer push.+ const clean = mockSdk({ artifactsExist: true });+ await runSdkBuild(makeSpec(), { sdk: clean.sdk, apply: true, phases: fullPhases, genpageCli: noPages });+ assert.strictEqual(appCalls(clean.calls, 'pushArtifact').length, 1);+});++// A failed push of the app resets the copy even when it carried no header change: the edits are projected from+// the spec and the re-run re-applies them, so a failure no longer leaves a copy the next run must refuse. A+// concurrent edit keeps it — that copy is what stops a blind re-run from overwriting the other edit.+test('#583 a failed app push resets the workspace copy, header change or not — except a concurrent edit', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushThrows: 'ECONNRESET' });+ await assert.rejects(runSdkBuild(makeSpec(), { sdk, apply: true, phases: fullPhases, genpageCli: noPages }));+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1, 'the copy is reset');+ // …and a failure the SDK RETURNS by value, with a code that is no concurrent edit.+ const returned = mockSdk({ artifactsExist: true, appPushResult: { saved: false, error: Object.assign(new Error('sitemap target not found'), { code: 'SITEMAP_TARGET_NOT_FOUND' }) } });+ await assert.rejects(runSdkBuild(makeSpec(), { sdk: returned.sdk, apply: true, phases: fullPhases, genpageCli: noPages }));+ assert.strictEqual(appCalls(returned.calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1, 'a returned failure resets it too');+ const conflict = mockSdk({ artifactsExist: true, appPushResult: SITEMAP_412 });+ await assert.rejects(runSdkBuild(makeSpec(), { sdk: conflict.sdk, apply: true, phases: fullPhases, genpageCli: noPages }));+ assert.strictEqual(appCalls(conflict.calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 0, 'a concurrent edit keeps it');+});++test('#583 a never-published app\u2019s THROWN refusal halts the same way, after resetting the copy', async () => {+ for (const phases of [appShellPhases, fullPhases]) {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushThrows: 'APP_DRAFT_HEADER_NOT_WRITABLE' });+ const seen = [];+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } }, seen);+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases, genpageCli: noPages }), (e) => {+ assert.strictEqual(e.code, 'app-header-unpublished', `${phases.join(',')}: ${e.message}`);+ assert.match(e.message, /the app has never been published, and Dataverse refuses a write to its name, description or routing description until it is\. .*: publish the app in Power Apps, then re-run the build\.$/);+ return true;+ });+ assert.strictEqual(seen.length, 0, 'the SDK\u2019s own code proves the state; no draft read');+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1, 'the copy is reset');+ }+});++// A push that carried the routing change and failed for any reason but a concurrent edit left that change+// unrecorded in the workspace copy — where the re-run's plain fetch refuses it once the server moves, and+// where applyAppAiDescription (which reads the copy) mistakes it for "already set". So the copy is reset+// before the error propagates — unchanged. Without a routing change it is reset too: the sitemap edit it holds+// is projected from the spec as well, and a copy left holding it would be refused by the next run that pushes+// the app (refuseUnpushedAppCopy).+test('#583 any other thrown push error propagates unchanged, and resets the copy, routing change or not', async () => {+ for (const [what, spec, resets] of [['with a routing change', routingSpec(), 1], ['without one', makeSpec(), 1]]) {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushThrows: 'SITEMAP_TARGET_NOT_FOUND' });+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } });+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, 'SITEMAP_TARGET_NOT_FOUND', `${what}: ${e.message}`);+ return true;+ });+ const overwrite = appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true);+ assert.strictEqual(overwrite.length, resets, `${what}: ${resets ? 'the copy is reset' : 'no reset'}`);+ if (resets) assert.ok(calls.indexOf(overwrite[0]) > calls.indexOf(appCalls(calls, 'pushArtifact')[0]), 'after the failed push');+ }+ // A reset that itself fails leaves the error exactly as it was.+ const { sdk } = mockSdk({ artifactsExist: true, appPushThrows: 'SITEMAP_TARGET_NOT_FOUND', failOverwriteFetch: true });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'SITEMAP_TARGET_NOT_FOUND');+ // A THROWN failure with no code (the connection dropped mid-push) resets too: the code-less 412 that+ // keeps the copy is one the SDK RETURNS by value.+ const dropped = mockSdk({ artifactsExist: true });+ const push = dropped.sdk.pushArtifact;+ dropped.sdk.pushArtifact = async (t, id) => {+ if (t !== 'app') return push(t, id);+ dropped.calls.push({ name: 'pushArtifact', args: [t, id] });+ throw new Error('socket hang up');+ };+ await assert.rejects(runSdkBuild(routingSpec(), { sdk: dropped.sdk, apply: true, phases: appShellPhases }), (e) => /socket hang up/.test(e.message));+ assert.strictEqual(appCalls(dropped.calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1);+});++test('#583 a returned push failure resets the copy, but a concurrent edit keeps it as the fence', async () => {+ const withCode = (code, message) => ({ saved: false, shipped: false, publish: { kind: 'notRequested' }, error: Object.assign(new Error(message), code ? { code } : {}) });+ for (const [what, result, haltCode, resets] of [+ ['a failure with its own code', withCode('SITEMAP_REFERENCE_UNRESOLVED', 'subarea target missing'), 'SITEMAP_REFERENCE_UNRESOLVED', 1],+ // requireSuccessfulPush asks for a fresh download on these; the unrecorded copy is what stops a blind+ // re-run from overwriting the other edit.+ ['a VERSION_CONFLICT on a settled row', HEADER_412, 'version-conflict', 0],+ ['a code-less 412', withCode(null, 'version conflict (412)'), 'version-conflict', 0],+ ]) {+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: result });+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 0 }] } });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {+ assert.strictEqual(e.code, haltCode, `${what}: ${e.message}`);+ return true;+ });+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, resets, what);+ }+ // `success` (the older SDK spelling) is read the same way as `saved`.+ const legacy = { success: false, error: Object.assign(new Error('subarea target missing'), { code: 'SITEMAP_REFERENCE_UNRESOLVED' }) };+ const { sdk, calls } = mockSdk({ artifactsExist: true, appPushResult: legacy });+ await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'SITEMAP_REFERENCE_UNRESOLVED');+ assert.strictEqual(appCalls(calls, 'fetchArtifact', (c) => c.args[2] && c.args[2].overwrite === true).length, 1);+});++// Without the pages phase the live-page gate guards the page-less sitemap write. The routing description+// used to be applied BEFORE it, so a gate that halted left the edit unrecorded in the workspace copy.+test('#583 without the pages phase, a live-page gate that halts leaves no routing edit behind', async () => {+ const spec = routingSpec();+ const appUnique = appUniqueName(spec);+ const sm = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}"/></Group></Area></SiteMap>`; // the live app HAS a genpage+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingSitemap: PRIOR_SITEMAP, selfAppUnique: appUnique, liveSitemapXml: sm });+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true, env: 'https://x', phases: appShellPhases }), (e) => e && e.phase === 'app-shell' && e.code === 'pages-removed');+ assert.strictEqual(appCalls(calls, 'getArtifact').length, 0, 'not even compared');+ assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0);+ assert.strictEqual(appCalls(calls, 'updateElement', (c) => c.args[2] === '/aiDescription').length, 0);+ assert.strictEqual(appCalls(calls, 'pushArtifact').length, 0);+});++test('#583 a 412 on a push that carries no routing change is never re-diagnosed', async () => {+ const { sdk } = mockSdk({ artifactsExist: true, appPushResult: HEADER_412 });+ const seen = [];+ sdk.dataverse = draftReader({ status: 200, body: { value: [{ componentstate: 1 }] } }, seen);+ await assert.rejects(runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => e.code === 'version-conflict');+ assert.strictEqual(seen.length, 0, 'the draft is not even read');+});+test('Tier 1 data model: global choices, rich column types, customer, status, alt keys, N:N', async () => {const spec = makeSpec();spec.globalChoices = [{ name: 'new_severity', displayName: 'Severity', options: ['Low', 'High'] }];@@ -1215,6 +1638,106 @@ test('dashboards: an existing dashboard is reused (no duplicate) and reported inassert.ok(find(calls, 'resolveArtifact').some((c) => c.args[0] === 'dashboard' && c.args[1].name === 'Ops'), 'discovered via resolveArtifact');});+// Names are neither unique nor compared exactly, so the lookup can return several dashboards. Reusing+// the first one returned silently bound the app to an arbitrary one — possibly another app's. The app's+// own is the one its solution holds; when that does not single one out the build halts, creating nothing.+test('dashboards: several dashboards matching the name halt the build unless the solution singles one out', async () => {+ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const halts = [+ ['no solution to ask', { existingDashboards: ['Ops', 'Ops'] }, /cannot say which is its own/],+ ['none in the solution', { existingDashboards: [{ id: 'd-1', name: 'Ops' }, { id: 'd-2', name: 'Ops' }], solutionExists: true, dashboardsInSolution: [] }, /none of them is in this app's solution/],+ ['two in the solution', { existingDashboards: [{ id: 'd-1', name: 'Ops' }, { id: 'd-2', name: 'Ops' }], solutionExists: true, dashboardsInSolution: ['d-1', 'd-2'] }, /2 of them are in this app's solution/],+ ];+ for (const [what, opts, why] of halts) {+ const { sdk, calls } = mockSdk(opts);+ await assert.rejects(runSdkBuild(spec, { sdk, apply: true }), (err) => /2 dashboards in this environment match the name 'Ops'/.test(err.message) && why.test(err.message) && /Rename or delete the extra ones/.test(err.message), what);+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'), `${what}: no dashboard is created beside them`);+ }+});++test('dashboards: among several same-named dashboards the build reuses the one its solution holds', async () => {+ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ // The foreign one is returned FIRST, so the old "reuse existing[0]" would have adopted it.+ const { sdk, calls } = mockSdk({ existingDashboards: [{ id: 'd-foreign', name: 'Ops' }, { id: 'd-ours', name: 'Ops' }], solutionExists: true, dashboardsInSolution: ['d-ours'] });+ const result = await runSdkBuild(spec, { sdk, apply: true });+ assert.strictEqual(result.created.dashboards.Ops, 'd-ours');+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'), 'reused, not duplicated');+});++// A LONE match is still reused: a downloaded app's dashboard may never have joined the solution the+// download recovered. But when the solution does not hold it, nothing proves it is this app's rather than+// another app's namesake, so the build says so — never when the solution holds it, when there is no real+// solution to ask, or when the read fails.+test('dashboards: a lone same-named dashboard outside the solution is reused, with a warning', async () => {+ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const lone = [{ id: 'd-1', name: 'Ops' }];+ for (const [what, opts, warned, failRead] of [+ ['outside the solution', { existingDashboards: lone, solutionExists: true, dashboardsInSolution: [] }, true],+ ['in the solution', { existingDashboards: lone, solutionExists: true, dashboardsInSolution: ['d-1'] }, false],+ ['no solution to ask', { existingDashboards: lone }, false],+ ['a membership read that fails', { existingDashboards: lone, solutionExists: true, dashboardsInSolution: [] }, false, true],+ ]) {+ const { sdk, calls } = mockSdk(opts);+ if (failRead) {+ const query = sdk.queryRecords;+ sdk.queryRecords = async (set, q) => { if (set === 'solutioncomponent') throw new Error('read refused'); return query(set, q); };+ }+ const warnings = [];+ const result = await runSdkBuild(spec, { sdk, apply: true, warn: (m) => warnings.push(m) });+ assert.strictEqual(result.created.dashboards.Ops, 'd-1', `${what}: reused`);+ assert.ok(!find(calls, 'createArtifact').some((c) => c.args[0] === 'dashboard'), `${what}: not duplicated`);+ assert.strictEqual(warnings.some((w) => /dashboard "Ops": the one dashboard with this name is not in this app's solution/.test(w)), warned, `${what}: ${JSON.stringify(warnings)}`);+ }+});++// The vendored name lookup reads one page of ten, in no defined order, so with more matches the app's+// own dashboard can sort beyond it — and reuse, verify and teardown would all decide without it. A full+// page is re-read in full, and membership is then asked in bounded chunks.+test('dashboards: a full lookup page is re-read in full, so the app\'s own cannot hide beyond it', async () => {+ const { findDashboardsByName, dashboardsInSolution } = require('../lib/sdk-build.js');+ const foreign = Array.from({ length: 10 }, (_, i) => ({ id: `d-foreign-${i}`, name: 'Ops' }));+ const all = [...foreign, { id: 'd-ours', name: 'Ops' }];+ const asRows = () => all.map((d) => ({ formid: d.id, name: d.name }));+ const reads = [];+ const sdkWith = (page) => ({+ resolveArtifact: async () => page,+ queryRecords: async (set, q) => { reads.push(q); return set === 'systemform' ? asRows() : []; },+ });+ assert.deepStrictEqual(await findDashboardsByName(sdkWith(foreign.slice(0, 3)), 'Ops'), foreign.slice(0, 3), 'a short page is the whole set');+ assert.strictEqual(reads.length, 0, 'and needs no second read');+ assert.deepStrictEqual((await findDashboardsByName(sdkWith(foreign), 'Ops')).map((d) => d.id), all.map((d) => d.id), 'a full page is re-read in full');+ assert.strictEqual(reads.length, 1);+ assert.strictEqual(reads[0].paginate, true);+ assert.strictEqual(reads[0].top, undefined, 'uncapped');+ assert.strictEqual(reads[0].filter, "type eq 0 and name eq 'Ops'");+ reads.length = 0;+ await findDashboardsByName({ queryRecords: sdkWith([]).queryRecords }, 'Ops');+ assert.strictEqual(reads.length, 1, 'a reader without resolveArtifact (verify\'s) always reads in full');++ const ids = Array.from({ length: 30 }, (_, i) => `00000000-0000-0000-0000-${String(i).padStart(12, '0')}`);+ const chunks = [];+ const members = await dashboardsInSolution({+ queryRecords: async (set, q) => {+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ chunks.push((q.filter.match(/objectid eq /g) || []).length);+ return [ids[3], ids[27]].filter((id) => q.filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));+ },+ }, 'ContosoSln', ids);+ assert.deepStrictEqual(chunks, [25, 5], 'membership is asked in bounded chunks');+ assert.deepStrictEqual([...members].sort(), [ids[3], ids[27]].sort(), 'and members from every chunk are kept');++ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const { sdk } = mockSdk({ existingDashboards: foreign, solutionExists: true, dashboardsInSolution: ['d-ours'] });+ const query = sdk.queryRecords;+ sdk.queryRecords = async (set, q) => (set === 'systemform' && q && q.paginate ? asRows() : query(set, q));+ const result = await runSdkBuild(spec, { sdk, apply: true });+ assert.strictEqual(result.created.dashboards.Ops, 'd-ours', 'the build reuses its own from beyond the first page');+});+test('dashboards: a new dashboard is still created + pushed + added to the solution', async () => {const spec = makeSpec();spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];@@ -1225,6 +1748,59 @@ test('dashboards: a new dashboard is still created + pushed + added to the solutassert.ok(result.created.dashboards.Ops, 'created id recorded');});+// Solution membership is the only later proof that a dashboard is this app's. A push that landed but+// whose add-to-solution then failed left the dashboard outside it for good: a rebuild reused it as a+// lone name match without ever adding it, and teardown kept it while its tiles blocked the chart and+// view deletes. The build now undoes the push, and says exactly what is left when it cannot. Whether+// the halt is auto-retried follows what is left: nothing (safe — the cause's status is kept) or the+// dashboard (never — a retry would reuse it outside the solution, whatever transient text it quotes).+test('dashboards: a dashboard the build cannot add to its solution is removed again, never left outside it', async () => {+ const { isTransientHalt } = require(path.join(__dirname, '..', 'build-model-app.js'));+ const spec = makeSpec();+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'list', view: 'Active Tickets', name: 'Recent' }] }];+ const attempt = async ({ cause, undoFails = false, rowRemains = true, rowUnreadable = false }) => {+ const { sdk, calls } = mockSdk();+ const add = sdk.addSolutionComponent;+ // Forms are component type 60 too, so fail only the add for the dashboard that was just pushed.+ sdk.addSolutionComponent = async (o) => {+ const last = find(calls, 'pushArtifact').at(-1);+ if (o.componentType === 60 && last && last.args[0] === 'dashboard' && last.args[1] === o.componentId) throw cause;+ return add(o);+ };+ sdk.deleteRemoteArtifact = async (t, id) => { calls.push({ name: 'deleteRemoteArtifact', args: [t, id] }); if (undoFails) throw new Error('EPERM: operation not permitted, unlink'); };+ const query = sdk.queryRecords;+ sdk.queryRecords = async (set, q) => {+ if (set === 'systemform' && /^formid eq /.test((q && q.filter) || '')) {+ if (rowUnreadable) throw new Error('HTTP 500');+ return rowRemains ? [{ formid: q.filter.slice('formid eq '.length) }] : [];+ }+ return query(set, q);+ };+ let error = null;+ await runSdkBuild(spec, { sdk, apply: true }).catch((e) => { error = e; });+ const pushed = find(calls, 'pushArtifact').find((c) => c.args[0] === 'dashboard');+ return { error, pushed, undo: find(calls, 'deleteRemoteArtifact') };+ };+ const busy = Object.assign(new Error('HTTP 503 Service Unavailable'), { statusCode: 503 });+ const undone = await attempt({ cause: busy });+ assert.ok(undone.error, 'the build halts');+ assert.match(undone.error.message, /dashboard "Ops" could not be added to solution '[^']+' \(HTTP 503 Service Unavailable\), so it was removed again — re-run to create it afresh/);+ assert.deepStrictEqual(undone.undo.map((c) => c.args), [['dashboard', undone.pushed.args[1]]], 'the dashboard just pushed is the one removed');+ assert.strictEqual(isTransientHalt(undone.error), true, 'nothing is left behind, so a 503 is still auto-retried');++ const lock = new Error('Microsoft.Crm.ObjectModel.CustomizationLockException: try again later');+ const stranded = await attempt({ cause: lock, undoFails: true });+ assert.match(stranded.error.message, /dashboard "Ops" was created \([^)]+\) but could not be added to solution '[^']+' \(.*CustomizationLockException.*\), and removing it again failed \(EPERM.*\) — add it to the solution or delete it in Maker before re-running/);+ assert.strictEqual(isTransientHalt(stranded.error), false, 'a retry would reuse the stranded dashboard outside the solution');+ assert.strictEqual(isTransientHalt((await attempt({ cause: busy, undoFails: true, rowUnreadable: true })).error), false, 'when its absence cannot be read, it is assumed to be there');++ // The row went but the local workspace copy could not be removed: nothing is left outside the+ // solution, so it is reported (and retried) as removed.+ const localOnly = await attempt({ cause: busy, undoFails: true, rowRemains: false });+ assert.match(localOnly.error.message, /so it was removed again — re-run to create it afresh/);+ assert.strictEqual(isTransientHalt(localOnly.error), true);+});+test('commands: an existing command bar is reused (no duplicate) and reported in result.created', async () => {const spec = makeSpec();spec.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'var T={a:function(){}};' }];@@ -1990,7 +2566,12 @@ test('form topology: a tab the deployed form lacks is CREATED with empty sectionconst tabAdds = find(calls, 'addElement').filter((c) => String(c.args[2]) === '/tabs');assert.strictEqual(tabAdds.length, 1, `exactly one tab added; saw ${tabAdds.length}`);assert.strictEqual(tabAdds[0].args[3].name, 'tab_audit');- assert.deepStrictEqual(tabAdds[0].args[3].columns[0].sections[0].rows, [], 'its sections arrive EMPTY so the field pass owns every control');+ // The tab arrives with its form-columns but no sections: each section then goes through the same+ // per-section pass as an existing tab's, so one already on the form elsewhere would be MOVED in.+ assert.deepStrictEqual(tabAdds[0].args[3].columns[0].sections, [], 'the new tab arrives without sections');+ const sectionAdd = find(calls, 'addElement').find((c) => String(c.args[2]) === '/tabs/1/columns/0/sections');+ assert.ok(sectionAdd && sectionAdd.args[3].name === 'section_audit', 'its genuinely new section is then created in it');+ assert.deepStrictEqual(sectionAdd.args[3].rows, [], 'EMPTY, so the field pass owns every control');// And the field it declares still lands inside the new tab rather than back in the first section.const extra = find(calls, 'addElement').find((c) => /\/rows$/.test(String(c.args[2])) && (((c.args[3] || {}).cells || [])[0] || {}).control && c.args[3].cells[0].control.fieldName === 'new_extra');assert.ok(extra && extra.args[2].startsWith('/tabs/1/'), `new_extra should land in the new tab, landed at ${extra && extra.args[2]}`);@@ -2011,7 +2592,10 @@ test('form topology: a tab that gains a second form-column has the column ADDEDassert.strictEqual(colAdds.length, 1, `exactly one form-column added; saw ${colAdds.map((c) => c.args[2]).join(', ')}`);assert.strictEqual(colAdds[0].args[2], '/tabs/0/columns');assert.strictEqual(colAdds[0].args[3].width, '40%', 'the authored width is carried onto the new column');- assert.deepStrictEqual(colAdds[0].args[3].sections[0].rows, [], 'and its sections arrive empty');+ assert.deepStrictEqual(colAdds[0].args[3].sections, [], 'the new column arrives without sections');+ const sectionAdd = find(calls, 'addElement').find((c) => String(c.args[2]) === '/tabs/0/columns/1/sections');+ assert.ok(sectionAdd && sectionAdd.args[3].name === 'section_side', 'its new section is then created in it');+ assert.deepStrictEqual(sectionAdd.args[3].rows, [], 'and arrives empty');});test('form topology: a field moving into an EMPTY section gets a row seeded for it first', async () => {@@ -3470,7 +4054,7 @@ test('dashboardTileOpts id-passthrough: a tile carrying viewId/visualizationId +test('dashboardTileOpts name-based still resolves from result.created (author-declared dashboard)', () => {const spec = { views: [{ name: 'V', entity: 'new_ohproject' }], charts: [{ name: 'C', entity: 'new_ohproject' }] };- const result = { created: { views: { 'new_ohproject|V': 'view-id' }, charts: { C: 'chart-id' } } };+ const result = { created: { views: { 'new_ohproject|V': 'view-id' }, charts: { 'new_ohproject|C': 'chart-id' } } };const chart = dashboardTileOpts(spec, { type: 'chart', chart: 'C', view: 'V' }, result);assert.strictEqual(chart.viewId, 'view-id');assert.strictEqual(chart.visualizationId, 'chart-id');@@ -3488,6 +4072,32 @@ test('dashboardTileOpts keys created.views by entity|name so same-named views acassert.strictEqual(listB.viewId, 'view-b', 'new_b tile binds the new_b Active view');});+// #586 item 3, found live: two charts with the same NAME on different tables and a dashboard tile on+// one of them. Charts were keyed by name alone, so the tile took whichever chart was built last — a+// tile whose view is one table's and whose visualization is another's. The platform accepts and+// publishes that, and `--verify` passed it.+test('dashboards: same-named charts on different tables do not cross-wire a tile', async () => {+ const spec = makeSpec(); // new_ticket: view "Active Tickets", chart "By Priority"+ spec.views.push({ entity: 'new_customer', name: 'All Customers', columns: ['new_name', 'new_tier'] });+ // Declared LAST, so a name-only key ends on this one.+ spec.charts.push({ entity: 'new_customer', name: 'By Priority', chartType: 'Pie', groupBy: 'new_tier', measure: 'count' });+ spec.dashboards = [{ name: 'Ops', tiles: [{ type: 'chart', chart: 'By Priority', view: 'Active Tickets' }] }];+ const { sdk, calls } = mockSdk();+ const chartIdByEntity = {};+ const create = sdk.createArtifact;+ const record = (t, def, art) => { if (t === 'chart' && art) chartIdByEntity[String(def.entityLogicalName).toLowerCase()] = art.id; return art; };+ sdk.createArtifact = (t, def) => {+ const art = create(t, def);+ return art && typeof art.then === 'function' ? art.then((a) => record(t, def, a)) : record(t, def, art);+ };+ await runSdkBuild(spec, { sdk, apply: true });+ assert.ok(chartIdByEntity.new_ticket && chartIdByEntity.new_customer, `both charts are built: ${JSON.stringify(chartIdByEntity)}`);+ const tile = find(calls, 'addElement').find((c) => c.args[0] === 'dashboard' && c.args[2] === '/components').args[3];+ assert.strictEqual(tile.parameters.TargetEntityType, 'new_ticket');+ assert.strictEqual(tile.parameters.VisualizationId, chartIdByEntity.new_ticket,+ `the tile must show the new_ticket chart; charts built: ${JSON.stringify(chartIdByEntity)}`);+});+test('pages phase (v2, page key != name): result.created.pages is keyed by KEY so the sitemap finalize resolves', async () => {const spec = makeSpec();spec.schemaVersion = 2;@@ -4288,6 +4898,8 @@ test('form topology: a section emptied by a layout move is removed, not left as`exactly one vacated section should be reclaimed; saw ${removedSections.map((c) => c.args[2]).join(', ')}`);assert.ok(warnings.some((w) => /removed the now-empty section/.test(w) && /section_0_1/.test(w)),`the removal must be reported and name the section; got ${JSON.stringify(warnings)}`);+ assert.ok(warnings.some((w) => /section_0_1/.test(w) && /Give a section an explicit `name`/.test(w)),+ 'a GENERATED name lost its identity on the move, so the report says how to keep it');});// The sweep must never touch a section that still holds anything, nor one the engine owns.@@ -4350,7 +4962,7 @@ test('form topology: an UNCLAIMED section that still holds a cell is never remov'a section still holding the primary field must survive — removing it would take the record title off the form');});-// Astra review, HIGH: "zero cells" does not establish that THIS reconcile vacated the section. A+// "Zero cells" does not establish that THIS reconcile vacated the section. A// maker-added section that was ALREADY empty — one a form script may show/hide by name — would be// deleted by an otherwise no-op rebuild, and the destructive preflight cannot see it because that// compares fields and sitemap targets, not containers.@@ -5241,3 +5853,519 @@ test('form topology: narrowing a cell in an already-overflowing reserved row isassert.ok(res.skipped.layout.some((m) => /was applied, but its row still overflows/.test(m)),`the remaining overflow must be recorded; got ${JSON.stringify(res.skipped.layout)}`);});++// --- A NAMED section the spec places in another tab or form-column is MOVED there ------------------+//+// It used to be reused in place: found by name anywhere on the form, its attributes patched, its+// location left alone. The build reported success with the section still in the old tab, and verify,+// which checks placement, then failed the form.+const tabsForm = (tabs) => ({ id: 'f1', bag: { a: [], c: [] }, tabs: tabs.map(([name, label, sections], ti) => ({+ id: `t${ti}`, name, label, expanded: true, visible: true,+ columns: [{ width: '100%', sections: sections.map(([id, sname, slabel, fields]) => ({+ id, ...(sname ? { name: sname } : {}), label: slabel, visible: true, showLabel: true, columns: 1,+ rows: fields.map((fn) => ({ cells: [{ control: { fieldName: fn } }] })) })) }] })) });+const formShape = async (sdk, calls) => {+ const form = await sdk.getArtifact('form', find(calls, 'fetchArtifact').find((c) => c.args[0] === 'form').args[1]);+ return form.tabs.map((t) => [t.name, t.columns.flatMap((c) => c.sections.map((s) =>+ [s.id || 'new', s.name || null, (s.rows || []).flatMap((r) => (r.cells || []).map((x) => x.control && x.control.fieldName))]))]);+};+const sectionMoves = (calls) => find(calls, 'moveElement')+ .filter((c) => c.args[0] === 'form' && /\/sections\/\d+$/.test(String(c.args[2])))+ .map((c) => [c.args[2], c.args[3], c.args[4] && c.args[4].index]);+const sectionAdds = (calls) => find(calls, 'addElement').filter((c) => c.args[0] === 'form' && /\/sections$/.test(String(c.args[2])));+const relocateSpec = () => {+ const spec = makeSpec();+ spec.forms = explicitForm([+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }] },+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_tier'] }] },+ ]);+ return spec;+};+const formsOnly = ['solution', 'data-model', 'forms'];+const inOldTab = () => tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']]]], ['tab_two', 'Two', []]]);++test('form topology: a named section the spec moves to another tab is MOVED there — the same section, fields and all', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: inOldTab() });+ const warnings = [];+ await runSdkBuild(relocateSpec(), { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/1', '/tabs/1/columns/0/sections', 0]]);+ assert.ok(warnings.some((w) => w.includes("moved section 'sec_wide' from tab 'tab_one' (form-column 1) to tab 'tab_two' (form-column 1)")),+ `a move a maker may not expect is reported; got ${JSON.stringify(warnings)}`);+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']]]],+ ['tab_two', [['s1', 'sec_wide', ['new_tier']]]],+ ], 'the section keeps its id and its field, and nothing is left behind');+ assert.strictEqual(sectionAdds(calls).length, 0, 'no empty twin is created in the new tab');+});++test('form topology: a section relocation converges — a second build moves nothing', async () => {+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: inOldTab() });+ await runSdkBuild(relocateSpec(), { sdk, apply: true, phases: formsOnly });+ const first = calls.length;+ await runSdkBuild(relocateSpec(), { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls.slice(first)), []);+ assert.strictEqual(find(calls.slice(first), 'moveElement').length, 0, 'no cell moves either');+});++test('form topology: a moved section lands after the ones its new column already matched', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[1].sections.unshift({ name: 'sec_first', label: 'First', columns: 1, fields: [] });+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']]]],+ ['tab_two', 'Two', [['s5', 'sec_first', 'First', []], ['s6', 'sec_maker', 'Added in Maker', []]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/1', '/tabs/1/columns/0/sections', 1]]);+ assert.deepStrictEqual((await formShape(sdk, calls))[1][1].map((s) => s[1]), ['sec_first', 'sec_wide', 'sec_maker'],+ 'after the authored section before it, ahead of a section the author never declared');+});++// Without the guard, sec_main claimed sec_wide by its LABEL, and sec_wide's own name hit then moved it+// to tab_two — carrying sec_main's field along and leaving sec_main nowhere.+test('form topology: a label or position match never takes a section another authored section claims by name', async () => {+ const deployed = tabsForm([['tab_one', 'One', [['s1', 'sec_wide', 'Main', ['new_name', 'new_tier']]]], ['tab_two', 'Two', []]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(relocateSpec(), { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionAdds(calls).map((c) => c.args[3].name), ['sec_main'], 'sec_main gets a section of its own');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['new', 'sec_main', ['new_name']]]],+ ['tab_two', [['s1', 'sec_wide', ['new_tier']]]],+ ]);+});++// The naming hint is for a GENERATED name, which loses its identity on a move. An author may NAME a section+// `section_1_0`, and a copy of that needs no advice to give it a name — while a copy of the same name+// generated from the section's position still gets it.+test('form topology: an emptied copy is given the naming hint only when its name was generated', async () => {+ for (const [what, named] of [['named by the author', true], ['generated from its position', false]]) {+ const spec = relocateSpec();+ if (named) spec.forms[0].tabs[1].sections[0].name = 'section_1_0';+ else delete spec.forms[0].tabs[1].sections[0].name;+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'section_1_0', 'Wide', ['new_tier']]]],+ ['tab_two', 'Two', [['s9', 'section_1_0', 'Wide', []]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ const warnings = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });+ const removal = warnings.find((w) => /removed the now-empty section 'section_1_0'/.test(w));+ assert.ok(removal, `${what}: the emptied copy is removed; got ${JSON.stringify(warnings)}`);+ assert.strictEqual(/Give a section an explicit `name`/.test(removal), !named, `${what}: ${removal}`);+ assert.deepStrictEqual((await formShape(sdk, calls))[1], ['tab_two', [['s9', 'section_1_0', ['new_tier']]]], what);+ }+});++// A GENERATED name encodes the section's place (`section_<tab>[_<column>]_<index>`), so it is no identity to+// look for across the form: a section of that name found elsewhere — dragged there in Maker, or another+// section that now carries it after a reorder — is not moved back. As documented for a generated section,+// it is created where the layout places it, its fields follow, and the original, emptied, is removed.+test('form topology: a section with a generated name found elsewhere is recreated in place, not moved', async () => {+ const spec = makeSpec();+ spec.forms = explicitForm([+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }, { label: 'Wide', columns: 1, fields: ['new_tier'] }] },+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_two', label: 'Two', columns: 1, fields: [] }] },+ ]);+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]],+ ['tab_two', 'Two', [['s9', 'sec_two', 'Two', []], ['s1', 'section_0_1', 'Wide', ['new_tier']]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ const warnings = [];+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(sectionMoves(calls), [], 'the dragged section is not moved back');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['new', 'section_0_1', ['new_tier']]]],+ ['tab_two', [['s9', 'sec_two', []]]],+ ]);+ assert.ok(warnings.some((w) => /removed the now-empty section 'section_0_1'/.test(w) && /Give a section an explicit `name`/.test(w)), JSON.stringify(warnings));+});++// A section the build CREATES lands where the layout places it — right after the sections already matched in+// its column — not at the end. Appended, it followed every section still to come, and since the build never+// reorders what exists (and verify does not check order) the wrong order was permanent: a new section+// declared mid-column, or a generated one recreated after a drag in Maker.+test('form topology: a section the build creates lands where the layout places it, not at the end', async () => {+ const layout = (middle) => explicitForm([+ { name: 'tab_one', label: 'One', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }, middle, { name: 'sec_after', label: 'After', columns: 1, fields: ['new_x'] }] },+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_two', label: 'Two', columns: 1, fields: [] }] },+ ]);+ for (const [what, middle, dragged] of [+ ['a new named section declared mid-column', { name: 'sec_new', label: 'New', columns: 1, fields: ['new_tier'] }, false],+ ['a generated section dragged away in Maker', { label: 'Wide', columns: 1, fields: ['new_tier'] }, true],+ ]) {+ const spec = makeSpec();+ spec.forms = layout(middle);+ const two = [['s9', 'sec_two', 'Two', []]].concat(dragged ? [['s1', 'section_0_1', 'Wide', ['new_tier']]] : []);+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s2', 'sec_after', 'After', ['new_x']]]], ['tab_two', 'Two', two]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ const name = middle.name || 'section_0_1';+ const shape = [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['new', name, ['new_tier']], ['s2', 'sec_after', ['new_x']]]],+ ['tab_two', [['s9', 'sec_two', []]]],+ ];+ assert.deepStrictEqual(await formShape(sdk, calls), shape, what);+ const first = calls.length;+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ const later = calls.slice(first);+ assert.deepStrictEqual(await formShape(sdk, calls), shape, `${what}: stable`);+ assert.deepStrictEqual([find(later, 'moveElement').length, sectionAdds(later).length, find(later, 'removeElement').length], [0, 0, 0], `${what}: the next build changes nothing`);+ }+});++// An older build could leave two sections of one name: the real one in the old tab and an empty twin+// in the new one. The twin already in place is used, so nothing is moved on top of it.+test('form topology: a same-named section already in the target column wins over one elsewhere', async () => {+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']]]],+ ['tab_two', 'Two', [['s9', 'sec_wide', 'Wide', []]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ const warnings = [];+ await runSdkBuild(relocateSpec(), { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(sectionMoves(calls), [], 'no section is moved');+ const removal = warnings.find((w) => /removed the now-empty section 'sec_wide'/.test(w));+ assert.ok(removal && !/Give a section an explicit/.test(removal), `the copy is reported without a naming hint it does not need; got ${JSON.stringify(warnings)}`);+ const shape = await formShape(sdk, calls);+ assert.deepStrictEqual(shape[1], ['tab_two', [['s9', 'sec_wide', ['new_tier']]]], 'the field is moved into the twin in place');+ // The emptied original is not the section the layout claims, so the sweep reclaims it: claims are+ // judged by where each target resolves, never by a name the two share.+ assert.deepStrictEqual(shape[0], ['tab_one', [['s0', 'sec_main', ['new_name']]]], 'and the empty copy left behind is removed');+});++// A match made by label or position keeps the deployed section's own (here: absent) name, so the+// field pass finds it through the POINTER recorded when it matched — the pointer a later move shifts.+test('form topology: a section recorded by position still receives its field after a move shifts it', async () => {+ const spec = makeSpec();+ spec.entities[0].columns.push({ schemaName: 'new_other', displayName: 'Other', type: 'Text' });+ spec.forms = explicitForm([+ { name: 'tab_one', label: 'One', sections: [+ { name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] },+ { name: 'sec_old', label: 'Old', columns: 1, fields: ['new_other'] },+ ] },+ { name: 'tab_two', label: 'Two', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_tier'] }] },+ ]);+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']], ['s2', null, 'Old', []]]],+ ['tab_two', 'Two', []]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['s2', null, ['new_other']]]],+ ['tab_two', [['s1', 'sec_wide', ['new_tier']]]],+ ]);+});// The correction is scoped to the column the section LEFT. A position-recorded section in another+// column is untouched by the move, so correcting it too would send its field somewhere else.+test('form topology: a move corrects recorded pointers only in the column it left', async () => {+ const spec = makeSpec();+ spec.entities[0].columns.push({ schemaName: 'new_other', displayName: 'Other', type: 'Text' });+ spec.forms = explicitForm([+ { name: 'tab_a', label: 'A', sections: [+ { name: 'sec_a', label: 'Main', columns: 1, fields: ['new_name'] },+ { name: 'sec_old', label: 'Old', columns: 1, fields: ['new_other'] },+ ] },+ { name: 'tab_c', label: 'C', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_tier'] }] },+ ]);+ const deployed = tabsForm([['tab_a', 'A', [['s0', 'sec_a', 'Main', ['new_name']], ['s2', null, 'Old', []]]],+ ['tab_b', 'B', [['s1', 'sec_wide', 'Wide', ['new_tier']]]], ['tab_c', 'C', []]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ const shape = await formShape(sdk, calls);+ assert.deepStrictEqual(shape[0], ['tab_a', [['s0', 'sec_a', ['new_name']], ['s2', null, ['new_other']]]]);+ assert.deepStrictEqual(shape[2], ['tab_c', [['s1', 'sec_wide', ['new_tier']]]]);+});// A section the spec moves into a tab or form-column the deployed form does not have yet is still+// MOVED: the new container arrives without sections, and each of its sections goes through the same+// per-section pass. Creating the container WITH its sections made a same-named copy, the field pass+// filled the copy, and the emptied original survived the sweep under its claimed name — while verify,+// which looks only at authored containers, passed the form.+test('form topology: a named section moved into a NEW tab is moved, not duplicated', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[1] = { name: 'tab_three', label: 'Three', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_tier'] }] };+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/1', '/tabs/1/columns/0/sections', 0]]);+ assert.deepStrictEqual(sectionAdds(calls).map((c) => c.args[3].name), [], 'no copy is created');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']]]],+ ['tab_three', [['s1', 'sec_wide', ['new_tier']]]],+ ]);+});++test('form topology: a named section moved into a NEW form-column is moved, not duplicated', async () => {+ const spec = makeSpec();+ spec.forms = [{ entity: 'new_customer', name: 'Customer', layout: 'explicit', tabs: [{ name: 'tab_one', label: 'One', columns: [+ { width: '60%', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }] },+ { width: '40%', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_tier'] }] },+ ] }] }];+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ // Same tab, different form-columns: different arrays, so the index needs no compensation.+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/1', '/tabs/0/columns/1/sections', 0]]);+ assert.deepStrictEqual(sectionAdds(calls).length, 0, 'no copy is created');+ const form = await sdk.getArtifact('form', find(calls, 'fetchArtifact').find((c) => c.args[0] === 'form').args[1]);+ assert.deepStrictEqual(form.tabs[0].columns.map((c) => c.sections.map((s) => s.id)), [['s0'], ['s1']]);+});++// The notes/timeline section is appended by the COMPILER, not placed by the author, and nothing+// verifies where it sits — so a timeline a maker moved to another tab stays there.+test('form topology: an engine-owned section a maker moved is left where it is', async () => {+ const spec = relocateSpec();+ spec.forms[0].notes = true;+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ deployed.tabs[1].columns[0].sections.push({ id: 's7', name: 'section_notes', label: 'Notes', visible: true, showLabel: true, columns: 1,+ rows: [{ cells: [{ control: { classId: '{06375649-C143-495E-A496-C962E5B4488E}', fieldName: null } }] }] });+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [], 'the timeline is not dragged back to the first tab');+ assert.deepStrictEqual(sectionAdds(calls).length, 0, 'nor copied there');+ assert.ok((await formShape(sdk, calls))[1][1].some((s) => s[0] === 's7'), 'it stays in the tab the maker put it in');+});++// An AUTHORED section may legally carry the name the engine gives its own host — `section_notes` is a+// natural name for a section that holds a notes field — and the name lookups took the host: the move+// dragged the timeline into the author's tab and the field pass poured the author's fields into it.+// An engine-owned host is simply not a candidate for an authored want; the want is matched or created+// like any other authored section, and the host stays exactly as it was.+// The timeline's real control class id, as the SDK projects it (no braces, its original case).+const NOTES_CONTROL = '06375649-c143-495e-a496-c962e5b4488e';+const timelineHost = (id) => ({ id, name: 'section_notes', label: 'Notes', visible: true, showLabel: true, columns: 1,+ rows: [{ cells: [{ control: { classId: NOTES_CONTROL, fieldName: null } }] }] });+test('form topology: an authored section named like the timeline host never takes the host from another tab', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[1].sections[0] = { name: 'section_notes', label: 'Notes', columns: 1, fields: ['new_tier'] };+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', []]]);+ deployed.tabs[0].columns[0].sections.push(timelineHost('s7'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [], 'the timeline host is not moved into the author\u2019s tab');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['s7', 'section_notes', [null]]]],+ ['tab_two', [['new', 'section_notes', ['new_tier']]]],+ ], 'the author gets a section of their own, and the host keeps only its timeline');+});++test('form topology: an authored section named like the timeline host never takes the host in its own column', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[0].sections.push({ name: 'section_notes', label: 'Notes', columns: 1, fields: ['new_tier'] });+ spec.forms[0].tabs.pop();+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]]]);+ deployed.tabs[0].columns[0].sections.push(timelineHost('s7'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['new', 'section_notes', ['new_tier']], ['s7', 'section_notes', [null]]]],+ ], 'not by name, label or position: the host stays a timeline, and the authored section is created beside it, where the layout places it');+});++// With notes on, the COMPILER appends its own `section_notes` want after the author's sections in the+// first form-column, so an authored `section_notes` there shares its name. Recording the engine's want+// replaced the author's field target: the field pass poured the author's fields into the timeline, the+// sweep removed the emptied authored section, and verify still passed.+const notesOnSpec = () => {+ const spec = relocateSpec();+ spec.forms[0].notes = true;+ spec.forms[0].tabs[0].sections.push({ name: 'section_notes', label: 'Notes', columns: 1, fields: ['new_tier'] });+ spec.forms[0].tabs.pop();+ return spec;+};+test('form topology: with notes on, the compiled notes section never takes an authored section_notes\u2019 fields', async () => {+ // Deployed exactly as compiled: the author's section_notes, then the timeline host.+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s3', 'section_notes', 'Notes', ['new_tier']]]]]);+ deployed.tabs[0].columns[0].sections.push(timelineHost('s7'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ const warnings = [];+ await runSdkBuild(notesOnSpec(), { sdk, apply: true, phases: formsOnly, warn: (m) => warnings.push(m) });+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['s3', 'section_notes', ['new_tier']], ['s7', 'section_notes', [null]]]],+ ], 'an unchanged spec changes nothing');+ assert.ok(!warnings.some((w) => /removed the now-empty section/.test(w)), warnings.join('\n'));+ assert.deepStrictEqual([find(calls, 'moveElement').length, sectionAdds(calls).length], [0, 0]);+});++test('form topology: with notes on and the authored section_notes not deployed, it is created with its fields, and the builds settle', async () => {+ for (const [what, withHost] of [['only the timeline deployed', true], ['neither deployed', false]]) {+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]]]);+ if (withHost) deployed.tabs[0].columns[0].sections.push(timelineHost('s7'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(notesOnSpec(), { sdk, apply: true, phases: formsOnly });+ const shape = [['tab_one', withHost+ ? [['s0', 'sec_main', ['new_name']], ['new', 'section_notes', ['new_tier']], ['s7', 'section_notes', [null]]]+ : [['s0', 'sec_main', ['new_name']], ['new', 'section_notes', ['new_tier']], ['new', 'section_notes', [null]]]]];+ assert.deepStrictEqual(await formShape(sdk, calls), shape, `${what}: the field lands in the authored section, not the timeline`);+ const first = calls.length;+ await runSdkBuild(notesOnSpec(), { sdk, apply: true, phases: formsOnly });+ const later = calls.slice(first);+ assert.deepStrictEqual(await formShape(sdk, calls), shape, what);+ assert.deepStrictEqual([find(later, 'moveElement').length, sectionAdds(later).length, find(later, 'removeElement').length], [0, 0, 0], `${what}: the next build changes nothing`);+ }+});++// The timeline's host is found form-wide (a maker may have moved it), and the author's own section_notes+// holding fields elsewhere is not it: taking that one meant the form never got its timeline.+test('form topology: with notes on, an authored section_notes in another tab is never taken for the timeline host', async () => {+ const spec = relocateSpec();+ spec.forms[0].notes = true;+ spec.forms[0].tabs[1].sections[0] = { name: 'section_notes', label: 'Notes', columns: 1, fields: ['new_tier'] };+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s3', 'section_notes', 'Notes', ['new_tier']]]]]);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), []);+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['new', 'section_notes', [null]]]],+ ['tab_two', [['s3', 'section_notes', ['new_tier']]]],+ ], 'the timeline is added to the first tab, and the author\u2019s section keeps its field');+});++// With no host to find, the notes section is CREATED. It has no label or position to go on, and taking the+// maker section at its index relabelled it "Notes" and re-flowed it to one column, with still no timeline,+// on every build.+test('form topology: with notes on and no timeline deployed, the maker section at its index is never taken for it', async () => {+ for (const [what, prune, extra] of [+ ['a maker section with fields, prune off', false, (s) => Object.assign(s, { columns: 2, rows: [{ cells: [{ control: { fieldName: 'new_x' } }, { control: { fieldName: 'new_y' } }] }] })],+ ['an empty maker section', true, (s) => s],+ ]) {+ const spec = notesOnSpec();+ if (!prune) spec.forms[0].prune = false;+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s3', 'section_notes', 'Notes', ['new_tier']], ['s9', 'sec_extra', 'Extra', []]]]]);+ extra(deployed.tabs[0].columns[0].sections[2]);+ const before = JSON.parse(JSON.stringify(deployed.tabs[0].columns[0].sections[2]));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ for (const build of [1, 2]) {+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ const form = await sdk.getArtifact('form', find(calls, 'fetchArtifact').find((c) => c.args[0] === 'form').args[1]);+ const sections = form.tabs[0].columns[0].sections;+ assert.deepStrictEqual(sections.find((s) => s.id === 's9'), before, `${what}, build ${build}: the maker's section is untouched`);+ assert.strictEqual(sections.filter((s) => s.name === 'section_notes' && s.rows.some((r) => r.cells.some((c) => c.control && !c.control.fieldName))).length, 1,+ `${what}, build ${build}: exactly one timeline, created on the first build`);+ assert.strictEqual(sections[sections.length - 1].name, 'section_notes', `${what}, build ${build}: added last, where the compiler places it`);+ }+ }+});++// The timeline's host holds the timeline's own control. An authored `section_notes` holding a field and a+// maker's web resource holds AN unbound control but not that one — taking it for the host meant the form+// never got its timeline, and the notes want re-patched the author's section on every build.+test('form topology: with notes on, a section_notes holding a field and a maker web resource is never the timeline host', async () => {+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']], ['s3', 'section_notes', 'Notes', ['new_tier']]]]]);+ deployed.tabs[0].columns[0].sections[1].rows.push({ cells: [{ control: { classId: 'webresource-class', fieldName: null } }] });+ const before = JSON.parse(JSON.stringify(deployed.tabs[0].columns[0].sections[1]));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ for (const build of [1, 2]) {+ await runSdkBuild(notesOnSpec(), { sdk, apply: true, phases: formsOnly });+ const form = await sdk.getArtifact('form', find(calls, 'fetchArtifact').find((c) => c.args[0] === 'form').args[1]);+ const sections = form.tabs[0].columns[0].sections;+ assert.deepStrictEqual(sections.find((s) => s.id === 's3'), before, `build ${build}: the author's section is untouched`);+ assert.strictEqual(sections.filter((s) => s.rows.some((r) => r.cells.some((c) => c.control && String(c.control.classId).toLowerCase() === NOTES_CONTROL))).length, 1,+ `build ${build}: exactly one timeline`);+ }+});++// …while a timeline host a maker put a field into still holds that control, so it is still found and no+// second timeline is added.+test('form topology: with notes on, a timeline host a maker added a field to is still the host', async () => {+ const spec = relocateSpec();+ spec.forms[0].notes = true;+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ const host = timelineHost('s7');+ host.rows.push({ cells: [{ control: { fieldName: 'new_x' } }] });+ deployed.tabs[0].columns[0].sections.push(host);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionAdds(calls).map((c) => c.args[3].name), [], 'no second timeline section');+});++// A timeline or sub-grid host a maker added a bound field to is no longer engine-owned by STRUCTURE — not+// every cell is unbound — yet it is still the host: it holds the control the engine put it there for. An+// authored section sharing its name took it by name, so the build moved the host into the author's tab and+// poured the author's fields into it; and any authored want could take it by label or position.+const mixedHost = (host) => { host.rows.push({ cells: [{ control: { fieldName: 'new_x' } }] }); return host; };+const subgridHost = (id) => ({ id, name: 'section_grid_contacts', label: 'Contacts', visible: true, showLabel: true, columns: 1,+ rows: [{ cells: [{ control: { classId: 'E7A81278-8635-4D9E-8D4D-59480B391C5B', fieldName: null, parameters: { RelationshipName: 'new_customer_contacts' } } }] }] });+test('form topology: an engine host a maker added a field to is never taken by an authored section named like it', async () => {+ for (const [what, host] of [['timeline', mixedHost(timelineHost('s7'))], ['sub-grid', mixedHost(subgridHost('s7'))]]) {+ const spec = relocateSpec();+ spec.forms[0].prune = false;+ spec.forms[0].tabs[1].sections[0] = { name: host.name, label: host.label, columns: 1, fields: ['new_tier'] };+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', []]]);+ deployed.tabs[0].columns[0].sections.push(host);+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [], `${what}: the host is not moved into the author\u2019s tab`);+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['s7', host.name, [null, 'new_x']]]],+ ['tab_two', [['new', host.name, ['new_tier']]]],+ ], `${what}: the author gets a section of their own, and the host keeps its control and the maker's field`);+ }+});++// A host is known by the control ITS name exists for. A `section_notes` holding a sub-grid and a field is no+// timeline host, so it is the author's, and the spec moves it like any other named section.+test('form topology: a section named like the timeline host but holding a sub-grid is the author\u2019s', async () => {+ const spec = relocateSpec();+ spec.forms[0].prune = false;+ spec.forms[0].tabs[1].sections[0] = { name: 'section_notes', label: 'Notes', columns: 1, fields: ['new_tier'] };+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', []]]);+ deployed.tabs[0].columns[0].sections.push(mixedHost(Object.assign(subgridHost('s7'), { name: 'section_notes', label: 'Notes' })));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionAdds(calls).length, 0, 'no second section_notes');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']]]],+ ['tab_two', [['s7', 'section_notes', [null, 'new_x', 'new_tier']]]],+ ]);+});++test('form topology: a timeline host a maker added a field to is never taken by label or position', async () => {+ const spec = relocateSpec();+ spec.forms[0].notes = true;+ spec.forms[0].prune = false;+ spec.forms[0].tabs[0].sections.push({ name: 'sec_new', label: 'Notes', columns: 1, fields: ['new_tier'] });+ spec.forms[0].tabs.pop();+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]]]);+ deployed.tabs[0].columns[0].sections.push(mixedHost(timelineHost('s7')));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']], ['new', 'sec_new', ['new_tier']], ['s7', 'section_notes', [null, 'new_x']]]],+ ], 'the new section sits where its label and index point, but beside the host, not in it');+ assert.deepStrictEqual(sectionAdds(calls).map((c) => c.args[3].name), ['sec_new'], 'and the timeline is not added twice');+});++// A section is engine-owned by STRUCTURE (only unbound controls), which cannot say who laid it out: an+// authored section declared with no fields that a maker filled with a web resource looks the same. Skipping+// it by name created an empty duplicate beside it, and when the spec moved it, left the maker's control+// behind. Its authored name is the evidence it is the author's; only the engine's own names mark a host.+const makerFilled = (id, name) => ({ id, name, label: 'Related', visible: true, showLabel: true, columns: 1,+ rows: [{ cells: [{ control: { classId: 'webresource-class', fieldName: null } }] }] });+test('form topology: an authored section a maker filled with a control is still found by its name', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[0].sections.push({ name: 'sec_related', label: 'Related', columns: 1, fields: [] });+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ deployed.tabs[0].columns[0].sections.push(makerFilled('s4', 'sec_related'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.strictEqual(sectionAdds(calls).length, 0, 'no empty duplicate is created beside it');+ assert.deepStrictEqual((await formShape(sdk, calls))[0], ['tab_one', [['s0', 'sec_main', ['new_name']], ['s4', 'sec_related', [null]]]]);+});++test('form topology: an authored section a maker filled with a control moves WITH its control', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[1].sections.push({ name: 'sec_related', label: 'Related', columns: 1, fields: [] });+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ deployed.tabs[0].columns[0].sections.push(makerFilled('s4', 'sec_related'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [['/tabs/0/columns/0/sections/1', '/tabs/1/columns/0/sections', 1]]);+ assert.strictEqual(sectionAdds(calls).length, 0, 'no empty copy in the new tab');+ assert.deepStrictEqual(await formShape(sdk, calls), [+ ['tab_one', [['s0', 'sec_main', ['new_name']]]],+ ['tab_two', [['s1', 'sec_wide', ['new_tier']], ['s4', 'sec_related', [null]]]],+ ]);+});++// …while a host under the engine's OTHER name — a sub-grid's `section_grid_<relationship>` — is kept from+// an authored want of that name exactly like the timeline.+test('form topology: an authored section named like a sub-grid host never takes the host', async () => {+ const spec = relocateSpec();+ spec.forms[0].tabs[1].sections.push({ name: 'section_grid_new_ticket', label: 'Tickets', columns: 1, fields: [] });+ const deployed = tabsForm([['tab_one', 'One', [['s0', 'sec_main', 'Main', ['new_name']]]], ['tab_two', 'Two', [['s1', 'sec_wide', 'Wide', ['new_tier']]]]]);+ deployed.tabs[0].columns[0].sections.push(makerFilled('s8', 'section_grid_new_ticket'));+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingFormJson: deployed });+ await runSdkBuild(spec, { sdk, apply: true, phases: formsOnly });+ assert.deepStrictEqual(sectionMoves(calls), [], 'the host stays where it is');+ assert.deepStrictEqual(sectionAdds(calls).map((c) => c.args[3].name), ['section_grid_new_ticket'], 'the authored section is created');+});diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.jsindex 08256290c..62d5f8264 100644--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js@@ -71,6 +71,9 @@ const SKILL_SDK_SURFACE = ['getSolution','initWorkspace','insertStatusValue',+ // The deferred routing-description push reads the app copy's dirty flag, so it never replays an earlier+ // run's unpushed edits (sdk-build.js).+ 'listArtifacts','moveElement','publishArtifact','pushArtifact',diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex 6f0a57b2d..f09bb8679 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -200,6 +200,19 @@ function mockSdk(state = {}) {const queryRecords = async (entitySet, opts) => {calls.push({ method: 'queryRecords', entitySet });const filter = (opts && opts.filter) || '';+ // The app's solution, and which dashboards it holds (componenttype 60). Every dashboard the build+ // creates is added to the app's solution, so each seeded dashboard is a member unless listed in+ // state.foreignDashboards.+ if (entitySet === 'solution') {+ const m = filter.match(/uniquename eq '([^']*)'/);+ const row = m && db.solutions[m[1]];+ return row ? [{ solutionid: row.solutionid }] : [];+ }+ if (entitySet === 'solutioncomponent' && /componenttype eq 60/.test(filter)) {+ return Object.values(db.dashboards).map((d) => d.formid)+ .filter((id) => filter.includes(`objectid eq ${String(id).toLowerCase()}`) && !(state.foreignDashboards || []).includes(id))+ .map((objectid) => ({ objectid }));+ }if (entitySet === 'systemform') {const idm = filter.match(/formid eq (\S+)/);if (idm) {@@ -649,7 +662,10 @@ test('runTeardown reports ok=false and records the app step when a deleteAppCascassert.strictEqual(r.ok, false, 'a cascade child-cleanup failure makes the whole run not-ok');assert.ok(r.errors.some((e) => /app module "A"/.test(e.step || '') && /genPage gp-1: locked/.test(e.message)), 'the app step error names the orphaned genPage');assert.ok(events.some((e) => e.phase === 'app' && e.status === 'error'), 'the app step emits an error status');- assert.deepStrictEqual(solutionDeletes, ['sol-1'], 'best-effort: the solution step still ran after the app failure');+ // Best-effort: the run carried on past the app failure to the solution step — which, after a failed+ // step, keeps the solution so a re-run can still tell the app's dashboards apart (see below).+ assert.ok(events.some((e) => e.phase === 'solution' && e.status === 'skip' && e.skip === 'kept'), 'the solution step was reached and deliberately kept');+ assert.deepStrictEqual(solutionDeletes, [], 'the solution survives for the re-run');});// A main form the build promoted to the entity default (Gap 2) can't be deleted until a stock form@@ -704,6 +720,203 @@ test('planTeardown adds a resetDefaultViews step only for entities that have a 1assert.deepStrictEqual(resets, ['new_task'], 'only the child (referencing) entity needs its default views reset');});+// The dashboard lookup is by NAME, so it can return other apps' dashboards. Deleting every match took+// those with it. Ownership now comes from the app's solution: only the dashboards it holds are deleted,+// and with no real solution to ask none is.+test('teardown deletes only the dashboards the app\'s solution holds, never another app\'s namesake', async () => {+ const spec = { solution: { uniqueName: 'ContosoSln', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [], dashboards: [{ name: 'Operations', tiles: [] }] };+ const run = async (ids, { inSolution, solutionExists = true, failRead = false, failLookup = false, sln, noSolution = false } = {}) => {+ const deleted = [];+ const events = [];+ const sdk = {+ resolveArtifact: async (kind) => {+ if (failLookup && kind === 'dashboard') throw new Error(failLookup);+ return kind === 'dashboard' ? ids.map((id) => ({ id, name: 'Operations' })) : kind === 'solution' ? [{ id: 'sol-1', name: 'ContosoSln' }] : [];+ },+ deleteRemoteArtifact: async (type, id) => { deleted.push(id); },+ deleteAppCascade: async () => {},+ deleteSolution: async (id) => { deleted.push(`solution ${id}`); },+ queryRecords: async (set, opts) => {+ if (failRead && set === 'solutioncomponent') throw new Error(failRead);+ if (set === 'solution') return solutionExists ? [{ solutionid: 'sol-1' }] : [];+ if (set === 'solutioncomponent') return (inSolution || []).filter((id) => opts.filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));+ return [];+ },+ };+ const which = noSolution ? { app: spec.app, entities: [], dashboards: spec.dashboards } : sln ? { ...spec, solution: { ...spec.solution, uniqueName: sln } } : spec;+ const r = await runTeardown(which, { apply: true }, { sdk, emit: (e) => events.push(e) });+ const skip = events.find((e) => e.status === 'skip' && /^dashboard "Operations"/.test(e.label));+ return { deleted: deleted.filter((d) => !/^solution /.test(d)), skip, r, events, solutionDeleted: deleted.includes('solution sol-1') };+ };+ assert.deepStrictEqual((await run(['d-foreign', 'd-ours'], { inSolution: ['d-ours'] })).deleted, ['d-ours'], 'the namesake outside the solution survives');+ assert.deepStrictEqual((await run(['d-1', 'd-2'], { inSolution: ['d-1', 'd-2'] })).deleted, ['d-1', 'd-2'], 'every one the solution holds is this app\'s');+ const foreign = await run(['d-foreign'], { inSolution: [] });+ assert.deepStrictEqual(foreign.deleted, [], 'a lone namesake the solution does not hold is not this build\'s');+ assert.ok(foreign.skip && /none is in this app's solution 'ContosoSln'/.test(foreign.skip.label) && foreign.skip.skip === 'kept', JSON.stringify(foreign.skip));+ // An unreadable solution proves nothing, so nothing is deleted — and it is a FAILED step, not a skip.+ // As a skip it left no error behind, so the solution step then deleted the one thing a re-run needs to+ // tell this app's dashboards from same-named ones. A read error that says "not found" (a proxy's 404)+ // must not slip through runTeardown's not-found shortcut either.+ for (const failRead of ['HTTP 503', 'HTTP 404 Not Found']) {+ const unreadable = await run(['d-ours'], { inSolution: ['d-ours'], failRead });+ assert.deepStrictEqual(unreadable.deleted, [], `${failRead}: nothing is deleted`);+ assert.strictEqual(unreadable.r.ok, false, `${failRead}: the step fails`);+ assert.ok(unreadable.r.errors.some((e) => /^dashboard "Operations"/.test(e.step) && e.message.includes(`could not read solution 'ContosoSln'`) && e.message.includes(failRead)), JSON.stringify(unreadable.r.errors));+ assert.strictEqual(unreadable.skip, undefined, `${failRead}: not reported as a skip`);+ assert.strictEqual(unreadable.solutionDeleted, false, `${failRead}: the solution survives for the re-run`);+ assert.ok(unreadable.events.some((e) => e.phase === 'solution' && e.status === 'skip' && e.skip === 'kept' && /kept — 1 earlier step\(s\) failed/.test(e.label)), JSON.stringify(unreadable.events.filter((e) => e.phase === 'solution')));+ }+ // …and so does a failed NAME lookup, which a "not found" in its message made look like an absent dashboard.+ const lookup = await run(['d-ours'], { inSolution: ['d-ours'], failLookup: 'HTTP 404 Not Found' });+ assert.deepStrictEqual(lookup.deleted, [], 'a failed lookup deletes nothing');+ assert.ok(lookup.r.errors.some((e) => /^dashboard "Operations"/.test(e.step) && e.message.includes("could not look up dashboards named 'Operations'")), JSON.stringify(lookup.r.errors));+ assert.strictEqual(lookup.solutionDeleted, false, 'and the solution survives for the re-run');+ assert.strictEqual((await run(['d-ours'], { inSolution: ['d-ours'] })).solutionDeleted, true, 'a readable solution is still deleted once every step succeeds');+ // The named solution is gone (e.g. a re-run after a completed teardown): a lone namesake can only+ // be somebody else's now, so it is kept — the name posture would have deleted it.+ const gone = await run(['d-foreign'], { solutionExists: false });+ assert.deepStrictEqual(gone.deleted, []);+ assert.match(gone.skip.label, /solution 'ContosoSln' no longer exists/);+ // No real solution to ask — the built-in container a download may leave in the spec holds every+ // dashboard, so it proves nothing. A lone match used to be deleted here, and a re-run after this+ // app's own was gone then deleted another app's namesake; now none is deleted, single or several.+ const lone = await run(['d-1'], { sln: 'Default' });+ assert.deepStrictEqual(lone.deleted, [], 'a lone match may be another app\'s namesake');+ assert.ok(lone.skip && lone.skip.skip === 'kept' && /solution 'Default' is a built-in container that holds every dashboard/.test(lone.skip.label), JSON.stringify(lone.skip));+ assert.deepStrictEqual((await run(['d-1', 'd-2'], { sln: 'Default' })).deleted, [], 'several cannot be told apart either');+ const unnamed = await run(['d-1'], { noSolution: true });+ assert.deepStrictEqual(unnamed.deleted, []);+ assert.match(unnamed.skip.label, /this spec names no solution, so nothing proves a dashboard named 'Operations' is this app's/);+});++// The solution is what a re-run asks to tell this app's dashboards from same-named ones. Deleted after+// a failed step, it left the retry nothing to prove them by: the retry kept them for good, and their+// tiles then blocked the chart and view deletes on every later run. So a teardown with a failed step+// keeps it; a clean one still deletes it.+test('teardown keeps the solution while an earlier step failed, so a re-run can still tell which dashboards are the app\'s', async () => {+ const spec = { solution: { uniqueName: 'ContosoSln', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [], dashboards: [{ name: 'Operations', tiles: [] }] };+ const run = async (failDashboard) => {+ const calls = [];+ const events = [];+ const sdk = {+ resolveArtifact: async (kind) => (kind === 'dashboard' ? [{ id: 'd-ours', name: 'Operations' }] : kind === 'solution' ? [{ id: 'sol-1', name: 'ContosoSln' }] : []),+ deleteRemoteArtifact: async (type, id) => { calls.push(`delete ${type} ${id}`); if (failDashboard) throw new Error('HTTP 429 Too Many Requests'); },+ deleteAppCascade: async () => {},+ deleteSolution: async (id) => { calls.push(`delete solution ${id}`); },+ queryRecords: async (set, opts) => {+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ if (set === 'solutioncomponent') return opts.filter.includes('objectid eq d-ours') ? [{ objectid: 'd-ours' }] : [];+ return [];+ },+ };+ const r = await runTeardown(spec, { apply: true }, { sdk, emit: (e) => events.push(e) });+ return { r, calls, solutionSkip: events.find((e) => e.status === 'skip' && /^solution ContosoSln/.test(e.label)) };+ };+ const failed = await run(true);+ assert.strictEqual(failed.r.ok, false);+ assert.ok(!failed.calls.includes('delete solution sol-1'), 'the solution survives a failed step');+ assert.ok(failed.solutionSkip && failed.solutionSkip.skip === 'kept' && /kept — 1 earlier step\(s\) failed/.test(failed.solutionSkip.label), JSON.stringify(failed.solutionSkip));+ const clean = await run(false);+ assert.strictEqual(clean.r.ok, true, JSON.stringify(clean.r.errors));+ assert.ok(clean.calls.includes('delete solution sol-1'), 'a clean teardown still deletes it');+});++// A built-in container is never deleted and proves nothing about ownership, so after a failed step it+// keeps its own skip reason — "kept for the re-run" would promise evidence it cannot give.+test('a built-in solution keeps its own skip after a failed step, never the "kept for a re-run" one', async () => {+ const sdk = mockSdk({ webresources: { 'new_ticket.js': { webresourceid: 'wr-1', name: 'new_ticket.js' } }, tables: ['new_customer', 'new_ticket', 'new_comment'] });+ sdk.deleteWebResource = async () => { throw new Error('boom'); };+ const spec = fullSpec();+ spec.solution = { ...spec.solution, uniqueName: 'Default' };+ const r = await runTeardown(spec, { apply: true }, { sdk });+ assert.strictEqual(r.ok, false);+ assert.ok(r.skipped.includes('solution Default (restricted system solution)'), JSON.stringify(r.skipped));+ assert.ok(!r.skipped.some((s) => /re-run needs this solution/.test(s)));+});++// The name lookup reads one page of ten; the app's own dashboard can sort beyond it (see+// findDashboardsByName). Teardown must still find — and delete — it.+test('teardown deletes the app\'s dashboard even when it sorts beyond the first lookup page', async () => {+ const spec = { solution: { uniqueName: 'ContosoSln', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [], dashboards: [{ name: 'Operations', tiles: [] }] };+ const foreign = Array.from({ length: 10 }, (_, i) => ({ id: `d-foreign-${i}`, name: 'Operations' }));+ const deleted = [];+ const sdk = {+ resolveArtifact: async (kind) => (kind === 'dashboard' ? foreign : []),+ deleteRemoteArtifact: async (type, id) => { deleted.push(id); },+ deleteAppCascade: async () => {},+ queryRecords: async (set, opts) => {+ if (set === 'systemform') return [...foreign, { id: 'd-ours' }].map((d) => ({ formid: d.id, name: 'Operations' }));+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ if (set === 'solutioncomponent') return opts.filter.includes('objectid eq d-ours') ? [{ objectid: 'd-ours' }] : [];+ return [];+ },+ };+ const r = await runTeardown(spec, { apply: true }, { sdk });+ assert.deepStrictEqual(deleted, ['d-ours'], JSON.stringify(r.skipped));+});++// #587 item 6: `existing: true` is ONE ownership policy across tables, relationships and global+// choices. A download flags everything it recovers that way because it cannot prove this build created+// it — but only tables were protected, so tearing down a downloaded spec still deleted their+// relationships (removing the lookup column, and its data, from a table teardown RETAINS) and their+// possibly-shared global option sets.+const ownershipSpec = (flag) => ({+ solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' },+ entities: [+ { schemaName: 'new_project', ...(flag ? { existing: true } : {}), primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_stage', displayName: 'Stage', type: 'Choice', globalChoice: 'new_stage' }] },+ { schemaName: 'new_task', ...(flag ? { existing: true } : {}), primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_due', displayName: 'Due', type: 'DateTime' }] },+ ],+ relationships: [+ { type: 'OneToMany', referenced: 'new_project', referencing: 'new_task', lookup: { schemaName: 'new_ProjectId' }, ...(flag ? { existing: true } : {}) },+ { type: 'ManyToMany', entity1: 'new_project', entity2: 'new_task', ...(flag ? { existing: true } : {}) },+ ],+ globalChoices: [{ name: 'new_stage', options: ['Plan', 'Build'], ...(flag ? { existing: true } : {}) }],+});+const ownershipRun = async (flag) => {+ const sdk = mockSdk({ tables: ['new_project', 'new_task'], relationships: ['new_project_new_task', 'new_new_project_new_task'], globalchoices: ['new_stage'] });+ sdk.enrichDefaultViews = async (logical) => { sdk.calls.push({ method: 'enrichDefaultViews', logical }); return { updated: [] }; };+ const events = [];+ await runTeardown(ownershipSpec(flag), { apply: true }, { sdk, emit: (e) => events.push(e) });+ return { sdk, events };+};++test('teardown retains relationships and global choices flagged existing, exactly like tables (#587 item 6)', async () => {+ const { sdk, events } = await ownershipRun(true);+ const writes = sdk.calls.filter((c) => /^(delete|enrich)/.test(c.method)).map((c) => c.method);+ assert.deepStrictEqual(writes.filter((m) => m !== 'deleteAppCascade' && m !== 'deleteSolution'), [],+ 'nothing the download recovered may be deleted — nor may a retained table\'s default views be rewritten');+ for (const prefix of ['relationship ', 'global choice ', 'table ']) {+ // Events carry the skip reason inside the label: `<label> (<reason>)`.+ const skips = events.filter((e) => e.status === 'skip' && String(e.label).startsWith(prefix));+ assert.ok(skips.length && skips.every((e) => /existing: true/.test(e.label)), `${prefix.trim()}: ${JSON.stringify(skips)}`);+ }+});++test('control: an author-built spec still tears down its own relationships and global choices (#587 item 6)', async () => {+ const { sdk } = await ownershipRun(false);+ const methods = sdk.calls.map((c) => c.method);+ assert.strictEqual(methods.filter((m) => m === 'deleteRelationship').length, 2, 'both relationships this build created are deleted');+ assert.ok(methods.includes('deleteGlobalOptionSet'), 'and its global choice');+ assert.ok(methods.includes('enrichDefaultViews'), 'and the child\'s default views are still reset first');+});++// The reset exists only to undo lookups the BUILD surfaced on a table's default views, ahead of that+// relationship's delete. So it follows the build's own enrichment decision (enrichesDefaultViews) and+// needs a relationship that will actually be deleted — otherwise it rewrites views nobody asked it to.+test('resetDefaultViews is planned only where the build enriched the views AND a deleted relationship puts a lookup there', () => {+ const resetsFor = (mutate) => {+ const s = ownershipSpec(false);+ mutate(s);+ return planTeardown(s).filter((st) => st.kind === 'resetDefaultViews').map((st) => st.target.entityLogical);+ };+ assert.deepStrictEqual(resetsFor(() => {}), ['new_task'], 'baseline: the child of a relationship this build deletes');+ assert.deepStrictEqual(resetsFor((s) => { s.entities[1].existing = true; }), [], 'a retained table the build never enriched is left alone');+ assert.deepStrictEqual(resetsFor((s) => { s.entities[1].existing = true; s.entities[1].enrichDefaultViews = true; }), ['new_task'],+ 'unless the author opted it into enrichment — then the build did surface the lookup');+ assert.deepStrictEqual(resetsFor((s) => { s.entities[1].enrichDefaultViews = false; }), [], 'enrichment switched off: nothing to undo');+ assert.deepStrictEqual(resetsFor((s) => { s.relationships[0].existing = true; }), [], 'its relationship is retained: no delete to unblock');+});+// --- dry-run ----------------------------------------------------------------------------test('dry-run emits the whole plan as skips and never calls SDK', async () => {@@ -873,9 +1086,11 @@ test('a failed step does not strand the rest (best-effort continue)', async () =const r = await runTeardown(fullSpec(), { apply: true }, { sdk });assert.strictEqual(r.ok, false);assert.ok(r.errors.some((e) => /web resource/.test(e.step)));- // tables + solution after the failing step were still torn down+ // tables after the failing step were still torn downassert.strictEqual(sdk.db.tables.size, 0);- assert.deepStrictEqual(sdk.db.solutions, {});+ // ...but not the solution container: a re-run needs it to tell the app's dashboards from namesakes+ assert.deepStrictEqual(Object.keys(sdk.db.solutions), ['ContosoSupportDesk']);+ assert.ok(r.skipped.some((s) => /^solution ContosoSupportDesk \(kept — 1 earlier step\(s\) failed/.test(s)), JSON.stringify(r.skipped));});test('forms without names are skipped (cannot be resolved)', () => {@@ -1788,9 +2003,62 @@ test('#587 a cascade-cleanup failure still lets teardown continue — the app itassert.strictEqual(base.db.tables.size, 0,'the app is gone, so its dependents must still be torn down rather than left orphaned');});-// is not a GUID skips the association query entirely — and that is deliberate: FORM_GUID_RE is an-// injection guard on the OData filter, not an existence check. Every Dataverse `roleid` is an-// astra HIGH — the abort added above is DOWNSTREAM of deleteStep, which treats any not-found error++// The SDK's deleteAppCascade deletes remotely and THEN tidies its local workspace copy of the app, so a+// failure in that second, local step rejects the whole call after the app is already gone. Teardown read+// the rejection as "the app was not deleted" and abandoned every dependent step — leaving them all behind+// while reporting the app as still there.+test('an app delete that fails AFTER the app is gone still tears down its dependents, and says so', async () => {+ const seed = {+ appmodules: { [appUniqueName(desk)]: { appmoduleid: 'app-1', name: 'Support Desk' } },+ tables: ['new_customer', 'new_ticket', 'new_comment'],+ solutions: { ContosoSupportDesk: { solutionid: 'sol-1', uniquename: 'ContosoSupportDesk' } },+ };+ const base = mockSdk(seed);+ const sdk = {+ ...base,+ deleteAppCascade: async (id, unique) => {+ await base.deleteAppCascade(id, unique); // the remote delete really happened+ const err = new Error("EPERM: operation not permitted, unlink 'workspace\\apps\\app-1.json'");+ err.code = 'EPERM';+ throw err;+ },+ };+ const r = await runTeardown(desk, { apply: true }, { sdk, emit: () => {} });++ assert.strictEqual(r.ok, false, 'something did fail, and the run must say so');+ assert.ok(r.errors.some((e) => /app "Support Desk" was deleted, but the delete call then failed: EPERM/.test(e.message)), JSON.stringify(r.errors));+ assert.strictEqual(base.db.tables.size, 0, 'the app is gone, so its dependents are torn down');+ assert.ok(!r.skipped.some((s) => /not attempted/.test(s)), 'nothing may be reported as abandoned for an app that was deleted');+});++// Control for the rule above: a 404 whose app is CONFIRMED gone is a clean delete, handled (and+// verified) by deleteStep — it must not be turned into the "failed after the delete" error.+test('a 404 from an app delete whose app is confirmed gone is still a clean delete', async () => {+ const seed = {+ appmodules: { [appUniqueName(desk)]: { appmoduleid: 'app-1', name: 'Support Desk' } },+ tables: ['new_customer', 'new_ticket', 'new_comment'],+ solutions: { ContosoSupportDesk: { solutionid: 'sol-1', uniquename: 'ContosoSupportDesk' } },+ };+ const base = mockSdk(seed);+ const sdk = {+ ...base,+ deleteAppCascade: async (id, unique) => {+ await base.deleteAppCascade(id, unique);+ const err = new Error('appmodule not found');+ err.statusCode = 404;+ throw err;+ },+ };+ const r = await runTeardown(desk, { apply: true }, { sdk, emit: () => {} });+ assert.deepStrictEqual(r.errors, [], 'a confirmed-absent 404 is not a failure');+ assert.strictEqual(base.db.tables.size, 0);+ // The resolve, plus ONE confirming read by deleteStep — the handler leaves a 404 to it rather than+ // asking the platform the same question twice.+ assert.strictEqual(base.calls.filter((c) => c.method === 'resolveArtifact' && c.kind === 'app').length, 2);+});++// A 404 is not proof either. The abort added above is DOWNSTREAM of deleteStep, which treats any not-found error// as a successful delete. But the SDK also throws 404 when an ATOMIC app+sitemap changeset is// ROLLED BACK by the platform — the app is still there. That was recorded as a phantom delete, the// abort never fired, and dependent teardown went on to strip a live app: `ok: true`, no errors.diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.jsindex f3aab08aa..60caac9ed 100644--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js@@ -136,6 +136,39 @@ test('deleteAppCascade rejection is reported as a failed app step and dependentassert.ok(cap.logs.some((l) => /teardown finished with errors/.test(l)), 'the summary stays visibly non-clean');});+// After an app-delete abort the summary read "0 deleted, 8 not found, 1 failed" — eight steps never even+// QUERIED, reported as a fact about the environment. Likewise a step left in place on purpose (an+// `existing: true` table, a system table) is not "not found". Each skip is counted as what it is, and the+// counts must agree with the per-step lines the operator just read.+test('the teardown summary counts not-found, kept and not-attempted steps apart', async () => {+ const tally = (logs) => {+ const steps = logs.filter((l) => /^\s+\[\d+\/\d+\] ⊘ /.test(l));+ return {+ notFound: steps.filter((l) => /\(not found\)$/.test(l)).length,+ notAttempted: steps.filter((l) => /\(not attempted — /.test(l)).length,+ kept: steps.filter((l) => !/\(not found\)$/.test(l) && !/\(not attempted — /.test(l)).length,+ };+ };+ const summaryOf = (logs) => logs.find((l) => /teardown (complete|finished with errors) — /.test(l)) || '';++ const aborted = presentSdk();+ aborted.deleteAppCascade = async () => { throw new Error('delete not confirmed'); };+ const a = logCapture();+ await teardownModelApp(desk, { apply: true, allowDestructive: true }, { sdk: aborted, log: a.log });+ const at = tally(a.logs);+ assert.ok(at.notAttempted > 0 && at.notFound === 0, JSON.stringify(at));+ assert.match(summaryOf(a.logs), new RegExp(`0 deleted, 0 not found, 1 failed, ${at.notAttempted} not attempted \\(`), summaryOf(a.logs));++ const retained = JSON.parse(JSON.stringify(desk));+ for (const e of retained.entities) e.existing = true;+ const k = logCapture();+ await teardownModelApp(retained, { apply: true, allowDestructive: true }, { sdk: presentSdk(), log: k.log });+ const kt = tally(k.logs);+ assert.ok(kt.kept >= retained.entities.length, JSON.stringify(kt));+ assert.match(summaryOf(k.logs), new RegExp(`, ${kt.notFound} not found, 0 failed, ${kt.kept} kept \\(`), summaryOf(k.logs));+ assert.doesNotMatch(summaryOf(k.logs), /not attempted/, 'nothing was abandoned, so the clause is omitted');+});+test('deleteAppCascade resolved success:false reports orphaned generative-page children', async () => {const sdk = presentSdk();sdk.deleteAppCascade = async (appModuleId, appModuleIdUnique) => {@@ -215,6 +248,11 @@ function loadTeardownCli({// #587 item 8 — lets a test drive the destructive-cleanup guard both ways. `null` means the// guard accepts (the ordinary case); a string is the refusal reason.clearRefusedBecause = null,+ // What releasing the changed-only tombstone answers: deleted (the ordinary case), or left in place+ // because another teardown of the workspace is still running.+ releaseResult = { ok: true, deleted: true },+ // What the lease-held clear answers.+ clearResult = { ok: true },}) {const scriptPath = path.join(__dirname, '..', 'teardown-model-app.js');const source = `${fs.readFileSync(scriptPath, 'utf8')}\nmodule.exports.__mainForTest = main;\n`;@@ -293,8 +331,12 @@ function loadTeardownCli({}if (id === './lib/apply-snapshot-store.js') {return {- tombstoneSnapshot: (workspaceDir) => { events.push({ type: 'tombstoneSnapshot', workspaceDir }); return { ok: true }; },+ tombstoneSnapshot: (workspaceDir) => { events.push({ type: 'tombstoneSnapshot', workspaceDir }); return { ok: true, generation: 'g-tomb', teardownId: 'td-1' }; },deleteSnapshot: (workspaceDir) => events.push({ type: 'deleteSnapshot', workspaceDir }),+ releaseTombstone: (workspaceDir, teardownId, deps) => { events.push({ type: 'releaseTombstone', workspaceDir, teardownId, keep: !!(deps && deps.keep) }); return releaseResult; },+ beatTeardown: (workspaceDir, teardownId) => { events.push({ type: 'beatTeardown', workspaceDir, teardownId }); return { ok: true }; },+ clearWorkspace: (target) => { events.push({ type: 'clearWorkspace', target }); return clearResult; },+ TEARDOWN_BEAT_MS: 60000,};}if (id === './vendor/cds-maker-sdk.cjs') {@@ -332,6 +374,8 @@ function loadTeardownCli({process: sandboxProcess,Buffer,setImmediate,+ setInterval,+ clearInterval,}, { filename: scriptPath });return { main: mod.exports.__mainForTest, events, stderr, sdkTemp, settle: () => new Promise((resolve) => setImmediate(resolve)) };}@@ -365,12 +409,14 @@ test('teardown CLI applies, clears the local workspace only after a clean run, aawait harness.main();const emitIndex = harness.events.findIndex((e) => e.type === 'emitResult');const sdkCleanupIndex = harness.events.findIndex((e) => e.type === 'rmSync' && e.dir === harness.sdkTemp);- const workspaceCleanupIndex = harness.events.findIndex((e) => e.type === 'rmSync' && e.dir === workspaceDir);+ const workspaceCleanupIndex = harness.events.findIndex((e) => e.type === 'clearWorkspace' && e.target === workspaceDir);+ assert.ok(!harness.events.some((e) => e.type === 'rmSync' && e.dir === workspaceDir), 'never removed in place, outside the lease');assert.ok(harness.events.some((e) => e.type === 'createMakerSdk' && e.cfg.workspaceStorage.__mockWorkspaceRoot === harness.sdkTemp));assert.ok(harness.events.some((e) => e.type === 'runTeardown' && e.opts.apply === true));assert.ok(harness.events.some((e) => e.type === 'tombstoneSnapshot' && e.workspaceDir === workspaceDir));- assert.ok(harness.events.some((e) => e.type === 'deleteSnapshot' && e.workspaceDir === workspaceDir));+ assert.ok(harness.events.some((e) => e.type === 'releaseTombstone' && e.workspaceDir === workspaceDir && e.teardownId === 'td-1'),+ 'a clean teardown releases the tombstone entry IT wrote');assert.ok(workspaceCleanupIndex > -1, '--clear-workspace removes the caller workspace only after clean apply');assert.ok(sdkCleanupIndex > -1 && sdkCleanupIndex < emitIndex, 'emitResult exits, so SDK cleanup must happen first');assert.match(harness.stderr.join(''), /cleared workspace/);@@ -403,7 +449,7 @@ test('teardown CLI does not delete a workspace the safety guard refuses', asyncassert.ok(harness.events.some((e) => e.type === 'checkWorkspaceClearable' && e.dir === workspaceDir),'the guard must be consulted before any delete');- assert.ok(!harness.events.some((e) => e.type === 'rmSync' && e.dir === workspaceDir),+ assert.ok(!harness.events.some((e) => (e.type === 'rmSync' && e.dir === workspaceDir) || e.type === 'clearWorkspace'),'a refused workspace must NOT be removed');const err = harness.stderr.join('');assert.match(err, /skipped --clear-workspace/, 'the refusal must be reported, not silent');@@ -413,6 +459,94 @@ test('teardown CLI does not delete a workspace the safety guard refuses', async'the teardown succeeded; refusing an unsafe cleanup must not turn it into a failure');});+// --clear-workspace removes the whole workspace — and with it the changed-only tombstone, which another+// teardown of the same workspace may still be relying on. The release reports that, and the clear is+// skipped rather than deleting the fence.+test('teardown CLI skips --clear-workspace while the workspace still holds another teardown\u2019s fence', async () => {+ const workspaceDir = 'D:\\Projects\\power-platform-skills-sdk\\.test-workspace\\overlapped';+ const harness = loadTeardownCli({+ releaseResult: { ok: true, deleted: false, left: true, reason: '1 other teardown(s) of this workspace are still running' },+ parseResult: {+ positional: [],+ flags: {+ env: 'https://org.example',+ spec: '@D:\\Projects\\power-platform-skills-sdk\\plugins\\model-apps\\samples\\app-spec.support-desk.json',+ apply: true,+ 'allow-destructive': true,+ 'clear-workspace': true,+ workspace: workspaceDir,+ },+ },+ });++ await harness.main();++ assert.ok(!harness.events.some((e) => (e.type === 'rmSync' && e.dir === workspaceDir) || e.type === 'clearWorkspace'), 'the fence is not deleted');+ assert.ok(!harness.events.some((e) => e.type === 'checkWorkspaceClearable'), 'the clear is not even considered');+ const err = harness.stderr.join('');+ assert.match(err, /the changed-only snapshot stays tombstoned: 1 other teardown\(s\) of this workspace are still running\. The last of them to finish removes it\./);+ assert.match(err, /skipped --clear-workspace: the workspace still holds the changed-only fence/);+ const emitted = harness.events.find((e) => e.type === 'emitResult');+ assert.strictEqual(emitted.ok, true, 'the teardown itself succeeded');+});++// The clear runs under the workspace's lease and refuses a snapshot written since this teardown's release —+// another teardown's tombstone. Removing the folder in place deleted it. The teardown itself still succeeded.+test('teardown CLI skips --clear-workspace when a fence appeared after its release', async () => {+ const workspaceDir = 'D:\\Projects\\power-platform-skills-sdk\\.test-workspace\\refenced';+ const harness = loadTeardownCli({+ clearResult: { ok: false, reason: 'a changed-only snapshot was written to it after this teardown finished — another teardown or build of it is running' },+ parseResult: {+ positional: [],+ flags: {+ env: 'https://org.example',+ spec: '@D:\\Projects\\power-platform-skills-sdk\\plugins\\model-apps\\samples\\app-spec.support-desk.json',+ apply: true,+ 'allow-destructive': true,+ 'clear-workspace': true,+ workspace: workspaceDir,+ },+ },+ });++ await harness.main();++ assert.ok(harness.events.some((e) => e.type === 'clearWorkspace' && e.target === workspaceDir));+ assert.ok(!harness.events.some((e) => e.type === 'rmSync' && e.dir === workspaceDir), 'nothing removed in place');+ const err = harness.stderr.join('');+ assert.match(err, /skipped --clear-workspace: a changed-only snapshot was written to it after this teardown finished/);+ assert.doesNotMatch(err, /cleared workspace/);+ assert.strictEqual(harness.events.find((e) => e.type === 'emitResult').ok, true, 'the teardown itself succeeded');+});++// A release that FAILED (a held lease, a busy file) leaves the tombstone in place — safe, since a+// --changed-only build then only full-builds — and so the workspace holding it is not cleared either.+test('teardown CLI keeps the workspace when releasing the tombstone fails, and says what that costs', async () => {+ const workspaceDir = 'D:\\Projects\\power-platform-skills-sdk\\.test-workspace\\busy';+ const harness = loadTeardownCli({+ releaseResult: { ok: false, deleted: false, reason: 'release failed: EBUSY: resource busy or locked' },+ parseResult: {+ positional: [],+ flags: {+ env: 'https://org.example',+ spec: '@D:\\Projects\\power-platform-skills-sdk\\plugins\\model-apps\\samples\\app-spec.support-desk.json',+ apply: true,+ 'allow-destructive': true,+ 'clear-workspace': true,+ workspace: workspaceDir,+ },+ },+ });++ await harness.main();++ assert.ok(!harness.events.some((e) => e.type === 'rmSync' && e.dir === workspaceDir));+ const err = harness.stderr.join('');+ assert.match(err, /stays tombstoned: release failed: EBUSY: resource busy or locked\. A --changed-only build full-builds until a clean teardown removes it\./);+ assert.match(err, /skipped --clear-workspace: the workspace still holds the changed-only fence \(release failed: EBUSY/);+ assert.strictEqual(harness.events.find((e) => e.type === 'emitResult').ok, true);+});+test('teardown CLI dry-runs a positional spec with the default workspace and no destructive cleanup', async () => {const specPath = 'D:\\Projects\\power-platform-skills-sdk\\plugins\\model-apps\\samples\\app-spec.support-desk.json';const harness = loadTeardownCli({@@ -452,6 +586,32 @@ test('teardown CLI emits an engine failure only after cleaning the SDK temp workassert.ok(sdkCleanupIndex > -1 && sdkCleanupIndex < emitIndex);assert.strictEqual(harness.events[emitIndex].ok, false);assert.match(harness.events[emitIndex].payload.message, /engine failed/);+ // Even a teardown that throws drops its entry from the changed-only fence, keeping the tombstone.+ const released = harness.events.filter((e) => e.type === 'releaseTombstone');+ assert.deepStrictEqual(released.map((e) => [e.teardownId, e.keep]), [['td-1', true]]);+});++test('teardown CLI releases a teardown that finished with errors with keep, and clears nothing', async () => {+ const workspaceDir = 'D:\\Projects\\power-platform-skills-sdk\\.test-workspace\\failed';+ const harness = loadTeardownCli({+ runResult: { ok: false, dryRun: false, errors: ['app delete failed'] },+ parseResult: {+ positional: [],+ flags: {+ env: 'https://org.example',+ spec: '@D:\\Projects\\power-platform-skills-sdk\\plugins\\model-apps\\samples\\app-spec.support-desk.json',+ apply: true,+ 'allow-destructive': true,+ 'clear-workspace': true,+ workspace: workspaceDir,+ },+ },+ });++ await harness.main().catch(() => {});+ assert.deepStrictEqual(harness.events.filter((e) => e.type === 'releaseTombstone').map((e) => [e.teardownId, e.keep]), [['td-1', true]]);+ assert.ok(!harness.events.some((e) => e.type === 'rmSync' && e.dir === workspaceDir), 'a failed teardown clears no workspace');+ assert.strictEqual(harness.events.find((e) => e.type === 'emitResult').ok, false);});test('teardown CLI entrypoint reports SDK startup failures after removing the throwaway workspace', async () => {@@ -513,6 +673,66 @@ test('a teardown that finishes WITH ERRORS leaves the tombstone (snapshot not de} finally { fs.rmSync(ws, { recursive: true, force: true }); }});+// A teardown that FINISHED is no longer in flight, whatever its outcome: its entry is dropped and only the+// tombstone stays. Left behind, the entry read as a teardown still running whenever its pid was alive —+// here the very process the clean re-run runs in — and that re-run then kept the fence for up to a day.+test('a failed teardown drops its entry, so a clean re-run in the same process removes the snapshot', async () => {+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ eligibleSnap(ws, 'app-1');+ const failing = presentSdk();+ failing.deleteAppCascade = async () => { throw new Error('app delete failed'); };+ const r1 = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk: failing });+ assert.strictEqual(r1.ok, false);+ const kept = snapStore.readSnapshot(ws);+ assert.ok(snap.isTombstoned(kept) && kept.eligible === false, 'the tombstone stays');+ assert.deepStrictEqual(kept.teardowns, [], 'but no longer lists the teardown that finished');+ const r2 = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk: presentSdk() });+ assert.strictEqual(r2.ok, true, JSON.stringify(r2.errors));+ assert.strictEqual(r2.snapshotKept, undefined, 'no other teardown is running');+ assert.strictEqual(snapStore.readSnapshot(ws), null, 'the clean re-run removes the snapshot');+ } finally { fs.rmSync(ws, { recursive: true, force: true }); }+});++// While it runs, a teardown refreshes its entry, so the entry keeps counting; once it has finished it stops.+// An entry that is no longer seen stops counting, which is what lets a KILLED teardown's entry go.+test('a running teardown keeps its entry fresh, and stops once it has finished', async (t) => {+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ eligibleSnap(ws, 'app-1');+ t.mock.timers.enable({ apis: ['setInterval'] });+ const beat = t.mock.method(snapStore, 'beatTeardown');+ const sdk = presentSdk();+ let seen = null;+ const del = sdk.deleteAppCascade;+ sdk.deleteAppCascade = async (...args) => {+ const before = snapStore.readSnapshot(ws).teardowns[0].beat;+ t.mock.timers.tick(snapStore.TEARDOWN_BEAT_MS);+ seen = [before, snapStore.readSnapshot(ws).teardowns[0].beat];+ return del(...args);+ };+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.strictEqual(seen[0], undefined, 'no beat before the first interval');+ assert.strictEqual(typeof seen[1], 'number', 'a beat after it');+ const beats = beat.mock.callCount();+ t.mock.timers.tick(snapStore.TEARDOWN_BEAT_MS * 3);+ assert.strictEqual(beat.mock.callCount(), beats, 'a finished teardown beats no more');+ } finally { fs.rmSync(ws, { recursive: true, force: true }); }+});++test('a teardown that throws drops its entry too, and keeps the tombstone', async () => {+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ eligibleSnap(ws, 'app-1');+ await assert.rejects(teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws },+ { sdk: presentSdk(), emit: () => { throw new Error('emit failed'); } }), /emit failed/);+ const kept = snapStore.readSnapshot(ws);+ assert.ok(snap.isTombstoned(kept) && kept.eligible === false);+ assert.deepStrictEqual(kept.teardowns, []);+ } finally { fs.rmSync(ws, { recursive: true, force: true }); }+});+test('teardown dry-run does NOT tombstone or delete the snapshot', async () => {const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));try {@@ -522,3 +742,111 @@ test('teardown dry-run does NOT tombstone or delete the snapshot', async () => {assert.ok(disk && disk.eligible === true, 'a dry-run leaves the eligible snapshot untouched');} finally { fs.rmSync(ws, { recursive: true, force: true }); }});++// #587 item 2: the tombstone is the fence, so a teardown that cannot write it must not mutate. It used+// to warn and carry on — and if the app delete then failed after lower-level artifacts were gone, the+// old ELIGIBLE snapshot survived describing a state that no longer existed.+test('teardown --apply refuses to delete anything when the snapshot cannot be fenced', async () => {+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ eligibleSnap(ws, 'app-1');+ // Another live, young build holds the workspace lease, so the tombstone cannot be written.+ const held = snapStore.acquireLease(ws, { now: () => Date.now(), pid: process.pid, processAlive: () => true, staleMs: snapStore.LEASE_STALE_MS });+ assert.ok(held.ok);+ const sdk = presentSdk();+ const { log, logs } = logCapture();+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk, log });+ snapStore.releaseLease(held);+ assert.strictEqual(r.ok, false);+ assert.ok(r.errors.some((e) => /fence|tombstone/.test(e)), JSON.stringify(r.errors));+ assert.deepStrictEqual(sdk.calls.filter((c) => /^delete/.test(c.method)), [], 'no delete may run before the fence is in place');+ assert.ok(logs.some((m) => /nothing was deleted/i.test(m)), logs.join('\n'));+ const disk = snapStore.readSnapshot(ws);+ assert.ok(disk && disk.eligible === true && !snap.isTombstoned(disk), 'the untouched snapshot still describes the untouched app');+ } finally { fs.rmSync(ws, { recursive: true, force: true }); }+});++// A workspace with NO snapshot is fenced too — a FIRST changed-only build has none until it finishes, and+// "nothing to fence" let it bless the app this teardown was deleting. That means creating the folder when+// there is none: a clean teardown removes it again, and a failed one leaves the tombstone, which is what+// keeps a surviving artifact from being blessed by the next baseline.+test('teardown --apply from a folder with no workspace fences it while deleting, then leaves none behind', async () => {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ const ws = path.join(parent, '.maker-workspace');+ const sdk = presentSdk();+ let fencedDuringDelete = null;+ const deleteApp = sdk.deleteAppCascade;+ sdk.deleteAppCascade = async (...args) => { fencedDuringDelete = snap.isTombstoned(snapStore.readSnapshot(ws)); return deleteApp(...args); };+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.strictEqual(fencedDuringDelete, true, 'a tombstone must be in place while the app is deleted');+ assert.deepStrictEqual(fs.readdirSync(parent), [], 'a folder that never had a workspace is left without one');+ } finally { fs.rmSync(parent, { recursive: true, force: true }); }+});++test('a failed teardown from a folder with no workspace leaves the fresh tombstone behind', async () => {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ const ws = path.join(parent, '.maker-workspace');+ const sdk = presentSdk();+ sdk.deleteAppCascade = async () => { throw new Error('app delete failed'); };+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk });+ assert.strictEqual(r.ok, false);+ const disk = snapStore.readSnapshot(ws);+ assert.ok(disk && snap.isTombstoned(disk) && disk.eligible === false, 'the tombstone outlives a failed teardown');+ } finally { fs.rmSync(parent, { recursive: true, force: true }); }+});++// An existing workspace folder is the build's, so a clean teardown removes only the snapshot from it — even+// when that leaves it empty.+test('a clean teardown keeps a workspace folder that already existed, even one it leaves empty', async () => {+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ eligibleSnap(ws, 'app-1');+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk: presentSdk() });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ assert.ok(fs.existsSync(ws), 'the folder survives');+ assert.deepStrictEqual(fs.readdirSync(ws), [], 'and only the snapshot is gone');+ } finally { fs.rmSync(ws, { recursive: true, force: true }); }+});++// Two teardowns can overlap — an agent re-running one that timed out. The tombstone lists each one in+// flight, and only the LAST to finish deletes it, in either finishing order. Deleting it when the first one+// finished let a first changed-only build claim and bless a baseline for an app the other was still deleting.+test('overlapping teardowns keep the fence until the last one finishes, whichever finishes first', async () => {+ for (const order of ['the other finishes after this one', 'the other finishes first']) {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'td-snap-'));+ try {+ const ws = path.join(parent, '.maker-workspace');+ const sdk = presentSdk();+ let other = null;+ let claimedDuring = null;+ const deleteApp = sdk.deleteAppCascade;+ sdk.deleteAppCascade = async (...args) => {+ other = snapStore.tombstoneSnapshot(ws);+ if (order === 'the other finishes first') {+ assert.deepStrictEqual(snapStore.releaseTombstone(ws, other.teardownId).left, true, 'the other leaves the fence to this one');+ claimedDuring = snapStore.claimBaselineSnapshot(ws, { orgId: 'o', envUrl: 'https://e', appUniqueName: 'a' });+ }+ return deleteApp(...args);+ };+ const logs = [];+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true, workspaceDir: ws }, { sdk, log: (m) => logs.push(m) });+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));+ if (order === 'the other finishes first') {+ assert.strictEqual(claimedDuring.ok, false, 'no first build may claim while this teardown is still deleting');+ assert.strictEqual(snapStore.readSnapshot(ws), null, 'the last teardown to finish deletes the snapshot');+ assert.deepStrictEqual(fs.readdirSync(parent), [], 'and the folder it created');+ assert.strictEqual(r.snapshotKept, undefined);+ } else {+ const disk = snapStore.readSnapshot(ws);+ assert.ok(disk && snap.isTombstoned(disk), 'the other teardown\u2019s fence survives this one finishing');+ assert.deepStrictEqual(disk.teardowns.map((t) => t.id), [other.teardownId], 'with only the other\u2019s entry left');+ assert.match(r.snapshotKept, /1 other teardown\(s\) of this workspace are still running/);+ assert.ok(logs.some((m) => /stays tombstoned: .*The last of them to finish removes it/.test(m)), logs.join('\n'));+ assert.deepStrictEqual(snapStore.releaseTombstone(ws, other.teardownId), { ok: true, deleted: true }, 'the other, finishing last, deletes it');+ }+ } finally { fs.rmSync(parent, { recursive: true, force: true }); }+ }+});diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.jsindex 5f782ff61..74b1215c7 100644--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js@@ -737,4 +737,150 @@ test('appEntityComponents(): matches an objectid whose CASING differs from the rconst r = await readerWith(sdk).appEntityComponents(['new_order']);assert.strictEqual(r.ok, true);assert.deepStrictEqual(r.present, ['new_order'], 'an upper-cased objectid must still match');+});+// The dashboard oracle through the REAL reader seam: `dashboardComponents` is implemented here with+// the SDK's own deserializer (fetch, then read the artifact), so a stub-only test would prove nothing+// about the reader verify actually runs with.+// A dashboard the SDK returns no artifact for, or a component list that is not a list, is not "no tiles": verify+// reports it unverified. Converting it to an empty list passed the check having read nothing.+test('readerFor + verifySpec: a dashboard whose artifact cannot be read is unverified, never passed', async () => {+ for (const [what, art] of [['no artifact', null], ['a malformed component list', { components: { chart: 1 } }]]) {+ const sdk = {+ findTables: async () => [],+ findColumns: async () => [],+ queryRecords: async (set) => (set === 'systemform' ? [{ formid: 'dash-1', formxml: '<form/>' }] : []),+ listArtifacts: async () => [],+ dataverse: { get: async () => ({ status: 200, body: { formxml: '<form/>', '@odata.etag': 'W/"1"' } }) },+ fetchArtifact: async () => {},+ getArtifact: async () => art,+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ };+ const spec = { solution: { publisherPrefix: 'new' }, app: { name: 'Support Desk', uniqueName: 'new_supportdesk' }, entities: [], appShell: { areas: [] },+ dashboards: [{ name: 'Ops', tiles: [{ type: 'chart', name: 'By Priority', entity: 'new_ticket', viewId: 'v', visualizationId: 'c' }] }] };+ const r = await verifySpec(spec, readerFor(sdk, 'new_supportdesk', {}));+ const chk = r.checks.find((c) => c.kind === 'dashboard');+ assert.strictEqual(chk.present, false, what);+ assert.match(chk.detail, new RegExp(`its tiles could not be read \\(the SDK returned ${what}`), what);+ }+});++// verify checks what users see: the PUBLISHED dashboard. The SDK's read is the unpublished draft, and verify runs+// in the build's workspace, whose copy can hold unpushed edits — so a fix saved but not published, or never+// pushed, passed while users still saw the broken dashboard. Either is now unverified. So is a draft saved and put+// back while the tiles were read: that leaves the FormXML as it was, but not the draft's token.+test('readerFor + verifySpec: a dashboard whose draft or workspace copy is not what is published is unverified', async () => {+ const spec = { solution: { publisherPrefix: 'new' }, app: { name: 'Support Desk', uniqueName: 'new_supportdesk' }, entities: [], appShell: { areas: [] },+ dashboards: [{ name: 'Ops', tiles: [{ type: 'chart', name: 'By Priority', entity: 'new_ticket', viewId: 'v', visualizationId: 'c' }] }] };+ const fetches = [];+ // `later` answers the reads made AFTER the fetch: the dashboard changing while it is being read. `laterVersion` is+ // the draft's token then: a draft saved and put back leaves the FormXML as it was, but not its token.+ const sdkWith = ({ draftXml = '<form/>', dirty = false, draftStatus = 200, later = null, version = 'W/"1"', laterVersion = null } = {}) => {+ let reads = 0;+ const xml = () => (later && reads > 2 ? later : '<form/>');+ return {+ findTables: async () => [],+ findColumns: async () => [],+ queryRecords: async (set, o) => {+ // The published row carries its own token, which a write to the draft does not move.+ if (set === 'systemform' && o && o.select && o.select.includes('formxml')) { reads += 1; return [{ formid: 'dash-1', formxml: xml(), '@odata.etag': 'W/"9"' }]; }+ if (set === 'systemform') return [{ formid: 'dash-1', formxml: '<form/>' }];+ if (set === 'savedqueryvisualization') return [{ primaryentitytypecode: 'new_ticket' }];+ if (set === 'savedquery') return [{ returnedtypecode: 'new_ticket' }];+ return [];+ },+ listArtifacts: async (type) => (type === 'dashboard' ? [{ type, id: 'dash-1', isDirty: dirty }] : []),+ dataverse: { get: async (url) => {+ assert.strictEqual(url, '/systemforms(dash-1)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml');+ reads += 1;+ const token = laterVersion && reads > 2 ? laterVersion : version;+ return { status: draftStatus, body: { formxml: later && reads > 2 ? later : draftXml, ...(token === null ? {} : { '@odata.etag': token }) } };+ } },+ fetchArtifact: async (type, id, o) => { fetches.push(o); },+ getArtifact: async () => ({ components: [{ type: 'chart', name: 'By Priority', parameters: {+ TargetEntityType: 'new_ticket', ViewId: '{11111111-1111-1111-1111-111111111111}', VisualizationId: '{22222222-2222-2222-2222-222222222222}' } }] }),+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ };+ };+ const check = async (sdk) => (await verifySpec(spec, readerFor(sdk, 'new_supportdesk', {}))).checks.find((c) => c.kind === 'dashboard');+ for (const [what, opts, detail] of [+ ['an unpublished draft', { draftXml: '<form><changed/></form>' }, /dashboard dash-1 has changes that are not published — publish it, then verify/],+ ['a draft that cannot be read', { draftStatus: 503 }, /the draft of dashboard dash-1 could not be read \(HTTP 503\)/],+ ['a dashboard that changed while it was read', { later: '<form><changed/></form>' }, /dashboard dash-1 changed while it was being read — verify again/],+ ['a draft saved and put back while it was read', { laterVersion: 'W/"3"' }, /dashboard dash-1 changed while it was being read — verify again/],+ ['a draft read with no version', { version: null }, /the version of dashboard dash-1 could not be read/],+ ]) {+ const chk = await check(sdkWith(opts));+ assert.strictEqual(chk.present, false, what);+ assert.match(chk.detail, detail, what);+ }+ // CONTROL: published, with nothing pending — the tiles are read and checked.+ const ok = await check(sdkWith());+ assert.strictEqual(ok.present, true, ok.detail);+ // With an isolated reader the tiles come from IT — a throwaway workspace — and never from the build's copy, which+ // may hold unpushed edits (the main SDK here would answer cross-wired tiles and is never asked), and it is disposed.+ const main = sdkWith();+ main.fetchArtifact = async () => { throw new Error('the build workspace must not be read for tiles'); };+ main.getArtifact = async () => ({ components: [{ type: 'chart', name: 'By Priority', parameters: { TargetEntityType: 'new_customer' } }] });+ const iso = sdkWith();+ let disposed = 0;+ const isolated = await verifySpec(spec, readerFor(main, 'new_supportdesk', { isolatedReader: async () => ({ sdk: iso, dispose: () => { disposed += 1; } }) }));+ const chk = isolated.checks.find((c) => c.kind === 'dashboard');+ assert.strictEqual(chk.present, true, chk.detail);+ assert.strictEqual(disposed, 1, 'the throwaway workspace is disposed after the read');+});++// A client per isolated read ran `az account get-access-token` once per dashboard. One client serves every read of a+// run — the run's own when it is given — while each read still gets a fresh SDK in its own throwaway workspace.+test('isolatedReaderFor shares one HTTP client across reads, each with a fresh SDK', async () => {+ const { isolatedReaderFor } = require('../verify-model-app.js');+ const client = { request: async () => { throw new Error('no request is made'); } };+ let made = 0;+ const makeClient = () => { made += 1; return client; };+ const read = isolatedReaderFor('https://contoso.crm.dynamics.com', { makeClient });+ const a = await read();+ const b = await read();+ assert.strictEqual(made, 1, 'one client for the run');+ assert.notStrictEqual(a.sdk, b.sdk, 'a fresh SDK per read');+ a.dispose();+ b.dispose();+ const own = await isolatedReaderFor('https://contoso.crm.dynamics.com', { httpClient: client, makeClient })();+ own.dispose();+ assert.strictEqual(made, 1, 'with the run\u2019s own client, none is made');+});++test('readerFor + verifySpec: a cross-wired dashboard chart tile fails verify through the real reader seam', async () => {+ const calls = [];+ const sdk = {+ findTables: async () => [],+ findColumns: async () => [],+ queryRecords: async (set, opts) => {+ if (set === 'systemform') return [{ formid: 'dash-1', formxml: '<form/>' }];+ if (set === 'savedqueryvisualization') return [{ primaryentitytypecode: 'new_customer' }];+ if (set === 'savedquery') return [{ returnedtypecode: 'new_ticket' }];+ return [];+ },+ listArtifacts: async () => [],+ dataverse: { get: async () => ({ status: 200, body: { formxml: '<form/>', '@odata.etag': 'W/"1"' } }) },+ fetchArtifact: async (type, id) => { calls.push(['fetchArtifact', type, id]); },+ getArtifact: async (type, id) => {+ calls.push(['getArtifact', type, id]);+ return { components: [{ type: 'chart', name: 'By Priority', parameters: {+ TargetEntityType: 'new_ticket', ViewId: '{11111111-1111-1111-1111-111111111111}', VisualizationId: '{22222222-2222-2222-2222-222222222222}' } }] };+ },+ fetchEntityMetadata: async () => ({ Relationships: [] }),+ resolveArtifact: async () => [],+ retrieveSetting: async () => null,+ };+ const spec = { solution: { publisherPrefix: 'new' }, app: { name: 'Support Desk', uniqueName: 'new_supportdesk' }, entities: [], appShell: { areas: [] },+ dashboards: [{ name: 'Ops', tiles: [{ type: 'chart', name: 'By Priority', entity: 'new_ticket', viewId: 'v', visualizationId: 'c' }] }] };+ const r = await verifySpec(spec, readerFor(sdk, 'new_supportdesk', {}));+ const chk = r.checks.find((c) => c.kind === 'dashboard');+ assert.ok(chk, 'a dashboard check must be produced');+ assert.strictEqual(chk.present, false);+ assert.match(chk.detail, /shows new_ticket, but its chart belongs to new_customer/);+ assert.deepStrictEqual(calls, [['fetchArtifact', 'dashboard', 'dash-1'], ['getArtifact', 'dashboard', 'dash-1']], 'the tiles come from the SDK artifact of THAT dashboard');});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.jsindex 90ace6ea7..43493f01b 100644--- a/plugins/model-apps/scripts/tests/verify-spec.test.js+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js@@ -1078,6 +1078,37 @@ test('verifySpec: a failing context read cannot flip a proven feature to FAIL',});});+// #583: the routing description is asserted only when the spec sets one, against the row's own+// `appmodule.aiappdescription`, found by the identity the build wrote under.+test('#583 verify checks the deployed routing description when the spec sets one', async () => {+ const base = { solution: { publisherPrefix: 'new' }, app: { name: 'Ops', uniqueName: 'new_ops' } };+ const withRouting = { ...base, app: { ...base.app, aiDescription: 'Route ops work here.' } };+ const reader = (rows, fail) => ({+ sitemapXml: async () => '',+ queryRecords: async (set, o) => {+ if (set !== 'appmodule') return [];+ if (fail) throw new Error('read denied');+ assert.match(o.filter, /uniquename eq 'new_ops'/, 'read by the identity the build wrote under');+ return rows;+ },+ });+ const check = async (spec, read) => (await verifySpec(spec, read)).checks.find((c) => c.kind === 'app-ai-description');++ assert.strictEqual((await check(withRouting, reader([{ aiappdescription: 'Route ops work here.' }]))).present, true);+ for (const [what, read, re] of [+ ['a different value', reader([{ aiappdescription: 'Other text' }]), /differs from the spec/],+ ['no value', reader([{ aiappdescription: null }]), /no routing description/],+ ['no app', reader([]), /no app module with unique name 'new_ops'/],+ ['an unreadable row', reader([], true), /could not read the app's routing description: read denied/],+ ]) {+ const c = await check(withRouting, read);+ assert.strictEqual(c.present, false, what);+ assert.match(c.detail, re, what);+ }+ assert.strictEqual(await check(base, reader([{ aiappdescription: 'Written by the platform.' }])), undefined,+ 'nothing is asserted when the spec leaves it to the platform');+});+// ---------------------------------------------------------------------------// App-module TABLE (type-1) membership.// ---------------------------------------------------------------------------@@ -1312,6 +1343,84 @@ test('verify tolerates deployed sections and fields the spec never declared', asconst chk = await topoCheck(xml);assert.strictEqual(chk.present, true, `extras must not fail the authored subset; got ${chk && chk.detail}`);});++// An authored section may share the name the engine gives its timeline host. Verify matches containers+// the way the BUILD does, and the build never lets an authored section take an engine host by name —+// so neither may verify, or it grades the author's fields against the timeline section.+test('verify never matches an authored section to an engine host that shares its name', async () => {+ const xml = `<form><tabs><tab name="tab_overview"><columns>`+ + `<column width="60%"><sections><section name="sec_left"><rows><row><cell><control datafieldname="new_name" /></cell></row></rows></section></sections></column>`+ + `<column width="40%"><sections>`+ + `<section name="section_notes"><rows><row><cell><control id="notescontrol" classid="{06375649-c143-495e-a496-c962e5b4488e}" /></cell></row></rows></section>`+ + `<section name="section_notes"><rows><row><cell><control datafieldname="new_notes" /></cell></row></rows></section>`+ + `</sections></column>`+ + `</columns></tab></tabs></form>`;+ const chk = await topoCheck(xml, (spec) => { spec.forms[0].tabs[0].columns[1].sections[0].name = 'section_notes'; });+ assert.strictEqual(chk.present, true, `the authored section is the one holding its field; got ${chk && chk.detail}`);+});++// A host a maker added a bound field to is no longer engine-owned by structure, yet it still holds the+// timeline — and verify reads FormXML, so it must see the control's classid to know. The build skips such a+// host by name, label and position, so verify must too, or it grades the author's fields against it.+test('verify never matches an authored section to an engine host a maker added a field to', async () => {+ const host = `<section name="section_notes"><labels><label description="Notes" languagecode="1033" /></labels><rows>`+ + `<row><cell><control id="notescontrol" classid="{06375649-C143-495E-A496-C962E5B4488E}" /></cell></row>`+ + `<row><cell><control id="new_x" classid="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}" datafieldname="new_x" /></cell></row></rows></section>`;+ const xml = (second) => `<form><tabs><tab name="tab_overview"><columns>`+ + `<column width="60%"><sections><section name="sec_left"><rows><row><cell><control datafieldname="new_name" /></cell></row></rows></section></sections></column>`+ + `<column width="40%"><sections>${host}${second}</sections></column>`+ + `</columns></tab></tabs></form>`;+ // By name: the author's own section_notes sits after the host.+ const byName = await topoCheck(xml(`<section name="section_notes"><rows><row><cell><control datafieldname="new_notes" /></cell></row></rows></section>`),+ (spec) => { spec.forms[0].tabs[0].columns[1].sections[0].name = 'section_notes'; });+ assert.strictEqual(byName.present, true, `by name; got ${byName && byName.detail}`);+ // By label: the author's section was deployed under another name, and carries the host's label.+ const byLabel = await topoCheck(xml(`<section name="section_x"><labels><label description="Notes" languagecode="1033" /></labels><rows><row><cell><control datafieldname="new_notes" /></cell></row></rows></section>`),+ (spec) => Object.assign(spec.forms[0].tabs[0].columns[1].sections[0], { name: 'sec_renamed', label: 'Notes' }));+ assert.strictEqual(byLabel.present, true, `by label; got ${byLabel && byLabel.detail}`);+});++// Engine-owned is a STRUCTURE (only unbound controls), which cannot say who laid a section out: an+// authored section declared with no fields that a maker filled with a web resource looks the same. Its+// authored name is the evidence it is the author's, so verify finds it by that name — as the build does —+// instead of reporting it absent.+test('verify finds an authored section a maker filled with a control by its name', async () => {+ const xml = `<form><tabs><tab name="tab_overview"><columns>`+ + `<column width="60%"><sections>`+ + `<section name="sec_left"><rows><row><cell><control datafieldname="new_name" /></cell></row></rows></section>`+ + `<section name="sec_related"><rows><row><cell><control id="WebResource_banner" classid="{9FDF5F91-88B1-47f4-AD53-C11EFC01A01D}" /></cell></row></rows></section>`+ + `</sections></column>`+ + `<column width="40%"><sections><section name="sec_right"><rows><row><cell><control datafieldname="new_notes" /></cell></row></rows></section></sections></column>`+ + `</columns></tab></tabs></form>`;+ const chk = await topoCheck(xml, (spec) => { spec.forms[0].tabs[0].columns[0].sections.push({ name: 'sec_related', label: 'Related', fields: [] }); });+ assert.strictEqual(chk.present, true, `the maker's control does not hide the authored section; got ${chk && chk.detail}`);+});++// Verify matches containers exactly as the build does, and the build no longer lets a label or+// position match take a section ANOTHER authored section owns by name (it moves that section to where+// its own want places it). Here the section NAMED sec_wide sits in tab_one holding sec_main's field,+// and an unnamed one in tab_two holds sec_wide's: every field is in the right tab, but a form script+// that addresses sec_wide by name reaches tab_one. Matching sec_main to it by label passed that form.+test('verify: the label pass skips a section another authored section owns by name', async () => {+ const section = (name, label, field) => `<section${name ? ` name="${name}"` : ''}><labels><label description="${label}" languagecode="1033"/></labels>`+ + `<rows><row><cell><control datafieldname="${field}" /></cell></row></rows></section>`;+ const tab = (name, label, sections) => `<tab name="${name}"><labels><label description="${label}" languagecode="1033"/></labels>`+ + `<columns><column width="100%"><sections>${sections}</sections></column></columns></tab>`;+ const twoTabs = (spec) => {+ spec.forms[0].tabs = [+ { name: 'tab_one', label: 'One', columns: [{ width: '100%', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] }] }] },+ { name: 'tab_two', label: 'Two', columns: [{ width: '100%', sections: [{ name: 'sec_wide', label: 'Wide', columns: 1, fields: ['new_notes'] }] }] },+ ];+ };+ const misnamed = `<form><tabs>${tab('tab_one', 'One', section('sec_wide', 'Main', 'new_name'))}${tab('tab_two', 'Two', section(null, 'Wide', 'new_notes'))}</tabs></form>`;+ const chk = await topoCheck(misnamed, twoTabs);+ assert.strictEqual(chk.present, false, 'a form whose sec_wide is in the wrong tab must not verify');+ assert.match(chk.detail, /section 'sec_main' is absent from tab 'tab_one'/);+ // Control: the shape the build produces for that spec verifies.+ const built = `<form><tabs>${tab('tab_one', 'One', section('sec_main', 'Main', 'new_name'))}${tab('tab_two', 'Two', section('sec_wide', 'Wide', 'new_notes'))}</tabs></form>`;+ const ok = await topoCheck(built, twoTabs);+ assert.strictEqual(ok.present, true, `got ${ok.detail}`);+});// --- #N3: the verifier must match containers the way the BUILD does ------------------------------// LIVE-REPRODUCED: reshaping an auto-built form to an explicit layout succeeds — the build reuses// the existing containers and deliberately does NOT rename them, because form scripts and business@@ -1674,3 +1783,133 @@ test('verify PASSES when the field really is in the requested tab', async () =>});assert.strictEqual(chk.present, true, `a real relocation must verify; got ${chk && chk.detail}`);});++// --- #586 item 3: a deployed dashboard must be internally consistent, not merely present ----------+// A chart tile names a table, a view and a chart. The platform accepts and publishes a tile whose+// chart belongs to another table — and a same-named chart elsewhere made the build produce exactly+// that, live, while verify passed. So each chart tile's chart and view must both be on its table.+const DASH_VIEW = '{11111111-1111-1111-1111-111111111111}';+const DASH_CHART = '{22222222-2222-2222-2222-222222222222}';+const dashSpec = () => ({ solution: { uniqueName: 's', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [],+ dashboards: [{ name: 'Ops', tiles: [{ type: 'chart', name: 'By Priority', entity: 'new_ticket', viewId: 'v', visualizationId: 'c' }] }] });+const chartTile = (over) => ({ type: 'chart', name: 'By Priority', parameters: { TargetEntityType: 'new_ticket', ViewId: DASH_VIEW, VisualizationId: DASH_CHART, ...over } });+const dashRead = ({ dashboards = [{ formid: 'dash-1' }], chartTable = 'new_ticket', viewTable = 'new_ticket', components = [chartTile()], reader = {} } = {}) => Object.assign({+ findTable: async () => null,+ findColumns: async () => [],+ sitemapXml: async () => '',+ queryRecords: async (set, q) => {+ if (set === 'systemform') { if (dashboards instanceof Error) throw dashboards; return dashboards; }+ if (set === 'savedqueryvisualization') {+ if (chartTable instanceof Error) throw chartTable;+ assert.match(q.filter, /^savedqueryvisualizationid eq 22222222-2222-2222-2222-222222222222$/, 'the braced tile GUID is queried bare and unquoted');+ return chartTable ? [{ primaryentitytypecode: chartTable }] : [];+ }+ if (set === 'savedquery') return viewTable ? [{ returnedtypecode: viewTable }] : [];+ return [];+ },+ dashboardComponents: async () => { if (components instanceof Error) throw components; return components; },+}, reader);+const dashCheck = async (opts) => (await verifySpec(dashSpec(), dashRead(opts))).checks.find((c) => c.kind === 'dashboard');++test('verify PASSES a dashboard whose chart tile shows its own table\'s view and chart', async () => {+ const chk = await dashCheck();+ assert.strictEqual(chk.present, true, chk.detail);+});++test('verify FAILS a chart tile whose chart belongs to another table (the live cross-wiring)', async () => {+ const chk = await dashCheck({ chartTable: 'new_customer' });+ assert.strictEqual(chk.present, false);+ assert.match(chk.detail, /chart tile 'By Priority' shows new_ticket, but its chart belongs to new_customer/);+});++test('verify FAILS a chart tile whose view belongs to another table, or whose chart no longer exists', async () => {+ assert.match((await dashCheck({ viewTable: 'new_customer' })).detail, /its view belongs to new_customer/);+ assert.match((await dashCheck({ chartTable: null })).detail, /its chart does not exist/);+});++test('verify FAILS a missing dashboard, and an ambiguous name it cannot identify', async () => {+ assert.strictEqual((await dashCheck({ dashboards: [] })).present, false);+ const ambiguous = await dashCheck({ dashboards: [{ formid: 'a' }, { formid: 'b' }] });+ assert.strictEqual(ambiguous.present, false);+ assert.match(ambiguous.detail, /2 dashboards share this name and this app's solution cannot say which is its own/);+});++// A name can also match another app's dashboard. The build reuses the one the app's solution holds, so+// verify checks THAT one — a namesake elsewhere must neither fail a correct app nor hide a broken one.+test('verify checks the dashboard the app\'s solution holds when a namesake exists elsewhere', async () => {+ const withSolution = (inSolution, onComponents) => ({+ reader: {+ queryRecords: async (set, q) => {+ if (set === 'systemform') return [{ formid: 'dash-foreign' }, { formid: 'dash-ours' }];+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ if (set === 'solutioncomponent') return inSolution.filter((id) => q.filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));+ return dashRead().queryRecords(set, q);+ },+ dashboardComponents: async (id) => { onComponents.push(id); return [chartTile()]; },+ },+ });+ const read = [];+ const ok = await dashCheck(withSolution(['dash-ours'], read));+ assert.strictEqual(ok.present, true, ok.detail);+ assert.deepStrictEqual(read, ['dash-ours'], 'the tiles checked are the solution\'s dashboard, not the first match');+ const none = await dashCheck(withSolution([], []));+ assert.strictEqual(none.present, false);+ assert.match(none.detail, /none of them is in this app's solution/);+});++// The sitemap subarea check resolves its dashboard the SAME way. It used to take the first name match:+// live, another app's same-named dashboard sorted first and failed a correctly wired app's nav entry.+test('the dashboard subarea check follows the app\'s solution too, never the first name match', async () => {+ const OURS = 'aaaaaaaa-0000-0000-0000-000000000002';+ const FOREIGN = 'aaaaaaaa-0000-0000-0000-000000000001';+ const spec = { ...dashSpec(), appShell: { areas: [{ groups: [{ subAreas: [{ dashboard: 'Ops', title: 'Ops nav' }] }] }] } };+ const subarea = async (inSolution, sitemapPointsAt, systemforms = [{ formid: FOREIGN }, { formid: OURS }]) => {+ const lookups = [];+ const read = dashRead({ reader: {+ queryRecords: async (set, q) => {+ if (set === 'systemform') { lookups.push(q); if (systemforms instanceof Error) throw systemforms; return systemforms; }+ if (set === 'solution') return [{ solutionid: 'sol-1' }];+ if (set === 'solutioncomponent') {+ if (inSolution instanceof Error) throw inSolution;+ return inSolution.filter((id) => q.filter.includes(`objectid eq ${id}`)).map((objectid) => ({ objectid }));+ }+ return dashRead().queryRecords(set, q);+ },+ sitemapXml: async () => `<SiteMap><Area><SubArea Id="s" DefaultDashboard="{${sitemapPointsAt.toUpperCase()}}"/></Area></SiteMap>`,+ } });+ const r = await verifySpec(spec, read);+ return { chk: r.checks.find((c) => c.kind === 'subarea'), lookups };+ };+ const ok = await subarea([OURS], OURS);+ assert.strictEqual(ok.chk.present, true, `a nav entry wired to the app's own dashboard verifies; got ${ok.chk.detail}`);+ assert.strictEqual(ok.lookups.length, 1, 'the dashboard check and the subarea check share one lookup per name');+ assert.strictEqual(ok.lookups[0].paginate, true, 'read in full, not one page of ten the app\'s own could sort beyond');+ assert.strictEqual((await subarea([OURS], FOREIGN)).chk.present, false, 'a nav entry wired to another app\'s namesake does not');+ const unknown = (await subarea([], OURS)).chk;+ assert.strictEqual(unknown.present, false);+ assert.match(unknown.detail, /2 dashboards share this name and none of them is in this app's solution/);+ const cannotAsk = (await subarea(new Error('HTTP 503'), OURS)).chk;+ assert.strictEqual(cannotAsk.present, false, 'an unreadable solution proves nothing');+ assert.match(cannotAsk.detail, /this app's solution cannot say which is its own \(HTTP 503\)/);+ const unreadable = (await subarea([OURS], OURS, new Error('boom'))).chk;+ assert.strictEqual(unreadable.present, false);+ assert.match(unreadable.detail, /unverified, not proven correct/);+});++test('verify reports unreadable dashboards, tiles and tile targets as UNVERIFIED, never as correct', async () => {+ for (const opts of [{ dashboards: new Error('boom') }, { components: new Error('boom') }, { chartTable: new Error('boom') }]) {+ const chk = await dashCheck(opts);+ assert.strictEqual(chk.present, false, JSON.stringify(Object.keys(opts)));+ assert.match(chk.detail, /unverified, not proven correct/);+ }+});++test('verify checks dashboard EXISTENCE only when the reader cannot read tiles (additive, reader-gated)', async () => {+ const chk = await dashCheck({ reader: { dashboardComponents: undefined } });+ assert.strictEqual(chk.present, true);+});++test('verify ignores non-chart tiles when proving a dashboard', async () => {+ const chk = await dashCheck({ components: [{ type: 'list', name: 'L', parameters: { TargetEntityType: 'new_ticket', ViewId: DASH_VIEW } }, { type: 'iframe', name: 'I', parameters: { Url: 'https://x' } }] });+ assert.strictEqual(chk.present, true, chk.detail);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex fde604f07..9f4ca7044 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -10,6 +10,7 @@const fs = require('node:fs');const path = require('node:path');+const os = require('node:os');const { parseArgs, validateFlags, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');const { verifySpec } = require('./lib/verify-spec.js');@@ -19,9 +20,31 @@ const { odataLit } = require('./lib/odata.js');const { makeGenpageCli } = require('./lib/genpage-cli.js');const { depthFromMask } = require('./lib/role-privileges.js');-async function makeProvision(env, workspaceDir) {+// A throwaway SDK workspace for ONE dashboard read (readerFor's dashboardComponents), deleted after it. The tiles+// verify checks must be the server's: read through the build's own workspace, a copy holding unpushed edits — or+// one another writer changed mid-read — was what got verified, and a forced refresh there could discard a+// concurrent writer's edit. A fresh workspace has no local copy to read, discard or race with, and a fresh SDK no+// cached read to hand back. One per read, not per run: a second read of the same dashboard must not come from+// the first one's cache. The HTTP client — and with it the Azure CLI token — is shared: `opts.httpClient` (the+// run's own), else one made on the first read. A client per read ran `az account get-access-token` once per+// dashboard. `opts.makeClient` is a test seam.+function isolatedReaderFor(env, opts = {}) {+ let client = opts.httpClient || null;+ const makeClient = opts.makeClient || createAzHttpClient;+ return async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-dashboard-'));+ try {+ const sdk = await makeProvision(env, dir, client || (client = makeClient(env)));+ return { sdk, dispose: () => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } } };+ } catch (e) {+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }+ throw e;+ }+ };+}++async function makeProvision(env, workspaceDir, httpClient = createAzHttpClient(env)) {const { createMakerSdk, createNodeWorkspaceStorage } = require('./vendor/cds-maker-sdk.cjs');- const httpClient = createAzHttpClient(env);fs.mkdirSync(workspaceDir, { recursive: true });const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });await sdk.initWorkspace();@@ -247,6 +270,64 @@ function readerFor(sdk, appUnique, opts) {const row = rows && rows[0];return (row && row.formxml) || null;},+ // dashboardComponents(dashboardId): the deployed dashboard's tiles, parsed by the SDK's own+ // dashboard deserializer — the path download already reads them through — so verify sees each+ // tile's TargetEntityType / ViewId / VisualizationId exactly as a rebuild would, instead of+ // regex-parsing FormXML a second way. Errors propagate: verify reports unreadable tiles as+ // unverified, never as correct.+ //+ // What is checked must be what users see: the PUBLISHED dashboard. The SDK's dashboard read is the+ // unpublished draft (RetrieveUnpublished), and verify runs in the build's workspace, where a plain fetch+ // keeps a copy holding unpushed edits while the server has not moved — so a fix saved in Maker but not+ // published, or never pushed at all, passed while users still saw the broken dashboard. The deserializer+ // is kept (download reads tiles through it, and a second FormXML parser would drift from it), and the+ // read is refused unless it IS the published dashboard: the server's draft FormXML is the published row's —+ // both before AND after the fetch the tiles come from (checked only after it, a draft the fetch had cached+ // and a maker then discarded passed, while the published dashboard was broken throughout). The fetch goes into+ // a throwaway workspace (opts.isolatedReader — isolatedReaderFor), never the build's, whose copy may hold+ // unpushed edits or be written by another process mid-read. Callers without one (tests) read through `sdk`.+ //+ // Equal FormXML before and after does not prove the fetch between them read it: a draft saved and then put+ // back (A, then B, then A again) leaves both checks reading A while the fetch read B, and B's tiles passed. So+ // each check also takes the draft's `@odata.etag`, which RetrieveUnpublished returns in the body and which+ // moves on every write to the draft, even one that restores its content (live-measured; the SDK guards its own+ // form writes on the same token). The same token before and after means nothing was written in between, so+ // the fetch read the document both checks compared with the published row. A read with no token is refused,+ // like one with no FormXML.+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/retrieveunpublished+ // and https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api+ dashboardComponents: async (dashboardId) => {+ const publishedDashboard = async () => {+ const [row] = (await sdk.queryRecords('systemform', { select: ['formid', 'formxml'], filter: `formid eq ${dashboardId}`, top: 1 })) || [];+ const draft = await sdk.dataverse.get(`/systemforms(${dashboardId})/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml`);+ // `dataverse.get` RESOLVES on a non-2xx, so the status is checked explicitly.+ if (!draft || draft.status < 200 || draft.status >= 300) throw new Error(`the draft of dashboard ${dashboardId} could not be read (HTTP ${draft && draft.status})`);+ const draftXml = draft.body && draft.body.formxml;+ if (!row || typeof row.formxml !== 'string' || typeof draftXml !== 'string') throw new Error(`the FormXML of dashboard ${dashboardId} could not be read`);+ if (draftXml !== row.formxml) throw new Error(`dashboard ${dashboardId} has changes that are not published — publish it, then verify`);+ const version = draft.body['@odata.etag'];+ if (typeof version !== 'string' || version === '') throw new Error(`the version of dashboard ${dashboardId} could not be read`);+ return { xml: row.formxml, version };+ };+ const before = await publishedDashboard();+ const reader = opts.isolatedReader ? await opts.isolatedReader() : { sdk, dispose: () => {} };+ let art;+ try {+ await reader.sdk.fetchArtifact('dashboard', dashboardId);+ art = await reader.sdk.getArtifact('dashboard', dashboardId);+ } finally {+ reader.dispose();+ }+ const after = await publishedDashboard();+ if (after.xml !== before.xml || after.version !== before.version) throw new Error(`dashboard ${dashboardId} changed while it was being read — verify again`);+ // No artifact, or a component list that is not a list, is not "no tiles": throw, so verify reports the+ // dashboard unverified instead of passing a check that read nothing. An artifact with no list at all+ // has no tiles, as download-model-app.js reads it.+ if (!art || (art.components !== undefined && !Array.isArray(art.components))) {+ throw new Error(`the SDK returned ${art ? 'a malformed component list' : 'no artifact'} for dashboard ${dashboardId}`);+ }+ return art.components || [];+ },// sitemapXml (string, fail-closed '') for entity/icon hasElement checks — from the discriminated sitemap// read. Returning '' on failure suppresses entity/icon checks without aborting the whole verify.sitemapXml: async () => { const r = await memoSitemap(); return r.ok ? r.xml : ''; },@@ -378,9 +459,10 @@ async function main() {const v = validateAppSpec(spec, { profile: 'deploy' });if (!v.ok) { emitResult(false, { ok: false, errors: v.errors }); return; }const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');- const sdk = await makeProvision(env, workspaceDir);+ const httpClient = createAzHttpClient(env);+ const sdk = await makeProvision(env, workspaceDir, httpClient);const genpageCli = makeGenpageCli(env);- const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir }));+ const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }));// Show `detail` on a failing check. Without it a READ that failed (throttling, auth expiry, a 5xx)// is indistinguishable from an artifact that is genuinely absent — verifySpec records the cause// but the operator saw only "✗ view: Active Orders" and would chase a phantom deployment drift.@@ -395,4 +477,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { sitemapXmlFor, readerFor, appIdFor, appRoleIdsFor };+module.exports = { sitemapXmlFor, readerFor, appIdFor, appRoleIdsFor, isolatedReaderFor };diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 58b5d53c3..9920e57a6 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -216,6 +216,10 @@ unless destructive authority was supplied independently.`"Severity 1-5; drives the escalation rule and the SLA clock"`, not `"The priority column"`.(`commands[]` and `Customer` columns accept one but the SDK cannot write it — you'll get awarning; `personas[]` does not take one at all. See the schema reference for why.)+ The app itself takes two: `app.description` is the short tile text, and `app.aiDescription` is+ the **routing description** an orchestrator reads to choose between apps — who the app is for,+ what it covers and excludes, and how to tell it from a sibling app over the same tables. Write+ it whenever such a sibling exists or is planned.- **Level (b) — artifacts + page-intents + design**: **enumerate every surface each job needs andclassify it** per the genpage-first policy above — record CRUD → form + view; anything else(overview/landing, dashboard, KPIs, analytics, guided/wizard flow, composite or comparison@@ -432,7 +436,12 @@ table's privileges can block that table's delete. Commandteardown removes the whole command bar for any entity the spec authored commands on. **Teardown onlydeletes tables this build created** — a **system/standard table** (account, contact, …) isauto-detected and **skipped**, and a **reused custom table** is skipped when its entity is flagged-`"existing": true`, so pre-existing data survives. **Dry-run by default**; add `--apply+`"existing": true`, so pre-existing data survives. The same flag protects **relationships and global+choices** — a download sets it on every one it recovers, so tearing down a downloaded spec never removes+a lookup column from a retained table or deletes a shared option set. Dashboards are found by name, so+teardown deletes only those the app's solution holds, never another app's namesake — and none when the spec+has no real solution to ask (the `Default` a download may leave); it keeps the solution itself while any step+failed, so a re-run can still tell. **Dry-run by default**; add `--apply--allow-destructive` to actually delete (`--clear-workspace` also prunes `.maker-workspace/`).**`--allow-destructive` is required for `teardown --apply`** — without it teardown refuses andtouches nothing.